Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(model-hunyuan3d): Hunyuan3D 2.1 worker lane (Dockerfile, app, cloudbuild)

nirholas34ab896b4dfc
diff --git a/workers/model-hunyuan3d/Dockerfile.hunyuan21 b/workers/model-hunyuan3d/Dockerfile.hunyuan21
new file mode 100644
index 000000000..90d48e398
--- /dev/null
+++ b/workers/model-hunyuan3d/Dockerfile.hunyuan21
@@ -0,0 +1,82 @@
+# Hunyuan3D-2.1 PBR image-to-3D worker.
+#
+# CUDA 12.4 devel base (matches Tencent's own docker/Dockerfile): the paint
+# stack compiles two in-tree extensions at build time — custom_rasterizer (CUDA)
+# and DifferentiableRenderer's mesh_inpaint_processor (pybind11) — and needs
+# nvcc + a C++ toolchain. TORCH_CUDA_ARCH_LIST targets the Cloud Run L4 (compute
+# capability 8.9) so the kernels build for it.
+FROM nvidia/cuda:12.4.1-devel-ubuntu22.04
+
+ENV PYTHONDONTWRITEBYTECODE=1 \
+ PYTHONUNBUFFERED=1 \
+ PIP_NO_CACHE_DIR=1 \
+ DEBIAN_FRONTEND=noninteractive \
+ TORCH_CUDA_ARCH_LIST="8.9+PTX" \
+ CUDA_NVCC_FLAGS="-allow-unsupported-compiler" \
+ CUDA_HOME=/usr/local/cuda \
+ PYOPENGL_PLATFORM=egl
+
+# System libs: build toolchain for the extensions, plus the GL/EGL/X stack that
+# headless Blender (bpy, imported by DifferentiableRenderer.mesh_utils) and the
+# EGL rasterizer link against at import/runtime.
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ python3.10 python3.10-dev python3-pip \
+ git curl wget build-essential ninja-build cmake pkg-config \
+ libeigen3-dev \
+ libgl1 libglib2.0-0 libegl1 libgles2 libglvnd0 libglvnd-dev \
+ libgl1-mesa-dev libegl1-mesa-dev libgles2-mesa-dev \
+ libxrender1 libxi6 libsm6 libxext6 libxkbcommon0 libxfixes3 \
+ && rm -rf /var/lib/apt/lists/* \
+ && ln -sf /usr/bin/python3.10 /usr/bin/python3 \
+ && ln -sf /usr/bin/python3.10 /usr/bin/python \
+ && pip install --upgrade pip setuptools wheel
+
+# torch first (cached layer), from the CUDA 12.4 wheel index to match the base.
+RUN pip install torch==2.5.1 torchvision==0.20.1 torchaudio==2.5.1 \
+ --index-url https://download.pytorch.org/whl/cu124
+
+COPY requirements.hunyuan21.txt /app/requirements.txt
+RUN pip install -r /app/requirements.txt
+
+# The 2.1 code (hy3dshape + hy3dpaint packages) is cloned in-tree from a pinned
+# Tencent-Hunyuan/Hunyuan3D-2.1 commit — the texgen extensions must be compiled
+# from this tree, and a moving `main` breaks the reproducibility bar. Build the
+# CUDA rasterizer (editable, so its .so lives in-tree) and the pybind11 mesh
+# inpaint processor, then fetch the RealESRGAN super-res checkpoint the paint
+# pass upscales its PBR views with.
+RUN git clone https://github.com/Tencent-Hunyuan/Hunyuan3D-2.1.git /opt/hunyuan3d21 \
+ && cd /opt/hunyuan3d21 \
+ && git checkout 82920d643c0dc2f7bfd7255f45f62d386edfe60c \
+ && cd hy3dpaint/custom_rasterizer \
+ && pip install --no-build-isolation -e . \
+ && cd ../DifferentiableRenderer \
+ && bash compile_mesh_painter.sh \
+ && cd /opt/hunyuan3d21/hy3dpaint \
+ && mkdir -p ckpt \
+ && wget -q https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth -P ckpt
+
+# Fail the BUILD (not a live deploy) if the dependency stack drifts: every
+# import the loader pulls before it touches the GPU must resolve. CUDA is not
+# initialised here (no GPU at build), so the smoke test stays to pure-python +
+# .so loads and skips modules that init CUDA on import.
+RUN cd /opt/hunyuan3d21 && python -c "\
+import sys; sys.path.insert(0,'.'); sys.path.insert(0,'hy3dshape'); sys.path.insert(0,'hy3dpaint'); \
+import torch, torchvision, transformers, diffusers, trimesh, bpy, cv2, pygltflib, custom_rasterizer; \
+from torchvision_fix import apply_fix; apply_fix(); \
+from hy3dshape.pipelines import Hunyuan3DDiTFlowMatchingPipeline; \
+from hy3dpaint.convert_utils import create_glb_with_pbr_materials; \
+print('deps ok:', torch.__version__, torchvision.__version__, transformers.__version__, diffusers.__version__)"
+
+# The worker runs from the repo root: the paint config references cfg/ckpt files
+# by repo-relative path, so cwd must be /opt/hunyuan3d21.
+WORKDIR /opt/hunyuan3d21
+COPY worker_security.py /opt/hunyuan3d21/worker_security.py
+COPY app21.py /opt/hunyuan3d21/app21.py
+
+EXPOSE 8080
+
+CMD ["uvicorn", "app21:app", \
+ "--host", "0.0.0.0", \
+ "--port", "8080", \
+ "--workers", "1", \
+ "--timeout-keep-alive", "300"]
diff --git a/workers/model-hunyuan3d/README.md b/workers/model-hunyuan3d/README.md
index 81797c91d..f357edf3b 100644
--- a/workers/model-hunyuan3d/README.md
+++ b/workers/model-hunyuan3d/README.md
@@ -1,35 +1,50 @@
-# model-hunyuan3d — single image → textured 3D mesh (Hunyuan3D-2.1)
-
-FastAPI inference service that turns **one image into a textured GLB** using
-Tencent [Hunyuan3D-2.1](https://github.com/Tencent/Hunyuan3D-2). It runs the
-model in two stages: a shape pipeline (`Hunyuan3DDiTFlowMatchingPipeline`,
-subfolder `hunyuan3d-dit-v2-1`, 30 steps, guidance 5.5, octree resolution 256)
-produces the mesh, then a texture pipeline (`Hunyuan3DPaintPipeline`, subfolder
-`hunyuan3d-paint-v2-1`, 20 steps, guidance 7.5) paints it. Both load in `float16`
-on one NVIDIA L4 on Cloud Run. This is the highest-fidelity mesh backend in the
-platform's own GPU fleet — heavier and slower than
-[`model-trellis`](../model-trellis/), chosen when geometry quality matters more
-than latency.
-
-Work is asynchronous: `POST /infer` returns `202` with a `task_id`, and the
-caller polls `GET /tasks/{id}` until the GLB is written to
-`gs://$GCS_BUCKET/raw-meshes/hunyuan3d/{task_id}.glb` and served back as an
-`https://storage.googleapis.com/…` URL. Task state is in-memory, so it does not
-survive a restart or scale-to-zero — poll promptly, don't treat it as durable.
+# model-hunyuan3d — single image → textured 3D mesh (Hunyuan3D)
+
+FastAPI inference workers that turn **one image into a textured GLB** with
+Tencent's Hunyuan3D. Two model generations run side by side as **two separate
+Cloud Run services**, because their Python stacks are mutually incompatible
+(torch 2.3 / cu121 + `hy3dgen` for 2.0 vs torch 2.5 / cu124 +
+`hy3dshape` / `hy3dpaint` for 2.1):
+
+| Service | Model | Entry point | Dockerfile | Output material |
+|---|---|---|---|---|
+| `model-hunyuan3d` | Hunyuan3D-2.0 | [`main.py`](./main.py) | [`Dockerfile`](./Dockerfile) | single baked diffuse texture |
+| `model-hunyuan3d-21` | **Hunyuan3D-2.1** | [`app21.py`](./app21.py) | [`Dockerfile.hunyuan21`](./Dockerfile.hunyuan21) | **PBR: baseColor + metallicRoughness + normal** |
+
+**2.1 is the realism lane.** It runs the `hy3dshape` shape DiT, then the
+`hy3dpaint` PBR paint pass (multiview PBR diffusion → RealESRGAN super-res →
+texture bake → inpaint), and exports a GLB with a true physically-based material
+set. PBR maps are what make a render read as a real photographed object under
+real lighting instead of a flat plastic toy — the single biggest realism lever
+in the platform's own GPU fleet. 2.0 remains deployed and untouched as the
+instant fallback lane: to roll back, repoint `GCP_HUNYUAN3D_URL` at the
+`model-hunyuan3d` service URL — no rebuild.
+
+Both services speak the **same wire contract**, so either URL drops straight
+into the platform's `GCP_HUNYUAN3D_URL` env.
+
+## License
+
+Hunyuan3D-2.1 is released under the **TENCENT HUNYUAN NON-COMMERCIAL LICENSE
+AGREEMENT** (the full text ships in the weights bucket at
+`gs://three-ws-model-weights/hunyuan3d-2.1/LICENSE` and in the cloned repo). This
+worker performs **self-hosted inference on our own GPU infrastructure**, exactly
+as the 2.0 lane already runs in production. The RealESRGAN super-res checkpoint
+and DINOv2 reference encoder carry their own upstream licenses (BSD-3 and Apache
+2.0 respectively). No weights or model code are redistributed by the platform;
+only generated GLBs are returned to callers.
## Endpoints
-`POST /infer` and `GET /tasks/{id}` require `Authorization: Bearer $API_KEY`.
-`GET /health` is unauthenticated.
+`POST /infer`, `POST /reconstruct`, `GET /tasks/{id}`, `GET /jobs/{id}` require
+`Authorization: Bearer $API_KEY`. `GET /health` is unauthenticated.
### `POST /infer` → `202`
-Request:
-
```json
{
- "images": ["https://example.com/statue.png"],
- "body_type": "neutral",
+ "images": ["https://example.com/portrait.png"],
+ "tier": "high",
"job_id": "abc123"
}
```
@@ -38,14 +53,14 @@ Request:
URL. **Only the first is used.** `https` sources go through the SSRF guard in
[`worker_security.py`](./worker_security.py) (https-only; private, loopback,
link-local, and cloud-metadata IPs rejected on every redirect hop).
-- `body_type` — optional, default `"neutral"` (accepted, not used by the model).
+- `tier` — `draft` | `standard` | `high` (default `high`). Selects the
+ generation budget (see below).
- `job_id` — optional correlation string.
-Response:
+Response: `{ "task_id": "3f2c…", "status": "queued" }`.
-```json
-{ "task_id": "3f2c…", "status": "queued" }
-```
+`POST /reconstruct` accepts the same body and additionally echoes `job_id`, for
+the avatar controller's `/reconstruct` + `/jobs/:id` wire shape.
### `GET /tasks/{task_id}`
@@ -57,108 +72,142 @@ Response:
"status": "done",
"model": "hunyuan3d-2.1",
"result_gcs_url": "https://storage.googleapis.com/three-ws-avatar-reconstructions/raw-meshes/hunyuan3d/3f2c….glb",
- "elapsed_ms": 92140
+ "elapsed_ms": 224140
}
```
-Failures carry a sanitized `error` string; unknown ids return `404`.
+Task state is persisted to a durable `tasks/{id}.json` GCS blob on every
+transition, so a `POST /infer` and a later `GET /tasks/:id` that land on
+different Cloud Run instances still resolve the same record. Failures carry a
+sanitized `error` string; unknown ids return `404`.
### `GET /health`
```json
-{
- "ok": true,
- "model": "hunyuan3d-2.1",
- "gpu_available": true,
- "gpu_name": "NVIDIA L4",
- "pipeline_loaded": true
-}
+{ "ok": true, "model": "hunyuan3d-2.1", "gpu_available": true, "gpu_name": "NVIDIA L4",
+ "pipeline_loaded": true, "ready": true, "load_error": null }
```
-Both pipelines (~10 GB) load **synchronously** during ASGI startup, so the
-instance only becomes ready — and only answers the probe — after the load
-completes.
+The pipeline loads in the **background** after the HTTP port opens, so the
+instance answers `/health` immediately; `ready` flips to `true` once the shape +
+paint models finish loading, and `load_error` carries a sanitized string if the
+load failed.
-## Environment
+## Quality tiers (2.1)
-| Var | Required | Default | Purpose |
-|---|---|---|---|
-| `API_KEY` | yes | — | Shared bearer secret (Secret Manager `avatar-reconstruction-key`) |
-| `GCS_BUCKET` | yes | — | Cloud Storage bucket for output meshes (`three-ws-avatar-reconstructions`) |
-| `WEIGHTS_DIR` | no | `/weights/hunyuan3d-2.1` | Local path to weights (mounted GCS volume in prod) |
-| `MAX_CONCURRENT` | no | `1` | In-flight inferences; one L4 fits exactly one |
+Quality over speed — GPU time is cheap against the platform's GCP credit budget.
+The budget splits across the shape DiT (inference steps + marching-cubes octree
+resolution) and the PBR paint pass (multiview count + per-view diffusion
+resolution). The paint texture atlas is fixed high at load (render 2048, texture
+4096).
-Weights are **not** baked into the image — the `three-ws-model-weights` bucket is
-mounted read-only at `/weights`. Pre-populate once with:
+| Tier | shape steps | octree | paint views | paint resolution |
+|---|---|---|---|---|
+| `draft` | 30 | 256 | 6 | 512 |
+| `standard` | 50 | 384 | 6 | 512 |
+| `high` (default) | 50 | 512 | 6 | 768 |
-```bash
-pip install huggingface_hub
-huggingface-cli download tencent/Hunyuan3D-2.1 --local-dir /tmp/hunyuan3d-2.1
-gsutil -m cp -r /tmp/hunyuan3d-2.1 gs://three-ws-model-weights/hunyuan3d-2.1/
-```
+`high` holds the multiview count at 6 so the paint pass fits the L4's 24 GiB
+VRAM alongside the shape DiT, DINOv2, and RealESRGAN, while pushing the shape
+octree and per-view diffusion resolution up for sharper geometry and PBR maps.
-## Run locally
+## Environment (2.1)
-Requires a CUDA GPU and the Hunyuan3D-2.1 weights on disk. The `hy3dgen` texture
-pipeline compiles CUDA extensions (`custom_rasterizer`, `differentiable_renderer`)
-at install time, so the reproducible way to run it is the image:
+| Var | Required | Default | Purpose |
+|---|---|---|---|
+| `API_KEY` | yes | — | Shared bearer secret (Secret Manager `avatar-reconstruction-key`) |
+| `GCS_BUCKET` | yes | — | Output-mesh bucket (`three-ws-avatar-reconstructions`) |
+| `HUNYUAN3D_MODEL` | no | `2.1` | Pins the image's lane |
+| `WEIGHTS_GCS_URI` | no | — | `gs://` prefix of the 2.1 weight tree to stage locally |
+| `WEIGHTS_LOCAL_DIR` | no | `/tmp/hunyuan3d-2.1` | Local staging dir for the 2.1 weights |
+| `WEIGHTS_DIR` | no | `/weights/hunyuan3d-2.1` | FUSE-mount fallback for the 2.1 weights |
+| `DINO_GCS_URI` | no | — | `gs://` prefix of `facebook/dinov2-giant` to stage locally |
+| `DINO_LOCAL_DIR` | no | `/tmp/dinov2-giant` | Local staging dir for DINOv2 |
+| `DINO_DIR` | no | `/weights/dinov2-giant` | FUSE-mount fallback for DINOv2 |
+| `MAX_CONCURRENT` | no | `1` | In-flight inferences; one L4 fits one |
+
+**Weight staging.** The 2.1 shape DiT is a single 6.9 GiB `.ckpt` and the paint
+UNet a single 3.7 GiB `.bin`. Reading files that large over the Cloud Storage
+FUSE mount stalls indefinitely (the failure the 2.0 lane already hit and fixed),
+so the worker streams the needed subtrees to local disk with the storage client
+(a plain sequential GET, which does not stall) and loads from there. Staging is
+gated on `WEIGHTS_GCS_URI` / `DINO_GCS_URI` and degrades to the FUSE mount on any
+failure — it never crashes the loader.
+
+## Stage the weights (one-time)
+
+The `three-ws-model-weights` bucket already holds both trees. To (re)populate:
```bash
-cd workers/model-hunyuan3d
-docker build -t model-hunyuan3d .
-
-docker run --rm --gpus all -p 8080:8080 \
- -e API_KEY=dev-secret \
- -e GCS_BUCKET=your-dev-bucket \
- -e WEIGHTS_DIR=/weights/hunyuan3d-2.1 \
- -e GOOGLE_APPLICATION_CREDENTIALS=/gcp/sa.json \
- -v /path/to/hunyuan3d-2.1:/weights/hunyuan3d-2.1:ro \
- -v /path/to/sa.json:/gcp/sa.json:ro \
- model-hunyuan3d
-```
+pip install "huggingface_hub[cli]"
-With the `hy3dgen` environment already installed you can run the server directly:
+# 2.1 shape + PBR paint + VAE weights (~14 GiB)
+hf download tencent/Hunyuan3D-2.1 --local-dir /tmp/hunyuan3d-2.1
+gcloud storage rsync --recursive /tmp/hunyuan3d-2.1 gs://three-ws-model-weights/hunyuan3d-2.1
-```bash
-API_KEY=dev-secret GCS_BUCKET=your-dev-bucket WEIGHTS_DIR=/path/to/hunyuan3d-2.1 \
- uvicorn main:app --host 0.0.0.0 --port 8080
+# DINOv2 reference encoder for the paint pass (~4.4 GiB)
+hf download facebook/dinov2-giant --local-dir /tmp/dinov2-giant
+gcloud storage rsync --recursive /tmp/dinov2-giant gs://three-ws-model-weights/dinov2-giant
```
+The RealESRGAN super-res checkpoint is fetched into the image at build time
+(`hy3dpaint/ckpt/RealESRGAN_x4plus.pth`).
+
## Deploy
-Submit from the **repo root** — the build step declares `dir: workers/model-hunyuan3d`,
-so the upload source is the whole repo:
+Submit from the **repo root** (the build step declares
+`dir: workers/model-hunyuan3d`, so the upload source is the whole repo). Pass
+`SHORT_SHA` explicitly — `gcloud builds submit` does not auto-populate it:
```bash
-gcloud builds submit --config workers/model-hunyuan3d/cloudbuild.yaml .
+# 2.1 (model-hunyuan3d-21)
+gcloud builds submit --config workers/model-hunyuan3d/cloudbuild.hunyuan21.yaml \
+ --substitutions=SHORT_SHA=21-$(git rev-parse --short HEAD) .
+
+# 2.0 (model-hunyuan3d) — legacy fallback lane
+gcloud builds submit --config workers/model-hunyuan3d/cloudbuild.yaml \
+ --substitutions=SHORT_SHA=$(git rev-parse --short HEAD) .
```
-Or provision it alongside the rest of the fleet (idempotent; prints the URLs to
-set on the `three-ws-api` service env):
+The 2.1 service deploys in `us-central1`: **1× `nvidia-l4` GPU** (no zonal
+redundancy), 8 vCPU, 32 GiB, 900 s request timeout, `min-instances=1` (kept warm
+so no request pays the multi-GiB weight load), `max-instances=1`. Build/runtime
+service accounts are pinned (`three-ws-build@` / `avatar-reconstruction-sa@`) —
+the project's default compute SA was deleted. The custom_rasterizer CUDA compile
+plus the bpy/torch install push the build past the default timeout, so
+`timeout: 3600s`.
+
+## Wire it into the platform
+
+The platform points **`GCP_HUNYUAN3D_URL`** at whichever service should serve
+the Hunyuan3D `/forge` tier. After verifying the 2.1 service end to end:
```bash
-PROJECT_ID=<gcp-project> SERVICES="hunyuan3d trellis triposg unirig" \
- workers/deploy/deploy-all.sh
+gcloud run services update three-ws-api --region us-central1 \
+ --update-env-vars GCP_HUNYUAN3D_URL=https://model-hunyuan3d-21-XXXXXXX-uc.a.run.app
```
-Deploys Cloud Run service **`model-hunyuan3d`** in `us-central1`: **1× `nvidia-l4`
-GPU** (no zonal redundancy), 8 vCPU, 32 GiB, 900 s request timeout,
-`min-instances=0` (scales to zero — the first request after idle pays a real cold
-start), `max-instances=3`. The build `timeout` is `3600s` because the texture
-pipeline's CUDA extensions compile for the L4 (`TORCH_CUDA_ARCH_LIST=8.9+PTX`).
-Weights bucket mounted at `/weights`; `API_KEY` from the `avatar-reconstruction-key`
-secret.
+**Always `--update-env-vars`, never `--set-env-vars`** — the latter wipes every
+other env var on the shared `three-ws-api` service. To fall back to 2.0, repoint
+the same var at the `model-hunyuan3d` service URL. The tier is declared in
+[`api/_lib/forge-tiers.js`](../../api/_lib/forge-tiers.js)
+(`requiresEnv: ['GCP_HUNYUAN3D_URL', 'GCP_RECONSTRUCTION_KEY']`), routed by
+[`api/forge.js`](../../api/forge.js), health-probed by
+[`api/_lib/forge-health.js`](../../api/_lib/forge-health.js), and the
+[avatar-pipeline-controller](../avatar-pipeline-controller/) also selects it as a
+mesh backend via `MODEL_HUNYUAN3D_URL`. All workers share the platform-side
+bearer secret `GCP_RECONSTRUCTION_KEY`, which must equal each service's
+`API_KEY`.
## Example — submit, poll, fetch
```bash
-BASE=https://model-hunyuan3d-xxxxxxxx-uc.a.run.app
+BASE=https://model-hunyuan3d-21-XXXXXXX-uc.a.run.app
KEY=your-api-key
TASK=$(curl -s -X POST "$BASE/infer" \
- -H "Authorization: Bearer $KEY" \
- -H 'Content-Type: application/json' \
- -d '{"images":["https://storage.googleapis.com/three-ws-public/samples/statue.png"]}' \
+ -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \
+ -d '{"images":["https://example.com/portrait.png"],"tier":"high"}' \
| python3 -c 'import sys,json; print(json.load(sys.stdin)["task_id"])')
while :; do
@@ -166,21 +215,6 @@ while :; do
echo "$STATE"
echo "$STATE" | grep -q '"status": *"done"' && break
echo "$STATE" | grep -q '"status": *"failed"' && exit 1
- sleep 5
+ sleep 10
done
-
-curl -s "$BASE/tasks/$TASK" -H "Authorization: Bearer $KEY" \
- | python3 -c 'import sys,json; print(json.load(sys.stdin)["result_gcs_url"])'
```
-
-## How three.ws calls it
-
-The platform points **`GCP_HUNYUAN3D_URL`** at this service. It runs on its own
-Cloud Run worker (never the avatar pipeline) and is invoked directly by
-[`api/forge.js`](../../api/forge.js) for the Hunyuan3D `/forge` tier, which
-[`api/_lib/forge-tiers.js`](../../api/_lib/forge-tiers.js) declares with
-`requiresEnv: ['GCP_HUNYUAN3D_URL', 'GCP_RECONSTRUCTION_KEY']`. Health is probed
-in [`api/_lib/forge-health.js`](../../api/_lib/forge-health.js), and the
-[avatar-pipeline-controller](../avatar-pipeline-controller/) also selects it as a
-mesh backend via its own `MODEL_HUNYUAN3D_URL`. All workers share the platform-side
-bearer secret `GCP_RECONSTRUCTION_KEY`, which must equal this service's `API_KEY`.
diff --git a/workers/model-hunyuan3d/app21.py b/workers/model-hunyuan3d/app21.py
new file mode 100644
index 000000000..b5bb73344
--- /dev/null
+++ b/workers/model-hunyuan3d/app21.py
@@ -0,0 +1,514 @@
+"""
+Hunyuan3D-2.1 inference service — single image → PBR-textured 3D mesh.
+
+This is the realism lane. Where 2.0 (see main.py, deployed as the
+`model-hunyuan3d` service) bakes a single diffuse texture, 2.1 runs Tencent's
+hy3dshape shape DiT followed by the hy3dpaint PBR paint pass and exports a GLB
+with a TRUE physically-based material set:
+
+ baseColor (albedo) + metallicRoughness (metallic in B, roughness in G) + normal
+
+PBR materials are what make a render read as a real photographed object under
+real lighting instead of a flat plastic toy — the single biggest realism lever
+in the platform's own GPU fleet.
+
+Deployed as its OWN Cloud Run service (`model-hunyuan3d-21`) rather than a new
+revision of `model-hunyuan3d`, because 2.0 and 2.1 have mutually incompatible
+Python stacks (torch 2.3/cu121 + hy3dgen vs torch 2.5/cu124 +
+hy3dshape/hy3dpaint). Running them as two services means the working 2.0 lane is
+never touched: fallback is an instant `GCP_HUNYUAN3D_URL` env swap back to the
+2.0 service, with zero rebuild. The HUNYUAN3D_MODEL flag pins this image to 2.1.
+
+API contract (identical to the 2.0 worker; consumed by the Pipeline Controller
+and by api/_providers/gcp.js in reconstruct mode):
+
+ POST /infer { images: [data-uri|url, ...], tier?, target_polycount?, job_id? }
+ → 202 { task_id, status: "queued" }
+ POST /reconstruct same body → 202 { task_id, job_id, status } (alias)
+ GET /tasks/:id → { task_id, status, result_gcs_url?, error? }
+ GET /jobs/:id → same, plus job_id + glb_url aliases (alias)
+ GET /health → { ok, model, gpu_available, ready, load_error }
+
+Task state is persisted to the durable `tasks/{id}.json` GCS blob on every
+transition (same as the 2.0 worker) so a POST /infer and a later GET /tasks/:id
+that land on different instances still see the same record.
+
+Weights load from GCS. The shape DiT is a single 6.9 GiB `.ckpt` and the paint
+UNet a single 3.7 GiB `.bin`; reading files that large over the Cloud Storage
+FUSE mount stalls indefinitely (the exact failure the 2.0 lane hit and fixed),
+so this worker streams the needed subtrees to local disk with the storage client
+(a plain sequential GET, which does not stall) and loads from there. Staging is
+gated on WEIGHTS_GCS_URI / DINO_GCS_URI and degrades to the FUSE mount on any
+failure — it never crashes the loader.
+
+Environment variables:
+ API_KEY — shared bearer secret (== platform GCP_RECONSTRUCTION_KEY)
+ GCS_BUCKET — Cloud Storage bucket for output meshes
+ HUNYUAN3D_MODEL — pinned to "2.1" for this image
+ WEIGHTS_GCS_URI — gs:// prefix of the 2.1 weight tree to stage locally
+ WEIGHTS_LOCAL_DIR — local staging dir for the 2.1 weights (default /tmp/hunyuan3d-2.1)
+ WEIGHTS_DIR — FUSE-mount fallback for the 2.1 weights (default /weights/hunyuan3d-2.1)
+ DINO_GCS_URI — gs:// prefix of facebook/dinov2-giant to stage locally
+ DINO_LOCAL_DIR — local staging dir for DINOv2 (default /tmp/dinov2-giant)
+ DINO_DIR — FUSE-mount fallback for DINOv2 (default /weights/dinov2-giant)
+ HUNYUAN3D21_REPO — path of the cloned 2.1 repo in the image (default /opt/hunyuan3d21)
+ MAX_CONCURRENT — in-flight inferences (default 1; one L4 fits one)
+"""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+import io
+import json
+import logging
+import os
+import sys
+import tempfile
+import time
+import uuid
+from concurrent.futures import ThreadPoolExecutor
+from contextlib import asynccontextmanager
+from typing import Optional
+
+import torch
+from fastapi import FastAPI, HTTPException, Header, BackgroundTasks
+from google.api_core.exceptions import NotFound
+from google.cloud import storage
+from PIL import Image
+from pydantic import BaseModel, Field
+
+from worker_security import (
+ UnsafeUrlError,
+ fetch_remote_bytes,
+ require_api_key,
+ safe_error,
+)
+
+logging.basicConfig(
+ level=logging.INFO,
+ format="%(asctime)s %(levelname)s %(name)s %(message)s",
+)
+log = logging.getLogger("hunyuan3d21")
+
+API_KEY = os.environ["API_KEY"]
+GCS_BUCKET = os.environ["GCS_BUCKET"]
+MODEL_VERSION = os.environ.get("HUNYUAN3D_MODEL", "2.1").strip()
+MODEL_LABEL = "hunyuan3d-2.1"
+MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT", "1"))
+REPO_ROOT = os.environ.get("HUNYUAN3D21_REPO", "/opt/hunyuan3d21")
+
+WEIGHTS_DIR = os.environ.get("WEIGHTS_DIR", "/weights/hunyuan3d-2.1")
+WEIGHTS_GCS_URI = os.environ.get("WEIGHTS_GCS_URI", "") # e.g. gs://bucket/hunyuan3d-2.1
+WEIGHTS_LOCAL_DIR = os.environ.get("WEIGHTS_LOCAL_DIR", "/tmp/hunyuan3d-2.1")
+DINO_DIR = os.environ.get("DINO_DIR", "/weights/dinov2-giant")
+DINO_GCS_URI = os.environ.get("DINO_GCS_URI", "") # e.g. gs://bucket/dinov2-giant
+DINO_LOCAL_DIR = os.environ.get("DINO_LOCAL_DIR", "/tmp/dinov2-giant")
+
+_pipeline = None
+_bucket: Optional[storage.Bucket] = None
+_sem: Optional[asyncio.Semaphore] = None
+_ready: Optional[asyncio.Event] = None
+_load_error: Optional[str] = None
+# In-memory cache only — Cloud Run has no session affinity, so a POST /infer and
+# a later GET /tasks/:id can land on different instances. The durable source of
+# truth is the tasks/{id}.json GCS blob; this dict just avoids a GCS round-trip
+# on a warm same-instance poll.
+_tasks: dict[str, dict] = {}
+
+
+def _task_blob(task_id: str):
+ return _bucket.blob(f"tasks/{task_id}.json")
+
+
+async def _update_task(task_id: str, **fields) -> dict:
+ task = _tasks.setdefault(task_id, {"task_id": task_id})
+ task.update(fields)
+ loop = asyncio.get_event_loop()
+ await loop.run_in_executor(
+ None,
+ lambda: _task_blob(task_id).upload_from_string(
+ json.dumps(task), content_type="application/json"
+ ),
+ )
+ return task
+
+
+def _stage_prefix_local(gcs_uri: str, local_dir: str, label: str) -> Optional[str]:
+ """Stream every object under a gs:// prefix to local disk with the storage
+ client, bypassing the FUSE mount (which stalls on multi-GiB sequential
+ reads). Returns local_dir on success or None to signal "load from the FUSE
+ mount instead". Never raises — a staging failure must degrade, not crash."""
+ if not gcs_uri.startswith("gs://"):
+ return None
+ try:
+ bucket_name, _, prefix = gcs_uri[len("gs://"):].partition("/")
+ prefix = prefix.rstrip("/") + "/"
+ client = storage.Client()
+ blobs = [
+ b for b in client.list_blobs(bucket_name, prefix=prefix)
+ if b.name[len(prefix):] and not b.name.endswith("/")
+ ]
+ if not blobs:
+ log.warning("[%s] staging: no objects under %s; using FUSE mount", label, gcs_uri)
+ return None
+
+ def _download(blob) -> int:
+ rel = blob.name[len(prefix):]
+ dest = os.path.join(local_dir, rel)
+ os.makedirs(os.path.dirname(dest), exist_ok=True)
+ # Reuse an already-staged object (warm restart) when its size matches.
+ if os.path.exists(dest) and blob.size is not None and os.path.getsize(dest) == blob.size:
+ return blob.size or 0
+ blob.download_to_filename(dest)
+ return blob.size or os.path.getsize(dest)
+
+ os.makedirs(local_dir, exist_ok=True)
+ t0 = time.time()
+ with ThreadPoolExecutor(max_workers=8) as pool:
+ total = sum(pool.map(_download, blobs))
+ log.info(
+ "[%s] staged to %s in %.1fs (%d objects, %.2f GiB)",
+ label, local_dir, time.time() - t0, len(blobs), total / (1024 ** 3),
+ )
+ return local_dir
+ except Exception as exc: # noqa: BLE001 — degrade to the FUSE mount, never crash
+ log.warning("[%s] staging failed (%s); falling back to FUSE mount", label, exc)
+ return None
+
+
+# ── Tier → generation budget ────────────────────────────────────────────────
+# Quality over speed: GPU time is cheap against the platform's GCP credit
+# budget, so the ceiling is pushed high. The budget splits across the shape DiT
+# (inference steps + marching-cubes octree resolution) and the PBR paint pass
+# (multiview count + per-view diffusion resolution). The paint atlas size is
+# fixed high at load (render 2048, texture 4096).
+_TIER_QUALITY = {
+ "draft": {"steps": 30, "octree_resolution": 256, "views": 6, "resolution": 512},
+ "standard": {"steps": 50, "octree_resolution": 384, "views": 6, "resolution": 512},
+ # high pushes shape octree + per-view diffusion resolution (768) for sharper
+ # PBR maps while holding the multiview count at 6 so the paint pass stays
+ # within the L4's 24 GiB VRAM alongside the shape DiT + DINOv2 + super-res.
+ "high": {"steps": 50, "octree_resolution": 512, "views": 6, "resolution": 768},
+}
+_DEFAULT_QUALITY = _TIER_QUALITY["high"]
+
+
+def _quality_for(tier: str | None) -> dict:
+ return dict(_TIER_QUALITY.get((tier or "").strip().lower(), _DEFAULT_QUALITY))
+
+
+def _load_pipeline():
+ global _pipeline
+ # The 2.1 repo is cloned to REPO_ROOT in the image and expects its two
+ # package dirs on sys.path plus cwd==REPO_ROOT (the paint config references
+ # cfg/ckpt files by repo-relative path). The Dockerfile sets WORKDIR there.
+ for p in (REPO_ROOT, os.path.join(REPO_ROOT, "hy3dshape"), os.path.join(REPO_ROOT, "hy3dpaint")):
+ if p not in sys.path:
+ sys.path.insert(0, p)
+
+ # torchvision >=0.17 moved functional_tensor; the repo ships a shim for it.
+ try:
+ from torchvision_fix import apply_fix
+ apply_fix()
+ except Exception as exc: # noqa: BLE001 — non-fatal compatibility shim
+ log.warning("[2.1] torchvision_fix not applied: %s", exc)
+
+ # Stage the big weight trees off the FUSE mount to local disk.
+ weights_root = _stage_prefix_local(WEIGHTS_GCS_URI, WEIGHTS_LOCAL_DIR, "weights") or WEIGHTS_DIR
+ dino_root = _stage_prefix_local(DINO_GCS_URI, DINO_LOCAL_DIR, "dino") or DINO_DIR
+
+ # hy3dshape's smart_load_model resolves ${HY3DGEN_MODELS}/${model_path}/${subfolder};
+ # point it at the staged tree's parent so nothing downloads at boot.
+ weights_parent = os.path.dirname(weights_root.rstrip("/"))
+ weights_name = os.path.basename(weights_root.rstrip("/"))
+ os.environ["HY3DGEN_MODELS"] = weights_parent
+
+ # The paint pipeline's multiview loader calls
+ # huggingface_hub.snapshot_download(repo_id, allow_patterns=["hunyuan3d-paintpbr-v2-1/*"])
+ # and joins that subfolder. Intercept the known repo id and hand back the
+ # local staged tree (which already contains hunyuan3d-paintpbr-v2-1/). Any
+ # other repo id falls through to the real downloader, so this never blocks a
+ # legitimate fetch.
+ import huggingface_hub
+
+ _real_snapshot = huggingface_hub.snapshot_download
+
+ def _local_snapshot(*args, **kwargs):
+ repo_id = kwargs.get("repo_id") or (args[0] if args else None)
+ if repo_id == "tencent/Hunyuan3D-2.1" and os.path.isdir(weights_root):
+ log.info("[2.1] serving paint weights from local staged tree %s", weights_root)
+ return weights_root
+ return _real_snapshot(*args, **kwargs)
+
+ huggingface_hub.snapshot_download = _local_snapshot
+
+ from hy3dshape.pipelines import Hunyuan3DDiTFlowMatchingPipeline
+ from hy3dshape.rembg import BackgroundRemover
+ from textureGenPipeline import Hunyuan3DPaintPipeline, Hunyuan3DPaintConfig
+ from hy3dpaint.convert_utils import create_glb_with_pbr_materials
+
+ log.info("[2.1] loading shape DiT (%s / hunyuan3d-dit-v2-1)", weights_name)
+ shape_pipe = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained(
+ weights_name,
+ subfolder="hunyuan3d-dit-v2-1",
+ use_safetensors=False,
+ variant="fp16",
+ device="cuda",
+ dtype=torch.float16,
+ )
+
+ log.info("[2.1] loading PBR paint pipeline (multiview + super-res + DINOv2)")
+ # Build the paint pipeline once at the ceiling view count; per job the tier
+ # scales max_selected_view_num / resolution down in place (both are read
+ # live from config at call time, so no model reload is needed).
+ conf = Hunyuan3DPaintConfig(max_num_view=8, resolution=768)
+ conf.realesrgan_ckpt_path = "hy3dpaint/ckpt/RealESRGAN_x4plus.pth"
+ conf.multiview_cfg_path = "hy3dpaint/cfgs/hunyuan-paint-pbr.yaml"
+ conf.custom_pipeline = "hy3dpaint/hunyuanpaintpbr"
+ conf.multiview_pretrained_path = "tencent/Hunyuan3D-2.1"
+ if os.path.isdir(dino_root):
+ conf.dino_ckpt_path = dino_root
+ log.info("[2.1] DINOv2 from %s", dino_root)
+ paint_pipe = Hunyuan3DPaintPipeline(conf)
+
+ _pipeline = {
+ "shape": shape_pipe,
+ "paint": paint_pipe,
+ "rembg": BackgroundRemover(),
+ "to_pbr_glb": create_glb_with_pbr_materials,
+ }
+ log.info("[2.1] pipelines loaded")
+
+
+def _generate(img: Image.Image, q: dict) -> bytes:
+ # Isolate the subject from a busy background: the shape DiT conditions on it.
+ subject = img if img.mode == "RGBA" else _pipeline["rembg"](img.convert("RGB"))
+
+ mesh = _pipeline["shape"](
+ image=subject,
+ num_inference_steps=q["steps"],
+ guidance_scale=5.0,
+ octree_resolution=q["octree_resolution"],
+ )[0]
+
+ with tempfile.TemporaryDirectory(prefix="hy3d21_") as tmp:
+ initial_glb = os.path.join(tmp, "shape.glb")
+ mesh.export(initial_glb)
+
+ # Scale the PBR paint budget to the tier in place.
+ paint = _pipeline["paint"]
+ paint.config.max_selected_view_num = q["views"]
+ paint.config.resolution = q["resolution"]
+
+ obj_out = os.path.join(tmp, "textured.obj")
+ # save_glb=False → returns the textured OBJ with sibling PBR maps:
+ # textured.jpg (albedo), textured_metallic.jpg, textured_roughness.jpg,
+ # textured_normal.jpg
+ textured_obj = paint(
+ mesh_path=initial_glb,
+ image_path=subject,
+ output_mesh_path=obj_out,
+ use_remesh=True,
+ save_glb=False,
+ )
+
+ base = textured_obj[:-4] if textured_obj.endswith(".obj") else textured_obj
+ textures = {"albedo": f"{base}.jpg"}
+ metallic, roughness, normal = f"{base}_metallic.jpg", f"{base}_roughness.jpg", f"{base}_normal.jpg"
+ if os.path.exists(metallic) and os.path.exists(roughness):
+ textures["metallic"] = metallic
+ textures["roughness"] = roughness
+ if os.path.exists(normal):
+ # Upstream's quick-convert drops the normal map; keep it so the GLB
+ # carries the full baseColor + metallicRoughness + normal PBR set.
+ textures["normal"] = normal
+
+ glb_out = os.path.join(tmp, "textured_pbr.glb")
+ _pipeline["to_pbr_glb"](textured_obj, textures, glb_out)
+ with open(glb_out, "rb") as fh:
+ return fh.read()
+
+
+async def _load_pipeline_bg():
+ """Load the pipeline off the request path and signal readiness when done.
+ Runs in a worker thread so the event loop (and the HTTP port) stay live — a
+ blocking lifespan load would delay the port past Cloud Run's startup probe
+ window and the revision would be marked failed."""
+ global _load_error
+ loop = asyncio.get_event_loop()
+ try:
+ await loop.run_in_executor(None, _load_pipeline)
+ _ready.set()
+ log.info("%s pipeline ready", MODEL_LABEL)
+ except Exception as exc: # noqa: BLE001 — surfaced via /health + task status
+ _load_error = safe_error(exc, context="model load")
+ log.error("%s pipeline load FAILED: %s", MODEL_LABEL, exc)
+
+
+@asynccontextmanager
+async def lifespan(app: FastAPI):
+ global _bucket, _sem, _ready
+ _bucket = storage.Client().bucket(GCS_BUCKET)
+ _sem = asyncio.Semaphore(MAX_CONCURRENT)
+ _ready = asyncio.Event()
+ asyncio.create_task(_load_pipeline_bg())
+ log.info(
+ "Service starting — %s loading in background (max_concurrent=%d)",
+ MODEL_LABEL, MAX_CONCURRENT,
+ )
+ yield
+
+
+app = FastAPI(title="model-hunyuan3d-21", lifespan=lifespan)
+
+
+def _require_api_key(authorization: str) -> None:
+ try:
+ require_api_key(authorization, API_KEY)
+ except PermissionError as exc:
+ raise HTTPException(status_code=401, detail=str(exc)) from exc
+
+
+def _decode_image(src: str) -> Image.Image:
+ if src.startswith("data:image"):
+ b64 = src.split(",", 1)[1]
+ return Image.open(io.BytesIO(base64.b64decode(b64))).convert("RGB")
+ if src.startswith("https://"):
+ # SSRF-hardened: https-only, private/loopback/link-local/metadata IPs
+ # rejected after DNS resolution, redirects re-validated per hop, bounded.
+ try:
+ data = fetch_remote_bytes(src, timeout=30)
+ except UnsafeUrlError as exc:
+ raise ValueError(f"refused to fetch image source: {exc}") from exc
+ return Image.open(io.BytesIO(data)).convert("RGB")
+ raise ValueError(f"unsupported image source: {src[:60]}")
+
+
+async def _run_inference(task_id: str, images: list[str], quality: dict | None = None) -> None:
+ if _load_error:
+ await _update_task(task_id, status="failed", error=f"pipeline unavailable: {_load_error}")
+ return
+ try:
+ await asyncio.wait_for(_ready.wait(), timeout=900)
+ except asyncio.TimeoutError:
+ await _update_task(task_id, status="failed", error="pipeline not ready (model load timed out)")
+ return
+ if _load_error:
+ await _update_task(task_id, status="failed", error=f"pipeline unavailable: {_load_error}")
+ return
+
+ async with _sem:
+ await _update_task(task_id, status="running")
+ loop = asyncio.get_event_loop()
+ t0 = time.time()
+ try:
+ img = await loop.run_in_executor(None, _decode_image, images[0])
+ q = quality or _DEFAULT_QUALITY
+ glb_bytes = await loop.run_in_executor(None, _generate, img, q)
+
+ blob_name = f"raw-meshes/hunyuan3d/{task_id}.glb"
+ blob = _bucket.blob(blob_name)
+ await loop.run_in_executor(
+ None,
+ lambda: blob.upload_from_string(glb_bytes, content_type="model/gltf-binary"),
+ )
+ gcs_url = f"https://storage.googleapis.com/{GCS_BUCKET}/{blob_name}"
+
+ elapsed = time.time() - t0
+ await _update_task(
+ task_id,
+ status="done",
+ result_gcs_url=gcs_url,
+ elapsed_ms=int(elapsed * 1000),
+ )
+ log.info("[%s] done in %.1fs — %d bytes → %s", task_id, elapsed, len(glb_bytes), gcs_url)
+ except Exception as exc:
+ await _update_task(
+ task_id,
+ status="failed",
+ error=safe_error(exc, context=f"[{task_id}] inference"),
+ elapsed_ms=int((time.time() - t0) * 1000),
+ )
+
+
+class InferRequest(BaseModel):
+ images: list[str] = Field(..., min_length=1, max_length=6)
+ body_type: str = "neutral"
+ job_id: str | None = None
+ # Forge reconstruct-mode provenance: the gcp provider forwards the resolved
+ # tier verbatim; it selects the generation budget via _quality_for. Absent
+ # fields mean the high default.
+ tier: str | None = None
+ path: str | None = None
+ target_polycount: int | None = None
+
+
[email protected]("/infer", status_code=202)
+async def infer(
+ body: InferRequest,
+ background_tasks: BackgroundTasks,
+ authorization: str = Header(...),
+) -> dict:
+ _require_api_key(authorization)
+ task_id = str(uuid.uuid4())
+ # Persist "queued" before responding — a poll can reach a different instance
+ # the moment the 202 lands, and that instance has nothing local to fall back on.
+ await _update_task(task_id, status="queued", model=MODEL_LABEL)
+ background_tasks.add_task(_run_inference, task_id, body.images, _quality_for(body.tier))
+ return {"task_id": task_id, "status": "queued"}
+
+
+# api/_providers/gcp.js drives this lane in `reconstruct` mode
+# (GCP_HUNYUAN3D_URL + mode:'reconstruct'), which speaks the avatar
+# controller's wire shape: POST /reconstruct → { job_id }, GET /jobs/:id.
+# These aliases accept that shape verbatim so the worker URL can be wired
+# directly into the API env; the poll reader is field-tolerant
+# (task_id|job_id, glb_url|result_gcs_url) so the same records serve both.
[email protected]("/reconstruct", status_code=202)
+async def reconstruct(
+ body: InferRequest,
+ background_tasks: BackgroundTasks,
+ authorization: str = Header(...),
+) -> dict:
+ result = await infer(body, background_tasks, authorization)
+ return {**result, "job_id": result["task_id"]}
+
+
[email protected]("/jobs/{task_id}")
+async def get_job(task_id: str, authorization: str = Header(...)) -> dict:
+ task = await get_task(task_id, authorization)
+ glb = task.get("result_gcs_url")
+ return {**task, "job_id": task.get("task_id"), **({"glb_url": glb} if glb else {})}
+
+
[email protected]("/tasks/{task_id}")
+async def get_task(task_id: str, authorization: str = Header(...)) -> dict:
+ _require_api_key(authorization)
+ task = _tasks.get(task_id)
+ if task is not None:
+ return task
+ # Not in this instance's local cache — fall back to the durable GCS record.
+ loop = asyncio.get_event_loop()
+ try:
+ data = await loop.run_in_executor(None, _task_blob(task_id).download_as_bytes)
+ except NotFound:
+ raise HTTPException(status_code=404, detail="task not found")
+ except Exception as exc:
+ raise HTTPException(status_code=502, detail=safe_error(exc, context="task lookup")) from exc
+ task = json.loads(data)
+ _tasks[task_id] = task
+ return task
+
+
+async def health() -> dict:
+ return {
+ "ok": True,
+ "model": MODEL_LABEL,
+ "gpu_available": torch.cuda.is_available(),
+ "gpu_name": torch.cuda.get_device_name(0) if torch.cuda.is_available() else None,
+ "pipeline_loaded": _pipeline is not None,
+ "ready": bool(_ready and _ready.is_set()),
+ "load_error": _load_error,
+ }
diff --git a/workers/model-hunyuan3d/cloudbuild.hunyuan21.yaml b/workers/model-hunyuan3d/cloudbuild.hunyuan21.yaml
new file mode 100644
index 000000000..9ff3536dd
--- /dev/null
+++ b/workers/model-hunyuan3d/cloudbuild.hunyuan21.yaml
@@ -0,0 +1,80 @@
+substitutions:
+ _REGION: us-central1
+ _RUN_SA: avatar-reconstruction-sa@aerial-vehicle-466722-p5.iam.gserviceaccount.com
+ _SERVICE: model-hunyuan3d-21
+ _REPO: model-hunyuan3d-21
+ _GCS_BUCKET: three-ws-avatar-reconstructions
+ _WEIGHTS_BUCKET: three-ws-model-weights
+ # min=1: the 2.1 shape DiT (6.9 GiB .ckpt) + paint UNet (3.7 GiB) + DINOv2
+ # stage ~18 GiB from GCS and load in minutes; keep one instance warm so no
+ # request ever pays that. GCP credit budget covers the always-on GPU-hour.
+ # max=1: one L4 fits exactly one in-flight generation.
+ _MIN_INSTANCES: "1"
+ _MAX_INSTANCES: "1"
+
+steps:
+ - id: build
+ name: gcr.io/cloud-builders/docker
+ dir: workers/model-hunyuan3d
+ args:
+ - build
+ - --file
+ - Dockerfile.hunyuan21
+ - --tag
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA
+ - --tag
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest
+ - --cache-from
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest
+ - .
+
+ - id: push
+ name: gcr.io/cloud-builders/docker
+ args:
+ - push
+ - --all-tags
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server
+
+ - id: deploy
+ name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim
+ entrypoint: gcloud
+ args:
+ - run
+ - deploy
+ - ${_SERVICE}
+ - --image=${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA
+ - --region=${_REGION}
+ - --service-account=${_RUN_SA}
+ - --platform=managed
+ - --port=8080
+ - --gpu=1
+ - --gpu-type=nvidia-l4
+ - --no-gpu-zonal-redundancy
+ - --no-cpu-throttling
+ - --cpu=8
+ - --memory=32Gi
+ - --min-instances=${_MIN_INSTANCES}
+ - --max-instances=${_MAX_INSTANCES}
+ - --timeout=900
+ - --allow-unauthenticated
+ - --add-volume=name=weights,type=cloud-storage,bucket=${_WEIGHTS_BUCKET}
+ - --add-volume-mount=volume=weights,mount-path=/weights
+ - --set-env-vars=^;^GCS_BUCKET=${_GCS_BUCKET};HUNYUAN3D_MODEL=2.1;WEIGHTS_DIR=/weights/hunyuan3d-2.1;WEIGHTS_GCS_URI=gs://${_WEIGHTS_BUCKET}/hunyuan3d-2.1;WEIGHTS_LOCAL_DIR=/tmp/hunyuan3d-2.1;DINO_DIR=/weights/dinov2-giant;DINO_GCS_URI=gs://${_WEIGHTS_BUCKET}/dinov2-giant;DINO_LOCAL_DIR=/tmp/dinov2-giant;MAX_CONCURRENT=1
+ - --set-secrets=API_KEY=avatar-reconstruction-key:latest
+
+images:
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest
+
+options:
+ machineType: E2_HIGHCPU_32
+ logging: CLOUD_LOGGING_ONLY
+
+# The project's default compute service account was deleted (see
+# docs/ops/gcp-production.md) — every Cloud Build must pin the build SA
+# explicitly or the submit fails with "Unknown service account".
+serviceAccount: projects/aerial-vehicle-466722-p5/serviceAccounts/[email protected]
+
+# The custom_rasterizer CUDA compile + the bpy/torch install push the build well
+# past the 10-minute default.
+timeout: 3600s
diff --git a/workers/model-hunyuan3d/requirements.hunyuan21.txt b/workers/model-hunyuan3d/requirements.hunyuan21.txt
new file mode 100644
index 000000000..6db4a50ad
--- /dev/null
+++ b/workers/model-hunyuan3d/requirements.hunyuan21.txt
@@ -0,0 +1,76 @@
+# Hunyuan3D-2.1 inference stack (torch 2.5.1 / cu124 era). Pinned to Tencent's
+# own requirements.txt for the pinned repo commit so the shape + PBR paint
+# pipelines import and run exactly as upstream verified them. torch/torchvision/
+# torchaudio are installed separately in the Dockerfile from the cu124 wheel
+# index (they must match the base image's CUDA 12.4).
+#
+# Deliberately excluded from upstream's list: gradio (demo UI only) and
+# deepspeed (training-only; its sole import in the shape stack sits inside a
+# training-EMA branch that inference never reaches). Added on top: httpx (the
+# SSRF guard in worker_security), google-cloud-storage (task state + weight
+# staging + result upload).
+
+# ── Build tools (custom_rasterizer CUDA ext + mesh_inpaint_processor pybind11) ─
+ninja==1.11.1.1
+pybind11==2.13.4
+
+# ── Core ML / diffusion ──────────────────────────────────────────────────────
+transformers==4.46.0
+diffusers==0.30.0
+accelerate==1.1.1
+pytorch-lightning==1.9.5
+huggingface-hub==0.30.2
+safetensors==0.4.4
+
+# ── Scientific computing ─────────────────────────────────────────────────────
+numpy==1.24.4
+scipy==1.14.1
+einops==0.8.0
+pandas==2.2.2
+
+# ── Computer vision / image processing ───────────────────────────────────────
+opencv-python==4.10.0.84
+imageio==2.36.0
+scikit-image==0.24.0
+rembg==2.0.65
+realesrgan==0.3.0
+tb_nightly==2.18.0a20240726
+basicsr==1.4.2
+
+# ── 3D mesh processing ───────────────────────────────────────────────────────
+trimesh==4.4.7
+pymeshlab==2022.2.post3
+pygltflib==1.16.3
+xatlas==0.0.9
+open3d==0.18.0
+
+# ── Configuration ────────────────────────────────────────────────────────────
+omegaconf==2.3.0
+pyyaml==6.0.2
+configargparse==1.7
+
+# ── Web framework (worker server) ────────────────────────────────────────────
+fastapi==0.115.12
+uvicorn[standard]==0.34.3
+pydantic==2.10.6
+
+# ── Utilities ────────────────────────────────────────────────────────────────
+tqdm==4.66.5
+psutil==6.0.0
+timm
+pythreejs
+torchdiffeq
+
+# ── GPU computing ────────────────────────────────────────────────────────────
+cupy-cuda12x==13.4.1
+
+# ── Blender (headless, used by DifferentiableRenderer.mesh_utils on import) ───
+bpy==4.0
+
+# ── ONNX runtime (rembg background removal) ──────────────────────────────────
+onnxruntime==1.16.3
+torchmetrics==1.6.0
+
+# ── three.ws worker deps ─────────────────────────────────────────────────────
+httpx>=0.27.0
+google-cloud-storage==2.18.0