Fixed Desktop App Setup + Added Auto Rig in Mesh Editor using Skintokens

This commit is contained in:
Bruno Fargnoli 2026-07-14 10:24:12 +02:00
parent f1c5d12b15
commit 0ffe63a410
85 changed files with 12929 additions and 22 deletions

11
.gitattributes vendored Normal file
View file

@ -0,0 +1,11 @@
# Default: let Git normalize text files, auto-detecting on commit.
* text=auto
# Shell scripts MUST use LF — CRLF breaks the shebang on Linux/macOS
# ("bad interpreter: /usr/bin/env bash^M"). core.autocrlf=true would otherwise
# convert them on checkout.
*.sh text eol=lf
# Windows batch files need CRLF.
*.bat text eol=crlf
*.cmd text eol=crlf

View file

@ -32,7 +32,7 @@ jobs:
- name: Set up Node
uses: actions/setup-node@v5
with:
node-version: 22
node-version: 24
cache: npm
- name: Install dependencies

15
.gitignore vendored
View file

@ -27,4 +27,17 @@ Thumbs.db
dev.log
python-server.log
.claude/
.claude/
# Python
__pycache__/
.venv/
# SkinTokens rigging service — generated / downloaded artifacts (never commit)
thirdparty/skintokens/.venv/
thirdparty/skintokens/rig-server.log
thirdparty/skintokens/experiments/
thirdparty/skintokens/models/
thirdparty/skintokens/tmp_ckpt/
thirdparty/skintokens/tmp_gradio/
thirdparty/skintokens/results/

28
package-lock.json generated
View file

@ -1,12 +1,12 @@
{
"name": "app",
"version": "0.0.0",
"version": "1.3.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "app",
"version": "0.0.0",
"version": "1.3.3",
"dependencies": {
"@react-three/drei": "^10.7.7",
"@react-three/fiber": "^9.5.0",
@ -31,7 +31,8 @@
"tencentcloud-sdk-nodejs-intl-en": "^3.0.1352",
"three": "^0.183.2",
"three-bvh-csg": "^0.0.18",
"three-mesh-bvh": "^0.9.9"
"three-mesh-bvh": "^0.9.9",
"ws": "^8.21.0"
},
"devDependencies": {
"@eslint/js": "^9.39.4",
@ -11638,6 +11639,27 @@
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
"license": "ISC"
},
"node_modules/ws": {
"version": "8.21.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",
"integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
},
"node_modules/xmlbuilder": {
"version": "15.1.1",
"resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz",

View file

@ -49,19 +49,20 @@
"tencentcloud-sdk-nodejs-intl-en": "^3.0.1352",
"three": "^0.183.2",
"three-bvh-csg": "^0.0.18",
"three-mesh-bvh": "^0.9.9"
"three-mesh-bvh": "^0.9.9",
"ws": "^8.21.0"
},
"devDependencies": {
"@eslint/js": "^9.39.4",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"electron": "^33.2.0",
"electron-builder": "^25.1.8",
"eslint": "^9.39.4",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.4.0",
"vite": "^8.0.4",
"electron": "^33.2.0",
"electron-builder": "^25.1.8"
"vite": "^8.0.4"
}
}

View file

@ -0,0 +1 @@
3.13

View file

@ -1,10 +1,17 @@
@echo off
:: Start the 3D Gen Studio Python mesh-processing service.
:: On first run: creates a local virtual environment, installs the base (CPU)
:: requirements, then auto-detects an NVIDIA GPU and installs matching GPU
:: On first run: uses `uv` to provision a pinned standalone Python (see
:: .python-version), create a local virtual environment, install the base (CPU)
:: requirements, then auto-detect an NVIDIA GPU and install matching GPU
:: acceleration (Warp + the correct cupy-cudaXXx wheel for your CUDA version).
::
:: uv gives every machine the SAME Python without depending on a system install
:: (mirrors thirdparty/skintokens). It is auto-downloaded if not already present.
setlocal enabledelayedexpansion
cd /d "%~dp0"
set "PYVER=3.13"
call :ensure_uv || goto :error
if not exist ".venv\Scripts\python.exe" (
call :setup || goto :error
@ -17,15 +24,29 @@ python main.py
goto :eof
:ensure_uv
set "UV="
where uv >nul 2>nul && set "UV=uv"
if not defined UV if exist "%USERPROFILE%\.local\bin\uv.exe" set "UV=%USERPROFILE%\.local\bin\uv.exe"
if not defined UV (
echo Installing uv ^(Python toolchain manager^)...
powershell -NoProfile -ExecutionPolicy Bypass -Command "irm https://astral.sh/uv/install.ps1 | iex" || exit /b 1
set "UV=%USERPROFILE%\.local\bin\uv.exe"
)
exit /b 0
:setup
echo Creating virtual environment...
python -m venv .venv || exit /b 1
echo Provisioning Python %PYVER% via uv...
"%UV%" python install %PYVER% || exit /b 1
echo Creating virtual environment ^(Python %PYVER%^)...
"%UV%" venv .venv --python %PYVER% || exit /b 1
call ".venv\Scripts\activate.bat"
python -m pip install --upgrade pip
echo.
echo Installing base (CPU) requirements...
pip install -r requirements.txt || exit /b 1
"%UV%" pip install -r requirements.txt || exit /b 1
:: --- Optional NVIDIA GPU acceleration -------------------------------------
:: detect_cuda.py prints the matching CuPy wheel (e.g. cupy-cuda13x) when an
@ -43,8 +64,8 @@ for /f "usebackq delims=" %%p in (`python detect_cuda.py`) do set "CUPY_PKG=%%p"
if defined CUPY_PKG (
echo NVIDIA GPU detected -- installing GPU acceleration: !CUPY_PKG! + Warp
pip install -r requirements-nvidia.txt || exit /b 1
pip install "!CUPY_PKG!" || exit /b 1
"%UV%" pip install -r requirements-nvidia.txt || exit /b 1
"%UV%" pip install "!CUPY_PKG!" || exit /b 1
echo GPU acceleration installed.
) else (
echo No NVIDIA GPU detected -- CPU-only install. Auto Retopo will run on the CPU.

60
python-server/run.sh Normal file
View file

@ -0,0 +1,60 @@
#!/usr/bin/env bash
# Start the 3D Gen Studio Python mesh-processing service (Linux / macOS).
#
# On first run: uses `uv` to provision a pinned standalone Python (see
# .python-version), create a local virtual environment, install the base (CPU)
# requirements, then auto-detect an NVIDIA GPU and install matching GPU
# acceleration (Warp + the correct cupy-cudaXXx wheel). macOS has no NVIDIA GPU,
# so it always does a CPU-only install.
#
# uv is auto-downloaded if not already present. Override host/port via env
# (e.g. MESHTOOLS_PORT=8200).
set -euo pipefail
cd "$(dirname "$0")"
PYVER=3.13
# --- Ensure uv is available -------------------------------------------------
if command -v uv >/dev/null 2>&1; then
UV="uv"
elif [ -x "$HOME/.local/bin/uv" ]; then
UV="$HOME/.local/bin/uv"
else
echo "Installing uv (Python toolchain manager)..."
curl -LsSf https://astral.sh/uv/install.sh | sh
UV="$HOME/.local/bin/uv"
fi
if [ ! -x ".venv/bin/python" ]; then
echo "Provisioning Python $PYVER via uv..."
"$UV" python install "$PYVER"
echo "Creating virtual environment (Python $PYVER)..."
"$UV" venv .venv --python "$PYVER"
# shellcheck disable=SC1091
source .venv/bin/activate
echo
echo "Installing base (CPU) requirements..."
"$UV" pip install -r requirements.txt
# --- Optional NVIDIA GPU acceleration -------------------------------------
echo
if [ -n "${MESHTOOLS_SKIP_GPU:-}" ]; then
echo "MESHTOOLS_SKIP_GPU set -- skipping GPU acceleration (CPU-only install)."
else
echo "Detecting NVIDIA GPU / CUDA version..."
CUPY_PKG="$(python detect_cuda.py || true)"
if [ -n "$CUPY_PKG" ]; then
echo "NVIDIA GPU detected -- installing GPU acceleration: $CUPY_PKG + Warp"
"$UV" pip install -r requirements-nvidia.txt
"$UV" pip install "$CUPY_PKG"
echo "GPU acceleration installed."
else
echo "No NVIDIA GPU detected -- CPU-only install. Auto Retopo will run on the CPU."
fi
fi
else
# shellcheck disable=SC1091
source .venv/bin/activate
fi
python main.py

View file

@ -10,6 +10,12 @@ start "3DGenStudio Dev" /min cmd /c "npm run dev > dev.log 2>&1"
:: first run can take a few minutes; output goes to python-server\python-server.log.
start "3DGenStudio Python" /min cmd /c "cd /d "%~dp0python-server" && run.bat > python-server.log 2>&1"
:: Start the SkinTokens rigging service (Auto Rig, port 8300) the same way. Its
:: run_server.bat builds a venv + installs torch/flash-attn/model on first launch,
:: so the FIRST run can take a long while (multi-GB download); output goes to
:: thirdparty\skintokens\rig-server.log. Needs an NVIDIA GPU (>=14 GB).
start "3DGenStudio Rigging" /min cmd /c "cd /d "%~dp0thirdparty\skintokens" && run_server.bat > rig-server.log 2>&1"
:: Wait a few seconds to let Vite + the backend spin up
timeout /t 3 /nobreak >nul

36
run.sh Normal file
View file

@ -0,0 +1,36 @@
#!/usr/bin/env bash
# Launch 3D Gen Studio on Linux / macOS (the cross-platform counterpart of
# run.bat). Starts the Vite dev server + Node backend, the Python mesh-tools
# service, and the SkinTokens rigging service (Linux only — it self-skips on
# macOS), each logging to its own file, then opens the app in the browser.
#
# First launch is slow: the Python services build their uv virtual environments
# and download dependencies + model checkpoints in the background.
set -u
cd "$(dirname "$0")"
echo "Starting dev server (npm run dev) -> dev.log"
npm run dev > dev.log 2>&1 &
echo "Starting Python mesh-tools service -> python-server/python-server.log"
( cd python-server && bash run.sh > python-server.log 2>&1 ) &
echo "Starting SkinTokens rigging service -> thirdparty/skintokens/rig-server.log"
( cd thirdparty/skintokens && bash run_server.sh > rig-server.log 2>&1 ) &
# Give Vite + the backend a moment to come up.
sleep 3
URL="http://localhost:5173"
if command -v xdg-open >/dev/null 2>&1; then
xdg-open "$URL" >/dev/null 2>&1 &
elif command -v open >/dev/null 2>&1; then
open "$URL" >/dev/null 2>&1 &
else
echo "Open $URL in your browser."
fi
echo
echo "3D Gen Studio is starting. Logs: dev.log, python-server/python-server.log, thirdparty/skintokens/rig-server.log"
echo "Press Ctrl+C to stop the dev server (background services keep running; close their windows/processes to stop them)."
wait

View file

@ -13,7 +13,12 @@ import process from 'node:process';
import os from 'node:os';
import { fileURLToPath } from 'node:url';
import si from 'systeminformation';
import { WebSocket as WsWebSocket } from 'ws';
import tencentcloudSdk from 'tencentcloud-sdk-nodejs-intl-en';
// Node 20 (bundled by Electron 33) has no global WebSocket, so fall back to the
// `ws` package. Newer Node runtimes (dev) expose a global WebSocket we can reuse.
const WebSocketImpl = globalThis.WebSocket ?? WsWebSocket;
import {
ASSETS_DIR,
DATA_DIR,
@ -896,6 +901,24 @@ function buildMeshToolsBaseUrl(settings = {}) {
return parsedUrl.toString().replace(/\/$/, '');
}
// Base URL of the dedicated rigging micro-service (thirdparty/skintokens/rig_server.py).
// It lives on its own host/port because it needs a heavy GPU/ML environment that
// must not mix with the mesh-tools service. Mirrors buildMeshToolsBaseUrl.
function buildRigToolsBaseUrl(settings = {}) {
const rigSettings = settings?.apis?.rigtools || {};
const rawUrl = String(rigSettings.url || 'http://127.0.0.1').trim();
const normalizedUrl = /^https?:\/\//i.test(rawUrl) ? rawUrl : `http://${rawUrl}`;
const parsedUrl = new URL(normalizedUrl);
const port = String(rigSettings.port || parsedUrl.port || '8300').trim();
parsedUrl.port = port;
parsedUrl.pathname = '';
parsedUrl.search = '';
parsedUrl.hash = '';
return parsedUrl.toString().replace(/\/$/, '');
}
function buildComfyUiWebSocketUrl(baseUrl, clientId) {
const parsedUrl = new URL(baseUrl);
const currentPath = parsedUrl.pathname && parsedUrl.pathname !== '/' ? parsedUrl.pathname.replace(/\/$/, '') : '';
@ -1104,7 +1127,7 @@ function createComfyExecutionMonitor(baseUrl, { clientId, promptId, workflowJson
};
const ready = new Promise((resolve, reject) => {
socket = new WebSocket(wsUrl);
socket = new WebSocketImpl(wsUrl);
if (Number.isFinite(timeout) && timeout > 0) {
timer = setTimeout(() => {
@ -1306,7 +1329,7 @@ function createComfyExecutionMonitor(baseUrl, { clientId, promptId, workflowJson
close: () => {
isSettled = true;
clearTimeout(timer);
if (socket && socket.readyState < WebSocket.CLOSING) {
if (socket && socket.readyState < WebSocketImpl.CLOSING) {
socket.close();
}
}
@ -5731,14 +5754,14 @@ const meshToolsUpload = multer({
limits: { fileSize: 512 * 1024 * 1024 },
});
async function proxyMeshTool(operationPath, req, res) {
async function proxyMeshTool(operationPath, req, res, { baseUrlBuilder = buildMeshToolsBaseUrl } = {}) {
const meshFile = req.file;
if (!meshFile?.buffer?.length) {
return res.status(400).json({ error: 'meshFile is required' });
}
const settings = await getSettings();
const baseUrl = buildMeshToolsBaseUrl(settings);
const baseUrl = baseUrlBuilder(settings);
const form = new FormData();
form.append(
@ -5834,6 +5857,18 @@ app.post('/api/meshes/repair', meshToolsUpload.single('meshFile'), async (req, r
}
});
// Auto Rig proxies to the dedicated rigging micro-service (SkinTokens/TokenRig),
// which runs on its own host/port (settings.apis.rigtools) with a GPU/ML stack.
// Same SSE contract as the mesh-tools routes above.
app.post('/api/meshes/rig', meshToolsUpload.single('meshFile'), async (req, res) => {
try {
await proxyMeshTool('/meshes/rig', req, res, { baseUrlBuilder: buildRigToolsBaseUrl });
} catch (err) {
console.error('Auto Rig proxy failed:', err);
if (!res.headersSent) res.status(500).json({ error: err.message || 'Auto Rig failed' });
}
});
// --- Mesh optimize (meshoptimizer / gltfpack binary) ------------------------
// Unlike Auto UV / Auto Retopo (which proxy to the Python service), this runs
// the bundled `gltfpack` binary locally. The browser uploads a GLB; we write it

View file

@ -488,6 +488,61 @@ export default function SettingsModal({ onClose }) {
python-server/run.bat. Can run on another machine or port.
</p>
</div>
<h3 className="settings-section-title font-label">Rigging (Python) Connection</h3>
<div className="settings-api-card">
<div className="settings-api-header">
<div className="settings-api-icon">
<span className="material-symbols-outlined" style={{ fontSize: '18px' }}>accessibility_new</span>
</div>
<span className="settings-api-name">Auto Rig</span>
</div>
<div className="settings-grid settings-grid--triple">
<div className="settings-input-group">
<label className="settings-label">Url</label>
<input
className="settings-input"
placeholder="http://127.0.0.1"
value={localSettings?.apis?.rigtools?.url || ''}
onChange={e => setLocalSettings(prev => ({
...prev,
apis: {
...prev?.apis,
rigtools: {
...prev?.apis?.rigtools,
url: e.target.value
}
}
}))}
/>
</div>
<div className="settings-input-group">
<label className="settings-label">Port</label>
<input
className="settings-input"
placeholder="8300"
value={localSettings?.apis?.rigtools?.port || ''}
onChange={e => setLocalSettings(prev => ({
...prev,
apis: {
...prev?.apis,
rigtools: {
...prev?.apis?.rigtools,
port: e.target.value
}
}
}))}
/>
</div>
</div>
<p className="settings-helper-text">
The SkinTokens/TokenRig rigging service (Auto Rig). Start it from
thirdparty/skintokens/run_server.bat. Needs an NVIDIA GPU (≥14 GB).
</p>
</div>
</section>
)}
</div>

View file

@ -0,0 +1,157 @@
// Auto Rig mode left panel. Generates a skeleton + skin weights for the current
// mesh via the SkinTokens/TokenRig rigging service, shows the resulting skeleton
// as an overlay in the viewport, and lets you save the rigged GLB as a new
// version or download it. Presentational: option state + handlers come from
// MeshEditorPage.
//
// Unlike Auto UV / Auto Retopo, the rig result is a SKINNED GLB whose value is
// the skeleton itself, so it is NOT flattened back into the editable mesh — hence
// Save/Download instead of Keep/Revert.
import { RangeField, ToggleField, SelectField } from './MeshToolField'
import MeshToolProgress from './MeshToolProgress'
export default function AutoRigToolsPanel({
options,
setOption,
running,
progress,
result,
onRun,
onSaveResult,
onDownloadResult,
onDismissResult,
saving,
hasSkeleton,
showSkeleton,
onToggleSkeleton,
disabled,
}) {
const o = options
const fieldsDisabled = disabled || running
return (
<>{/* AUTO RIG */}
<div className="mesh-editor-panel__section">
<span className="mesh-editor-panel__section-title">Auto Rig</span>
<ToggleField
label="Show skeleton"
value={showSkeleton}
onChange={onToggleSkeleton}
disabled={!hasSkeleton}
hint={hasSkeleton
? 'Overlay the skeleton (bones) on the mesh in the viewport'
: 'No skeleton yet — rig the mesh (or load an already-rigged one) to see its bones'}
/>
{!hasSkeleton && (
<span className="mesh-editor-panel__hint">This mesh has no skeleton yet. Run Auto Rig to generate one.</span>
)}
<button
type="button"
className="mesh-editor-btn mesh-editor-btn--primary"
onClick={onRun}
disabled={disabled || running}
title="Generate a skeleton and skin weights with the rigging service"
>
<span className="material-symbols-outlined">{running ? 'progress_activity' : 'accessibility_new'}</span>
<span>{running ? 'Rigging…' : 'Run Auto Rig'}</span>
</button>
{running && <MeshToolProgress progress={progress} />}
{result && (
<div className="mesh-editor-patch-preview">
<strong className="mesh-editor-patch-preview__title">
<span className="material-symbols-outlined">check_circle</span>
Rig generated
</strong>
<div className="mesh-editor-texture-workflow-meta">
{result.rows.map(row => (
<span key={row.label}><strong>{row.label}:</strong> {row.value}</span>
))}
</div>
<span className="mesh-editor-panel__hint">
The skeleton is shown in the viewport. Save it as a new version or download the rigged GLB.
</span>
<div className="mesh-editor-icon-grid mesh-editor-icon-grid--double mesh-editor-patch-preview__actions">
<button
type="button"
className="mesh-editor-btn mesh-editor-btn--primary"
onClick={onSaveResult}
disabled={saving}
title="Save the rigged mesh as a new version in the asset library"
>
<span className="material-symbols-outlined">{saving ? 'progress_activity' : 'save'}</span>
<span>{saving ? 'Saving…' : 'Save as version'}</span>
</button>
<button
type="button"
className="mesh-editor-btn"
onClick={onDownloadResult}
disabled={saving}
title="Download the rigged GLB"
>
<span className="material-symbols-outlined">download</span>
<span>Download</span>
</button>
</div>
<button
type="button"
className="mesh-editor-btn mesh-editor-btn--ghost"
onClick={onDismissResult}
disabled={saving}
title="Dismiss this result (keeps the skeleton overlay)"
>
<span className="material-symbols-outlined">close</span>
<span>Dismiss</span>
</button>
</div>
)}
</div>
<div className="mesh-editor-panel__section">
<span className="mesh-editor-panel__section-title">Skeleton</span>
<SelectField label="Bone names" value={o.rename_bones}
onChange={v => setOption('rename_bones', v)} disabled={fieldsDisabled}
options={[
{ value: 'mixamo', label: 'Mixamo' },
{ value: 'ue5', label: 'Unreal Engine 5' },
{ value: 'original', label: 'Keep model names' },
]}
hint="Rename the generated bones to a standard humanoid convention for retargeting" />
<ToggleField label="Preserve texture & scale" value={o.use_transfer}
onChange={v => setOption('use_transfer', v)} disabled={fieldsDisabled}
hint="Transfer the rig onto your original mesh (keeps its texture and scale). Recommended — leave on." />
<ToggleField label="Voxel-skin postprocess" value={o.use_postprocess}
onChange={v => setOption('use_postprocess', v)} disabled={fieldsDisabled}
hint="Clean up skin weights with a voxel pass to reduce bleed across disconnected parts" />
</div>
<div className="mesh-editor-panel__section">
<span className="mesh-editor-panel__section-title">Generation (advanced)</span>
<RangeField label="Top-k" min={1} max={200} step={1}
value={o.top_k} onChange={v => setOption('top_k', v)} disabled={fieldsDisabled}
hint="Top-k sampling" />
<RangeField label="Top-p" min={0.1} max={1} step={0.01} decimals={2}
value={o.top_p} onChange={v => setOption('top_p', v)} disabled={fieldsDisabled}
hint="Nucleus (top-p) sampling" />
<RangeField label="Temperature" min={0.1} max={2} step={0.1} decimals={1}
value={o.temperature} onChange={v => setOption('temperature', v)} disabled={fieldsDisabled} />
<RangeField label="Repetition penalty" min={0.5} max={3} step={0.1} decimals={1}
value={o.repetition_penalty} onChange={v => setOption('repetition_penalty', v)} disabled={fieldsDisabled} />
<RangeField label="Beams" min={1} max={20} step={1}
value={o.num_beams} onChange={v => setOption('num_beams', v)} disabled={fieldsDisabled}
hint="Beam-search width" />
</div>
<div className="mesh-editor-panel__notes">
<span className="mesh-editor-panel__hint">Auto Rig runs on the SkinTokens rigging service (Settings → Rigging). Needs an NVIDIA GPU.</span>
<span className="mesh-editor-panel__hint">The result is a skinned mesh; save it as a new version to keep the rig.</span>
</div>
</>
)
}

View file

@ -0,0 +1,64 @@
// Renders a skeleton as an overlay inside the mesh-editor <Canvas>: orange bone
// segments (parent→child) plus a dot at each joint, drawn on top of the mesh so
// the rig is visible through the surface (like a DCC armature view). Fed by the
// plain data from utils/meshEditor.js `extractSkeletonFromObject`.
import { useEffect, useMemo } from 'react'
import * as THREE from 'three'
const BONE_COLOR = '#f0913c'
const JOINT_COLOR = '#ffd9a0'
export default function SkeletonOverlay({ skeleton, visible = true }) {
const lineGeometry = useMemo(() => {
if (!skeleton?.segments?.length) return null
const geo = new THREE.BufferGeometry()
geo.setAttribute('position', new THREE.BufferAttribute(skeleton.segments, 3))
return geo
}, [skeleton])
const jointGeometry = useMemo(() => {
if (!skeleton?.joints?.length) return null
const geo = new THREE.BufferGeometry()
geo.setAttribute('position', new THREE.BufferAttribute(skeleton.joints, 3))
return geo
}, [skeleton])
// Size joint dots relative to the skeleton's extent so they read on any scale.
const jointSize = useMemo(() => Math.max((skeleton?.size || 1) * 0.02, 1e-4), [skeleton])
useEffect(() => () => {
lineGeometry?.dispose()
jointGeometry?.dispose()
}, [lineGeometry, jointGeometry])
if (!visible || (!lineGeometry && !jointGeometry)) return null
return (
<group renderOrder={40}>
{lineGeometry && (
<lineSegments geometry={lineGeometry} renderOrder={40}>
<lineBasicMaterial
color={BONE_COLOR}
transparent
opacity={0.95}
depthTest={false}
depthWrite={false}
/>
</lineSegments>
)}
{jointGeometry && (
<points geometry={jointGeometry} renderOrder={41}>
<pointsMaterial
color={JOINT_COLOR}
size={jointSize}
sizeAttenuation
transparent
opacity={1}
depthTest={false}
depthWrite={false}
/>
</points>
)}
</group>
)
}

View file

@ -24,6 +24,8 @@ import {
getSelectedHoleLoops,
loadEditableGeometryFromObject,
loadEditableGeometryFromGlbBuffer,
extractSkeletonFromObject,
extractSkeletonFromGlbBuffer,
mergeSelectedVertices,
smoothSelectedVertices,
subdivideSelectedFaces
@ -148,8 +150,10 @@ import { saveWorkflowDefaults } from '../utils/workflowDefaults'
import PaintingToolsPanel from '../components/meshEditor/PaintingToolsPanel'
import AutoUvToolsPanel from '../components/meshEditor/AutoUvToolsPanel'
import AutoRetopoToolsPanel from '../components/meshEditor/AutoRetopoToolsPanel'
import AutoRigToolsPanel from '../components/meshEditor/AutoRigToolsPanel'
import SkeletonOverlay from '../components/meshEditor/SkeletonOverlay'
import OptimizeToolsPanel from '../components/meshEditor/OptimizeToolsPanel'
import { autoUv as runAutoUvService, autoRetopo as runAutoRetopoService, optimizeMesh as runOptimizeService, repairMesh as runRepairService } from '../utils/meshTools'
import { autoUv as runAutoUvService, autoRetopo as runAutoRetopoService, optimizeMesh as runOptimizeService, repairMesh as runRepairService, autoRig as runAutoRigService } from '../utils/meshTools'
// Default option sets for the Python mesh-tools panels. These mirror the
// defaults of autouv.unwrap() and autoretopo.RetopoConfig 1:1 (see
@ -195,6 +199,17 @@ const DEFAULT_AUTO_RETOPO_OPTIONS = {
seed: 0,
}
const DEFAULT_AUTO_RIG_OPTIONS = {
use_transfer: true,
use_postprocess: false,
rename_bones: 'mixamo',
top_k: 5,
top_p: 0.95,
temperature: 1.0,
repetition_penalty: 2.0,
num_beams: 10,
}
// Non-manifold / topology repair (see python-server/app/schemas.py RepairOptions).
const DEFAULT_REPAIR_OPTIONS = {
method: 'remove',
@ -420,6 +435,18 @@ export default function MeshEditorPage() {
const [autoRetopoResult, setAutoRetopoResult] = useState(null)
const [autoUvProgress, setAutoUvProgress] = useState(null)
const [autoRetopoProgress, setAutoRetopoProgress] = useState(null)
// Auto Rig (SkinTokens/TokenRig) — dedicated rigging service.
const [autoRigOptions, setAutoRigOptions] = useState(DEFAULT_AUTO_RIG_OPTIONS)
const [autoRigRunning, setAutoRigRunning] = useState(false)
const [autoRigProgress, setAutoRigProgress] = useState(null)
const [autoRigResult, setAutoRigResult] = useState(null)
const [autoRigSaving, setAutoRigSaving] = useState(false)
// Skeleton overlay: the rig of the currently-loaded mesh (if it arrived rigged)
// or of the freshly-generated rig result. `showSkeleton` toggles its visibility.
const [skeleton, setSkeleton] = useState(null)
const [showSkeleton, setShowSkeleton] = useState(true)
// The rigged GLB blob returned by the service, kept for Save-as-version / download.
const riggedBlobRef = useRef(null)
// Watertight check (Auto Retopo panel) — runs on demand via a button.
const [watertightChecking, setWatertightChecking] = useState(false)
const [watertightResult, setWatertightResult] = useState(null)
@ -1863,6 +1890,16 @@ export default function MeshEditorPage() {
setLoading(true)
setError('')
const loadedRoot = await loadMeshRootFromUrl(modelUrl)
// Capture any existing skeleton BEFORE the editable/texturable pipelines
// consume the graph — an already-rigged mesh (skinned GLB) carries bones
// we can show as an overlay. Bone positions are in the same world space
// the editable geometry is baked into, so they align.
let loadedSkeleton = null
try {
loadedSkeleton = extractSkeletonFromObject(loadedRoot)
} catch (skeletonError) {
console.warn('Skeleton extraction failed:', skeletonError)
}
const texturableStartedAt = typeof performance !== 'undefined' && performance.now ? performance.now() : Date.now()
const geometryPromise = Promise.resolve().then(() => loadEditableGeometryFromObject(loadedRoot)).then(loadedGeometry => {
@ -1899,6 +1936,11 @@ export default function MeshEditorPage() {
setSelectedFaceIndices([])
setSelectedVertexIndices([])
setHoleLoops([])
// Reset the rig overlay to whatever this mesh arrived with.
setSkeleton(loadedSkeleton)
setShowSkeleton(true)
setAutoRigResult(null)
riggedBlobRef.current = null
// Bump the camera framing key so CameraRig re-frames the new mesh.
// Topology edits below do NOT bump this so the view stays put.
setMeshFrameKey(key => key + 1)
@ -3956,6 +3998,111 @@ export default function MeshEditorPage() {
setAutoRetopoOptions(prev => ({ ...prev, [key]: value }))
}, [])
const setAutoRigOption = useCallback((key, value) => {
setAutoRigOptions(prev => ({ ...prev, [key]: value }))
}, [])
// Auto Rig: generate a skeleton + skin weights via the SkinTokens rigging
// service. Unlike the other mesh tools this does NOT replace the editable
// geometry (that would discard the rig) — instead we parse the returned skinned
// GLB for a skeleton overlay and keep the blob so it can be saved as a new
// version or downloaded. We upload the TEXTURED GLB when available so the
// service's rig transfer preserves the texture and scale.
const handleRunAutoRig = useCallback(async () => {
if (!geometry || autoRigRunning) return
setAutoRigRunning(true)
setAutoRigResult(null)
setAutoRigProgress({ stage: 'start', frac: 0, message: 'Auto Rig starting…' })
setError('')
setFeedback('Auto Rig…')
try {
const canExportTextured = !!(
texturableMesh?.root
&& texturableMesh?.textureCanvas
&& geometry?.attributes?.uv?.count
)
const meshBinary = canExportTextured
? await exportTexturedMeshToGlb({
root: texturableMesh.root,
textureKey: texturableMesh.textureKey,
textureCanvas: texturableMesh.textureCanvas,
textureConfig: texturableMesh.textureConfig,
})
: await exportGeometryToGlb(geometry)
const meshBlob = new Blob([meshBinary], { type: 'model/gltf-binary' })
const { blob, stats } = await runAutoRigService(meshBlob, {
options: autoRigOptions,
fileName: 'mesh.glb',
onProgress: evt => setAutoRigProgress(evt),
})
const resultBuffer = await blob.arrayBuffer()
riggedBlobRef.current = blob
const rigSkeleton = await extractSkeletonFromGlbBuffer(resultBuffer)
setSkeleton(rigSkeleton)
setShowSkeleton(true)
const t = stats?.tool || {}
const rows = []
if (rigSkeleton?.jointCount != null) rows.push({ label: 'Bones', value: rigSkeleton.jointCount })
else if (t.bones != null) rows.push({ label: 'Bones', value: t.bones })
rows.push({ label: 'Bone names', value: autoRigOptions.rename_bones })
rows.push({ label: 'Texture preserved', value: autoRigOptions.use_transfer ? 'Yes' : 'No' })
if (autoRigOptions.use_postprocess) rows.push({ label: 'Postprocess', value: 'Voxel skin' })
setAutoRigResult({ rows })
setFeedback('Auto Rig complete.')
} catch (err) {
console.error('Auto Rig failed:', err)
setError(err?.message || 'Auto Rig failed.')
} finally {
setAutoRigRunning(false)
setAutoRigProgress(null)
}
}, [geometry, autoRigRunning, autoRigOptions, texturableMesh])
const handleSaveRiggedResult = useCallback(async () => {
const blob = riggedBlobRef.current
if (!blob || autoRigSaving) return
try {
setAutoRigSaving(true)
setError('')
setFeedback('Saving rigged mesh…')
const baseName = (meshName || 'mesh').trim() || 'mesh'
const meshFile = new File([blob], `${baseName}-rigged.glb`, { type: 'model/gltf-binary' })
await saveMeshEdit({
assetId: Number.isFinite(numericAssetId) && numericAssetId > 0 ? numericAssetId : null,
filePath,
name: `${baseName} (rigged)`,
saveMode: 'version',
meshFile,
})
setFeedback('Rigged mesh saved as a new version.')
} catch (err) {
console.error('Failed to save rigged mesh:', err)
setError(err?.message || 'Failed to save the rigged mesh.')
} finally {
setAutoRigSaving(false)
}
}, [autoRigSaving, meshName, numericAssetId, filePath, saveMeshEdit])
const handleDownloadRiggedResult = useCallback(() => {
const blob = riggedBlobRef.current
if (!blob) return
const url = URL.createObjectURL(blob)
const anchor = document.createElement('a')
anchor.href = url
anchor.download = `${(meshName || 'mesh').trim() || 'mesh'}-rigged.glb`
document.body.appendChild(anchor)
anchor.click()
anchor.remove()
setTimeout(() => URL.revokeObjectURL(url), 1000)
}, [meshName])
const handleDismissRigResult = useCallback(() => {
setAutoRigResult(null)
}, [])
// On-demand watertight check for the Auto Retopo panel. The position-welded
// edge scan can take a moment on dense meshes, so it runs behind a button with
// a loading state rather than automatically. A double rAF lets the spinner
@ -6049,6 +6196,15 @@ export default function MeshEditorPage() {
<span className="material-symbols-outlined">grid_4x4</span>
<span>Auto Retopo</span>
</button>
<button
type="button"
className={`mesh-editor-mode-btn ${activeMenu === 'autorig' ? 'mesh-editor-mode-btn--active' : ''}`}
onClick={() => setActiveMenu('autorig')}
title="Automatically generate a skeleton and skin weights (SkinTokens rigging service)"
>
<span className="material-symbols-outlined">accessibility_new</span>
<span>Auto Rig</span>
</button>
<button
type="button"
className={`mesh-editor-mode-btn ${activeMenu === 'optimize' ? 'mesh-editor-mode-btn--active' : ''}`}
@ -6156,6 +6312,20 @@ export default function MeshEditorPage() {
onRevertResult: () => handleRevertMeshTool(setAutoRetopoResult),
disabled: !geometry
}} />
) : activeMenu === 'autorig' ? (
<AutoRigToolsPanel {...{
options: autoRigOptions, setOption: setAutoRigOption,
running: autoRigRunning, progress: autoRigProgress, result: autoRigResult,
onRun: handleRunAutoRig,
onSaveResult: handleSaveRiggedResult,
onDownloadResult: handleDownloadRiggedResult,
onDismissResult: handleDismissRigResult,
saving: autoRigSaving,
hasSkeleton: !!skeleton,
showSkeleton,
onToggleSkeleton: setShowSkeleton,
disabled: !geometry
}} />
) : activeMenu === 'optimize' ? (
<OptimizeToolsPanel {...{
options: optimizeOptions, setOption: setOptimizeOption,
@ -6359,6 +6529,7 @@ export default function MeshEditorPage() {
</mesh>
</group>
)}
<SkeletonOverlay skeleton={skeleton} visible={showSkeleton} />
<Grid
infiniteGrid
fadeDistance={60}

View file

@ -331,6 +331,116 @@ export function loadEditableGeometryFromGlbBuffer(arrayBuffer) {
})
}
// Extract a skeleton from a loaded object graph (a GLTF scene / SkinnedMesh)
// for display as a line overlay in the editor. Returns plain data in WORLD space
// — the same space `loadEditableGeometryFromObject` bakes the editable geometry
// into (it applies child.matrixWorld and does NOT recenter), so the returned
// segments line up with the displayed mesh. Returns null when there is no rig.
//
// Shape: {
// jointCount,
// joints: Float32Array [x,y,z, ...] // one per bone
// segments: Float32Array [x1,y1,z1, x2,y2,z2, ...] // parent→child bone pairs
// names: string[] // bone names, parallel to joints
// size: number // bbox diagonal (for sizing joint dots)
// }
export function extractSkeletonFromObject(object) {
const root = object?.scene || object
if (!root) return null
root.updateMatrixWorld(true)
const bones = []
const boneSet = new Set()
root.traverse(child => {
if (child.isBone) {
bones.push(child)
boneSet.add(child)
}
})
// Some exporters don't tag nodes as Bone; fall back to any SkinnedMesh's skeleton.
if (bones.length === 0) {
root.traverse(child => {
if (child.isSkinnedMesh && child.skeleton?.bones?.length) {
for (const bone of child.skeleton.bones) {
if (!boneSet.has(bone)) {
bones.push(bone)
boneSet.add(bone)
}
}
}
})
}
if (bones.length === 0) return null
const indexOf = new Map(bones.map((bone, i) => [bone, i]))
const tmp = new THREE.Vector3()
const joints = new Float32Array(bones.length * 3)
const names = new Array(bones.length)
const box = new THREE.Box3()
bones.forEach((bone, i) => {
bone.getWorldPosition(tmp)
joints[i * 3] = tmp.x
joints[i * 3 + 1] = tmp.y
joints[i * 3 + 2] = tmp.z
names[i] = bone.name || `bone_${i}`
box.expandByPoint(tmp)
})
// A bone's parent may be a plain node; walk up until we find another bone.
const segments = []
bones.forEach((bone, i) => {
let parent = bone.parent
while (parent && !boneSet.has(parent)) parent = parent.parent
if (parent && indexOf.has(parent)) {
const p = indexOf.get(parent)
segments.push(
joints[p * 3], joints[p * 3 + 1], joints[p * 3 + 2],
joints[i * 3], joints[i * 3 + 1], joints[i * 3 + 2],
)
}
})
const size = box.isEmpty() ? 1 : box.getSize(tmp).length()
return {
jointCount: bones.length,
joints,
segments: new Float32Array(segments),
names,
size: size || 1,
}
}
// Parse an in-memory GLB (ArrayBuffer) and extract its skeleton overlay data.
// Used for the rigged result returned by the rig service. Returns null on no rig.
export function extractSkeletonFromGlbBuffer(arrayBuffer) {
return new Promise((resolve, reject) => {
try {
new GLTFLoader().parse(
arrayBuffer,
'',
gltf => {
const scene = gltf?.scene || (Array.isArray(gltf?.scenes) ? gltf.scenes[0] : null)
if (!scene) {
resolve(null)
return
}
try {
resolve(extractSkeletonFromObject(scene))
} catch {
resolve(null)
}
},
error => reject(error instanceof Error ? error : new Error('Failed to parse the rigged GLB.')),
)
} catch (error) {
reject(error instanceof Error ? error : new Error('Failed to parse the rigged GLB.'))
}
})
}
async function loadGeometryFromUrl(url) {
const extension = getExtensionFromUrl(url)

View file

@ -114,6 +114,14 @@ export function repairMesh(meshBlob, opts = {}) {
return callMeshTool('/meshes/repair', meshBlob, opts)
}
// Auto Rig (SkinTokens/TokenRig). Proxies to the dedicated rigging service; the
// returned blob is a SKINNED GLB (mesh + skeleton + skin weights) — unlike the
// tools above it must NOT be flattened into editable geometry. Same SSE contract;
// tool stats carry { bones, rename_bones, transfer, postprocess }.
export function autoRig(meshBlob, opts = {}) {
return callMeshTool('/meshes/rig', meshBlob, opts)
}
// Runs the bundled gltfpack binary server-side (not the Python service). Unlike
// the SSE-based tools above, this returns a single JSON envelope with the
// simplified GLB as base64. Same { blob, stats, previewUrl } contract so it

View file

@ -182,6 +182,10 @@ export const DEFAULT_SETTINGS = {
url: 'http://127.0.0.1',
port: '8200'
},
rigtools: {
url: 'http://127.0.0.1',
port: '8300'
},
custom: []
}
};

1
thirdparty/skintokens/.python-version vendored Normal file
View file

@ -0,0 +1 @@
3.13

167
thirdparty/skintokens/README.md vendored Normal file
View file

@ -0,0 +1,167 @@
<h1 align="center">SkinTokens: A Learned Compact Representation <br/> for Unified Autoregressive Rigging</h1>
<p align="center">
<a href="https://arxiv.org/abs/2602.04805"><img src='https://img.shields.io/badge/arXiv-2602.04805-b31b1b.svg?logo=arxiv' alt='arXiv'></a>
<a href="https://zjp-shadow.github.io/works/SkinTokens/"><img src='https://img.shields.io/badge/Project_Page-Website-green?logo=googlechrome&logoColor=white' alt='Project Page'></a>
<a href="https://huggingface.co/VAST-AI/SkinTokens"><img src='https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Model-blue' alt='HuggingFace Model'></a>
<a href="https://huggingface.co/spaces/VAST-AI/SkinTokens"><img src='https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Demo-yellow' alt='HuggingFace Demo'></a>
<a href="https://www.tripo3d.ai"><img src='https://img.shields.io/badge/Tripo-3D_Studio-ff7a00' alt='Tripo'></a>
</p>
<p align="center">
<img src="assets/skintokens-teaser.png" width="100%" alt="TokenRig teaser: automated rigging with SkinTokens"/>
</p>
**SkinTokens** is a learned, compact, and discrete representation for skinning weights. Built on this representation, **TokenRig** is a unified autoregressive framework that models the entire rig, i.e., skeleton and skinning weights, as a single token sequence. Given an input 3D mesh, it generates a complete skeleton hierarchy and skin weights that can be directly imported into standard 3D pipelines for character animation and simulation.
SkinTokens is the successor to [UniRig](https://github.com/VAST-AI-Research/UniRig) (SIGGRAPH '25). While UniRig uses separate stages for skeleton prediction and skinning, SkinTokens unifies both into a single autoregressive sequence via learned discrete skin tokens, yielding **98%–133%** improvement in skinning accuracy and **17%–22%** improvement in bone prediction over state-of-the-art baselines.
## 🔮 Overview
TokenRig takes a **single 3D mesh** as input and autoregressively produces a fully rigged asset — a coherent skeleton hierarchy plus dense per-vertex skinning weights — in a single unified sequence. Method in three stages:
1. **Learn SkinTokens** — An FSQ-CVAE compresses sparse skinning weights into a compact discrete vocabulary.
2. **Unified Autoregressive Modeling** — A Qwen3-0.6B-based Transformer generates the full rig (skeleton followed by SkinTokens) as one interleaved sequence.
3. **RL Refinement via GRPO** — Tailored geometric and semantic rewards (volumetric joint coverage, bone-mesh containment, skinning sparsity, deformation smoothness) refine the model for out-of-distribution assets.
<p align="center">
<img src="https://zjp-shadow.github.io/works/SkinTokens/static/images/pipeline.png" width="100%" alt="TokenRig pipeline overview"/>
</p>
<p align="center">
<img src="assets/compare-skin.jpg" width="100%" alt="Qualitative comparison of skinning prediction: TokenRig vs. Puppeteer vs. UniRig, with average L1 error maps"/>
</p>
<p align="center"><em>Qualitative comparison of skinning prediction. TokenRig produces clean, locally coherent influence maps that closely match the ground truth, while baselines suffer from "bleeding" artifacts across disconnected mesh parts.</em></p>
See the [project page](https://zjp-shadow.github.io/works/SkinTokens/) for the full teaser video and additional qualitative comparisons ([skeleton generation](https://zjp-shadow.github.io/works/SkinTokens/static/images/compare_rigging.png) and [impact of GRPO](https://zjp-shadow.github.io/works/SkinTokens/static/images/compare_grpo.png)).
## 📦 Installation
### Prerequisites
- **Hardware**: An NVIDIA GPU with at least **14 GB** of memory is required for inference.
- **Software**:
- Python >= 3.11
- [CUDA Toolkit](https://developer.nvidia.com/cuda-toolkit-archive) >= 12.1
- [uv](https://docs.astral.sh/uv/) is recommended for managing dependencies.
### Installation Steps
1. Clone the repo:
```sh
git clone https://github.com/VAST-AI-Research/SkinTokens.git
cd SkinTokens
```
2. Create a virtual environment and install PyTorch:
```sh
uv venv --python 3.11
source .venv/bin/activate
uv pip install torch==2.7.0 torchvision==0.22.0 torchaudio==2.7.0 --index-url https://download.pytorch.org/whl/cu128
```
> [!NOTE]
> Adjust the CUDA version in the PyTorch index URL to match your driver. See [PyTorch Get Started](https://pytorch.org/get-started/locally/) for other CUDA versions.
3. Install dependencies:
```sh
uv pip install -r requirements.txt
```
4. Install [flash-attn](https://github.com/Dao-AILab/flash-attention):
```sh
uv pip install flash-attn --no-build-isolation
```
5. Download pretrained models:
```sh
python download.py --model
```
This downloads the TokenRig and FSQ-CVAE checkpoints to `experiments/`, and the Qwen3-0.6B config to `models/`.
## 🤖 Pretrained Models
We provide the following pretrained models on [Hugging Face](https://huggingface.co/VAST-AI/SkinTokens):
| Model | Description | Download |
| --- | --- | --- |
| `articulation_xl_quantization_256_token_4` | TokenRig autoregressive rigging model, trained on ArticulationXL 2.0 + VRoid Hub + ModelsResource and refined with GRPO (**recommended**) | [Download](https://huggingface.co/VAST-AI/SkinTokens/tree/main/experiments/articulation_xl_quantization_256_token_4) |
| `skin_vae_2_10_32768` | FSQ-CVAE (SkinTokens) — skin-weight tokenizer used to encode and decode skinning weights | [Download](https://huggingface.co/VAST-AI/SkinTokens/tree/main/experiments/skin_vae_2_10_32768) |
## 💡 Usage
### Hugging Face Space Demo
The easiest way to try TokenRig without any local setup is the hosted [Hugging Face Space](https://huggingface.co/spaces/VAST-AI/SkinTokens) — upload a mesh and get a rigged result in the browser.
### Gradio Demo (local)
```sh
python demo.py
```
Then open `http://127.0.0.1:1024` in your browser.
### Command Line
```sh
# Rig a single model
python demo.py --input examples/giraffe.glb --output results/giraffe.glb
# Rig with original texture and scale preserved
python demo.py --input examples/giraffe.glb --output results/giraffe.glb --use_transfer
# Skin a model using its existing skeleton
python demo.py --input examples/giraffe_skeleton.glb --output results/giraffe.glb --use_skeleton --use_transfer
# Batch process a directory
python demo.py --input examples/ --output results/ --use_transfer
```
### Generation Parameters
| Parameter | Default | Description |
| --- | --- | --- |
| `--top_k` | 5 | Top-k sampling |
| `--top_p` | 0.95 | Top-p (nucleus) sampling |
| `--temperature` | 1.0 | Sampling temperature |
| `--repetition_penalty` | 2.0 | Repetition penalty |
| `--num_beams` | 10 | Number of beams for beam search |
| `--use_skeleton` | False | Use existing skeleton (generate skin only) |
| `--use_transfer` | False | Transfer original texture and scale |
| `--use_postprocess` | False | Apply voxel-based skin postprocessing |
### Troubleshooting
- **Server fails to start**: Make sure `http_proxy` / `https_proxy` environment variables are unset or correctly configured.
- **Blender export issues**: Remove the `glTF_not_exported` node when importing results into Blender.
## 🙏 Acknowledgements
- [UniRig](https://github.com/VAST-AI-Research/UniRig) — the predecessor to this work.
- [Qwen3](https://github.com/QwenLM/Qwen3) — the LLM architecture used by the TokenRig autoregressive backbone.
- [Michelangelo](https://github.com/NeuralCarver/Michelangelo) — 3D shape encoder.
- [3DShape2VecSet](https://github.com/1zb/3DShape2VecSet) — shape-representation backbone used by the FSQ-CVAE.
- [FSQ](https://arxiv.org/abs/2309.15505) — Finite Scalar Quantization, the discretization scheme behind SkinTokens.
- [GRPO (DeepSeekMath)](https://arxiv.org/abs/2402.03300) — the policy-optimization method used for RL refinement.
- [Tripo](https://www.tripo3d.ai) — the 3D generative studio from Tripo, a broader context for this line of work.
We sincerely appreciate the contributions of these excellent projects and their authors. We believe open source helps accelerate research, lower barriers to innovation, and make progress more accessible to the broader community.
## License
This project is licensed under the [MIT License](LICENSE).
## 📜 Citation
If you find this work helpful, please consider citing our paper:
```bibtex
@article{zhang2026skintokens,
title = {SkinTokens: A Learned Compact Representation for Unified Autoregressive Rigging},
author = {Zhang, Jia-Peng and Pu, Cheng-Feng and Guo, Meng-Hao and Cao, Yan-Pei and Hu, Shi-Min},
journal = {arXiv preprint arXiv:2602.04805},
year = {2026}
}
```

7
thirdparty/skintokens/bpy_server.py vendored Normal file
View file

@ -0,0 +1,7 @@
from src.server.bpy_server import run
def main():
run()
if __name__ == "__main__":
main()

View file

@ -0,0 +1,59 @@
parts_order: [body, hand]
parts:
body: [
mixamorig:Hips,
mixamorig:Spine,
mixamorig:Spine1,
mixamorig:Spine2,
mixamorig:Neck,
mixamorig:Head,
mixamorig:LeftShoulder,
mixamorig:LeftArm,
mixamorig:LeftForeArm,
mixamorig:LeftHand,
mixamorig:RightShoulder,
mixamorig:RightArm,
mixamorig:RightForeArm,
mixamorig:RightHand,
mixamorig:LeftUpLeg,
mixamorig:LeftLeg,
mixamorig:LeftFoot,
mixamorig:LeftToeBase,
mixamorig:RightUpLeg,
mixamorig:RightLeg,
mixamorig:RightFoot,
mixamorig:RightToeBase,
]
hand: [
mixamorig:LeftHandThumb1,
mixamorig:LeftHandThumb2,
mixamorig:LeftHandThumb3,
mixamorig:LeftHandIndex1,
mixamorig:LeftHandIndex2,
mixamorig:LeftHandIndex3,
mixamorig:LeftHandMiddle1,
mixamorig:LeftHandMiddle2,
mixamorig:LeftHandMiddle3,
mixamorig:LeftHandRing1,
mixamorig:LeftHandRing2,
mixamorig:LeftHandRing3,
mixamorig:LeftHandPinky1,
mixamorig:LeftHandPinky2,
mixamorig:LeftHandPinky3,
mixamorig:RightHandIndex1,
mixamorig:RightHandIndex2,
mixamorig:RightHandIndex3,
mixamorig:RightHandThumb1,
mixamorig:RightHandThumb2,
mixamorig:RightHandThumb3,
mixamorig:RightHandMiddle1,
mixamorig:RightHandMiddle2,
mixamorig:RightHandMiddle3,
mixamorig:RightHandRing1,
mixamorig:RightHandRing2,
mixamorig:RightHandRing3,
mixamorig:RightHandPinky1,
mixamorig:RightHandPinky2,
mixamorig:RightHandPinky3,
]

View file

@ -0,0 +1,59 @@
parts_order: [body, hand]
parts:
body: [
pelvis,
spine_01,
spine_02,
spine_03,
neck_01,
head,
clavicle_l,
upperarm_l,
lowerarm_l,
hand_l,
clavicle_r,
upperarm_r,
lowerarm_r,
hand_r,
thigh_l,
calf_l,
foot_l,
ball_l,
thigh_r,
calf_r,
foot_r,
ball_r,
]
hand: [
thumb_01_l,
thumb_02_l,
thumb_03_l,
index_01_l,
index_02_l,
index_03_l,
middle_01_l,
middle_02_l,
middle_03_l,
ring_01_l,
ring_02_l,
ring_03_l,
pinky_01_l,
pinky_02_l,
pinky_03_l,
index_01_r,
index_02_r,
index_03_r,
thumb_01_r,
thumb_02_r,
thumb_03_r,
middle_01_r,
middle_02_r,
middle_03_r,
ring_01_r,
ring_02_r,
ring_03_r,
pinky_01_r,
pinky_02_r,
pinky_03_r,
]

View file

@ -0,0 +1,59 @@
parts_order: [body, hand]
parts:
body: [
J_Bip_C_Hips,
J_Bip_C_Spine,
J_Bip_C_Chest,
J_Bip_C_UpperChest,
J_Bip_C_Neck,
J_Bip_C_Head,
J_Bip_L_Shoulder,
J_Bip_L_UpperArm,
J_Bip_L_LowerArm,
J_Bip_L_Hand,
J_Bip_R_Shoulder,
J_Bip_R_UpperArm,
J_Bip_R_LowerArm,
J_Bip_R_Hand,
J_Bip_L_UpperLeg,
J_Bip_L_LowerLeg,
J_Bip_L_Foot,
J_Bip_L_ToeBase,
J_Bip_R_UpperLeg,
J_Bip_R_LowerLeg,
J_Bip_R_Foot,
J_Bip_R_ToeBase,
]
hand: [
J_Bip_L_Thumb1,
J_Bip_L_Thumb2,
J_Bip_L_Thumb3,
J_Bip_L_Index1,
J_Bip_L_Index2,
J_Bip_L_Index3,
J_Bip_L_Middle1,
J_Bip_L_Middle2,
J_Bip_L_Middle3,
J_Bip_L_Ring1,
J_Bip_L_Ring2,
J_Bip_L_Ring3,
J_Bip_L_Little1,
J_Bip_L_Little2,
J_Bip_L_Little3,
J_Bip_R_Index1,
J_Bip_R_Index2,
J_Bip_R_Index3,
J_Bip_R_Thumb1,
J_Bip_R_Thumb2,
J_Bip_R_Thumb3,
J_Bip_R_Middle1,
J_Bip_R_Middle2,
J_Bip_R_Middle3,
J_Bip_R_Ring1,
J_Bip_R_Ring2,
J_Bip_R_Ring3,
J_Bip_R_Little1,
J_Bip_R_Little2,
J_Bip_R_Little3,
]

475
thirdparty/skintokens/demo.py vendored Normal file
View file

@ -0,0 +1,475 @@
import argparse
import atexit
import os
import signal
import subprocess
import sys
import tempfile
import time
from pathlib import Path
from typing import List, Iterable, Optional, Tuple
import gradio as gr
import requests
from torch import Tensor
from tqdm import tqdm
os.environ["XFORMERS_IGNORE_FLASH_VERSION_CHECK"] = "1"
gr.TEMP_DIR = "tmp_gradio"
from src.data.dataset import DatasetConfig, RigDatasetModule
from src.data.transform import Transform
from src.model.tokenrig import TokenRigResult
from src.tokenizer.parse import get_tokenizer
from src.server.spec import (
BPY_SERVER,
get_model,
object_to_bytes,
bytes_to_object,
)
from src.data.vertex_group import voxel_skin
MODEL_CKPTS = [
"experiments/articulation_xl_quantization_256_token_4/grpo_1400.ckpt",
]
HF_PATHS = [
"None",
]
SKELETON_TEMPLATE_LABELS = {
"original": "Keep model names",
"mixamo": "Mixamo",
"ue5": "Unreal Engine 5",
}
def _rename_skeleton(asset: any, skeleton_template: str) -> None:
from src.rig_package.skeleton_template import (
apply_asset_joint_name_template,
normalize_skeleton_template,
)
template_key = normalize_skeleton_template(skeleton_template)
asset.joint_names = apply_asset_joint_name_template(
joint_names=asset.joint_names,
joints=asset.joints,
parents=asset.parents,
template=template_key,
)
def start_bpy_server():
popen_kwargs = dict(
args=[sys.executable, "bpy_server.py"],
stdout=None,
stderr=None,
)
if os.name == "nt":
popen_kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
else:
popen_kwargs["preexec_fn"] = os.setsid
proc = subprocess.Popen(**popen_kwargs)
print(f"[Main] bpy_server.py started (pid={proc.pid})")
def cleanup():
print(f"[Main] Terminating bpy_server.py (pid={proc.pid})")
try:
if proc.poll() is not None:
return
if os.name == "nt":
proc.terminate()
else:
os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
except ProcessLookupError:
pass
atexit.register(cleanup)
return proc
model = None
tokenizer = None
transform = None
CURRENT_MODEL_CKPT: Optional[str] = None
CURRENT_HF_PATH: Optional[str] = None
def load_model(model_ckpt: str, hf_path: Optional[str]) -> Tuple[str, str]:
global model, tokenizer, transform, CURRENT_MODEL_CKPT, CURRENT_HF_PATH
if hf_path == "None":
hf_path = None
if model is not None and model_ckpt == CURRENT_MODEL_CKPT and hf_path == CURRENT_HF_PATH:
return ("Model already loaded.", model_ckpt)
if not model_ckpt:
raise RuntimeError("model_ckpt is empty. Please select a checkpoint.")
print(f"Loading model: {model_ckpt}, hf_path={hf_path}")
model = get_model(model_ckpt, hf_path=hf_path)
assert model.tokenizer_config is not None
tokenizer = get_tokenizer(**model.tokenizer_config)
transform = Transform.parse(**model.transform_config["predict_transform"])
CURRENT_MODEL_CKPT = model_ckpt
CURRENT_HF_PATH = hf_path
return ("Model loaded.", model_ckpt)
SUPPORTED_EXT = {".obj", ".fbx", ".glb"}
def collect_files(input_path: Path) -> List[Path]:
if input_path.is_file():
return [input_path]
files = []
for p in input_path.rglob("*"):
if p.suffix.lower() in SUPPORTED_EXT:
files.append(p)
return files
def map_output_path(
in_path: Path,
input_root: Path,
output_root: Path,
) -> Path:
rel = in_path.relative_to(input_root)
return (output_root / rel).with_suffix(".glb")
def post_bpy_payload(endpoint: str, payload):
payload_path = None
try:
with tempfile.NamedTemporaryFile(prefix=f"skintokens_{endpoint}_", suffix=".pt", delete=False) as f:
f.write(object_to_bytes(payload))
payload_path = f.name
request_payload = {"payload_path": payload_path}
response = requests.post(
f"{BPY_SERVER}/{endpoint}",
data=object_to_bytes(request_payload),
)
response.raise_for_status()
result = bytes_to_object(response.content)
if isinstance(result, dict) and result.get("error") is not None:
raise RuntimeError(result.get("traceback") or result["error"])
return result
finally:
if payload_path is not None:
try:
os.remove(payload_path)
except OSError:
pass
def run_rig(
filepaths: List[Path],
top_k: int,
top_p: float,
temperature: float,
repetition_penalty: float,
num_beams: int,
use_skeleton: bool,
use_transfer: bool,
use_postprocess: bool,
output_paths: List[Path],
model_ckpt: str,
hf_path: Optional[str],
skeleton_template: str = 'mixamo'
):
assert len(filepaths) == len(output_paths)
load_model(model_ckpt, hf_path)
datapath = {
"data_name": None,
"loader": "bpy_server",
"filepaths": {"articulation": [str(p) for p in filepaths]},
}
dataset_config = DatasetConfig.parse(
shuffle=False,
batch_size=1,
num_workers=1,
pin_memory=True,
persistent_workers=False,
datapath=datapath,
).split_by_cls()
module = RigDatasetModule(
predict_dataset_config=dataset_config,
predict_transform=transform,
tokenizer=tokenizer,
process_fn=model._process_fn,
)
dataloader = module.predict_dataloader()["articulation"]
results_out = []
for i, batch in tqdm(enumerate(dataloader), total=len(dataloader)):
batch = {
k: v.to("cuda") if isinstance(v, Tensor) else v
for k, v in batch.items()
}
if not use_skeleton:
batch.pop("skeleton_tokens", None)
batch.pop("skeleton_mask", None)
batch["generate_kwargs"] = dict(
max_length=2048,
top_k=int(top_k),
top_p=float(top_p),
temperature=float(temperature),
repetition_penalty=float(repetition_penalty),
num_return_sequences=1,
num_beams=int(num_beams),
do_sample=True,
)
if "skeleton_tokens" in batch and "skeleton_mask" in batch:
mask = batch["skeleton_mask"][0] == 1
skeleton_tokens = batch["skeleton_tokens"][0][mask].cpu().numpy()
else:
skeleton_tokens = None
preds: List[TokenRigResult] = model.predict_step(
batch,
skeleton_tokens=[skeleton_tokens] if skeleton_tokens is not None else None,
make_asset=True,
)["results"]
asset = preds[0].asset
assert asset is not None
print(f"Renaming Bones to {skeleton_template} ...")
_rename_skeleton(asset, skeleton_template)
if use_postprocess:
voxel = asset.voxel(resolution=196)
asset.skin *= voxel_skin(
grid=0,
grid_coords=voxel.coords,
joints=asset.joints,
vertices=asset.vertices,
faces=asset.faces,
mode="square",
voxel_size=voxel.voxel_size,
)
asset.normalize_skin()
out_path = output_paths[i]
out_path.parent.mkdir(parents=True, exist_ok=True)
if use_transfer:
payload = dict(
source_asset=asset,
target_path=asset.path,
export_path=str(out_path),
group_per_vertex=4,
)
res = post_bpy_payload("transfer", payload)
else:
payload = dict(
asset=asset,
filepath=str(out_path),
group_per_vertex=4,
)
res = post_bpy_payload("export", payload)
if res != "ok":
print(f"[Error] {res}")
else:
print(f"[OK] Exported: {out_path}")
results_out.append(out_path)
return results_out
def run_cli(args):
input_path = Path(args.input).resolve()
output_path = Path(args.output).resolve()
files = collect_files(input_path)
if not files:
raise RuntimeError("No valid 3D files found.")
if len(files) == 1 and output_path.suffix:
outputs = [output_path]
else:
outputs = [
map_output_path(f, input_path, output_path)
for f in files
]
run_rig(
files,
args.top_k,
args.top_p,
args.temperature,
args.repetition_penalty,
args.num_beams,
args.use_skeleton,
args.use_transfer,
args.use_postprocess,
outputs,
args.model_ckpt,
args.hf_path,
)
TOT = 0
def run_gradio(
files,
top_k,
top_p,
temperature,
repetition_penalty,
num_beams,
use_skeleton,
use_transfer,
use_postprocess,
model_ckpt,
hf_path,
):
if not files:
return "Please upload at least one 3D model.", None
tmp_out = Path(tempfile.mkdtemp(prefix="tokenrig_"))
filepaths = [Path(f.name) for f in files]
global TOT
outputs = []
for filepath in filepaths:
TOT += 1
outputs.append(tmp_out / f"res_{TOT}.glb")
run_rig(
filepaths,
top_k,
top_p,
temperature,
repetition_penalty,
num_beams,
use_skeleton,
use_transfer,
use_postprocess,
outputs,
model_ckpt,
hf_path,
)
return f"Processed {len(outputs)} models.", [str(p) for p in outputs]
def launch_gradio():
model_ckpts = MODEL_CKPTS
hf_paths = HF_PATHS
default_ckpt = model_ckpts[0] if model_ckpts else ""
default_hf = hf_paths[0] if hf_paths else "None"
with gr.Blocks(title="TokenRig Demo") as demo:
gr.Markdown("## TokenRig Demo")
gr.Markdown("Upload 3D assets, configure parameters, generate rigged GLB")
files = gr.File(
label="3D Models",
file_count="multiple",
file_types=[".obj", ".fbx", ".glb"],
)
with gr.Accordion("Generation Parameters", open=True):
model_ckpt = gr.Dropdown(
choices=model_ckpts,
value=default_ckpt,
label="Model checkpoint",
interactive=True,
)
hf_path = gr.Dropdown(
choices=hf_paths,
value=default_hf,
label="HF path",
interactive=True,
)
top_k = gr.Slider(1, 200, value=5, step=1, label="top_k")
top_p = gr.Slider(0.1, 1.0, value=0.95, step=0.01, label="top_p")
temperature = gr.Slider(0.1, 2.0, value=1.0, step=0.1, label="temperature")
repetition_penalty = gr.Slider(0.5, 3.0, value=2.0, step=0.1, label="repetition_penalty")
num_beams = gr.Slider(1, 20, value=10, step=1, label="num_beams")
use_skeleton = gr.Checkbox(False, label="Use skeleton (only generate skin if skeleton exists)")
use_transfer = gr.Checkbox(False, label="Use transfer (maintain texture)")
use_postprocess = gr.Checkbox(False, label="Use postprocess (voxel skin)")
run_btn = gr.Button("Run", variant="primary")
load_btn = gr.Button("Load Model")
log = gr.Textbox(label="Status")
output = gr.File(label="Generated GLB", interactive=False)
load_btn.click(
lambda ckpt, hf: load_model(ckpt, hf)[0],
inputs=[model_ckpt, hf_path],
outputs=[log],
)
run_btn.click(
run_gradio,
inputs=[
files,
top_k,
top_p,
temperature,
repetition_penalty,
num_beams,
use_skeleton,
use_transfer,
use_postprocess,
model_ckpt,
hf_path,
],
outputs=[log, output],
)
demo.launch(server_port=1024)
def wait_for_bpy_server(timeout=30):
t0 = time.time()
while True:
try:
requests.get(f"{BPY_SERVER}/ping", timeout=1)
print("[Main] bpy_server is ready")
return
except Exception:
if time.time() - t0 > timeout:
raise RuntimeError("bpy_server failed to start")
time.sleep(0.5)
if __name__ == "__main__":
parser = argparse.ArgumentParser("TokenRig Demo")
parser.add_argument("--input", help="Input file or directory")
parser.add_argument("--output", help="Output file or directory")
parser.add_argument("--top_k", type=int, default=5)
parser.add_argument("--top_p", type=float, default=0.95)
parser.add_argument("--temperature", type=float, default=1.0)
parser.add_argument("--repetition_penalty", type=float, default=2.0)
parser.add_argument("--num_beams", type=int, default=10)
parser.add_argument("--use_skeleton", action="store_true")
parser.add_argument("--use_transfer", action="store_true")
parser.add_argument("--use_postprocess", action="store_true")
parser.add_argument("--model_ckpt", default=MODEL_CKPTS[0] if MODEL_CKPTS else "")
parser.add_argument("--hf_path", default=None)
parser.add_argument("--gradio", action="store_true")
args = parser.parse_args()
server_proc = start_bpy_server()
wait_for_bpy_server()
if args.gradio or not args.input:
launch_gradio()
else:
run_cli(args)

72
thirdparty/skintokens/download.py vendored Normal file
View file

@ -0,0 +1,72 @@
from huggingface_hub import hf_hub_download, snapshot_download
import argparse
REPO_ID = "VAST-AI/SkinTokens"
MODELS = [
"experiments/skin_vae_2_10_32768/last.ckpt",
"experiments/articulation_xl_quantization_256_token_4/grpo_1400.ckpt",
]
DATASETS = [
"rignet.zip",
"articulation.zip",
]
LLM_REPO = "Qwen/Qwen3-0.6B"
LLM_LOCAL_DIR = "models/Qwen3-0.6B"
def download_model(name: str):
local_path = hf_hub_download(
repo_id=REPO_ID,
filename=name,
local_dir=".",
)
print(f"[MODEL] {name} downloaded to: {local_path}")
def download_llm():
local_path = snapshot_download(
repo_id=LLM_REPO,
local_dir=LLM_LOCAL_DIR,
ignore_patterns=["*.bin", "*.safetensors"],
)
print(f"[LLM] Config downloaded to: {local_path}")
def download_data(name: str):
local_path = hf_hub_download(
repo_id=REPO_ID,
filename=f"dataset_clean/{name}",
local_dir=".",
)
name = name.removesuffix(".zip")
local_path = snapshot_download(
repo_id=REPO_ID,
allow_patterns=[f"datalist/{name}/*"],
local_dir=".",
)
print(f"[DATA] {name} downloaded to: {local_path}")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--model", action="store_true", help="Download model checkpoints")
parser.add_argument("--data", action="store_true", help="Download datasets")
args = parser.parse_args()
if not args.model and not args.data:
print("Please specify --model or --data")
return
if args.model:
for model in MODELS:
download_model(model)
download_llm()
if args.data:
for data in DATASETS:
download_data(data)
if __name__ == "__main__":
main()

65
thirdparty/skintokens/download_wheel.py vendored Normal file
View file

@ -0,0 +1,65 @@
"""Download a wheel URL to a local file and print its path (for run_server.bat).
Installing flash-attn straight from its URL with ``pip install <url>`` fails on
Hugging Face Xet-backed files (the redirect to the Xet CAS bridge returns HTTP
403 to pip). Fetching through the ``huggingface_hub`` client instead (which uses
the ``hf_xet`` integration) downloads them correctly. Plain URLs (e.g. GitHub
release assets) are fetched with urllib.
Usage:
python download_wheel.py <url>
Prints the local file path on success (stdout), diagnostics on stderr, and
exits non-zero on failure so the caller can skip the install.
"""
from __future__ import annotations
import re
import sys
import tempfile
import urllib.parse
import urllib.request
def download(url: str) -> str:
if "huggingface.co" in url:
# https://huggingface.co/<owner>/<repo>/resolve/<rev>/<path-to-file>[?...]
m = re.search(r"huggingface\.co/([^/]+/[^/]+)/resolve/[^/]+/(.+)$", url)
if not m:
raise ValueError(f"Could not parse a HF repo/filename from: {url}")
repo_id = m.group(1)
# URL-decode the filename: the URL may contain %2B for '+' (as in
# flash_attn-2.8.3%2Bd2026...). hf_hub_download re-encodes the filename to
# build the request, so passing the still-encoded form would double-encode
# it (%2B -> %252B) and 404. Decoding first ('+') lets it re-encode
# correctly. unquote leaves a literal '+' untouched, so both forms work.
filename = urllib.parse.unquote(m.group(2).split("?")[0])
from huggingface_hub import hf_hub_download
# Returns a path inside the HF cache; pip installs it fine.
return hf_hub_download(repo_id=repo_id, filename=filename)
# Plain HTTP(S) download (e.g. GitHub release assets).
fd, path = tempfile.mkstemp(suffix=".whl", prefix="flash_attn_")
import os
os.close(fd)
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(req) as resp, open(path, "wb") as out:
out.write(resp.read())
return path
def main() -> None:
if len(sys.argv) < 2 or not sys.argv[1].strip():
print("[download_wheel] usage: python download_wheel.py <url>", file=sys.stderr)
sys.exit(2)
try:
print(download(sys.argv[1].strip()))
except Exception as exc: # noqa: BLE001 — the caller only needs pass/fail
print(f"[download_wheel] failed: {exc}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()

View file

@ -0,0 +1,4 @@
Torch;Cuda;Link;PyTorchLink
2.10.0;13.0;https://huggingface.co/Wildminder/AI-windows-whl/resolve/main/flash_attn-2.8.3%2Bd20260121.cu130torch2.10.0cxx11abiTRUE-cp313-cp313-win_amd64.whl;pip install torch==2.10.0 torchvision==0.25.0 torchaudio==2.10.0 --index-url https://download.pytorch.org/whl/cu130
2.9.0;12.9;https://huggingface.co/Wildminder/AI-windows-whl/resolve/main/flash_attn-2.8.3+cu129torch2.9.0cxx11abiTRUE-cp313-cp313-win_amd64.whl;pip install torch==2.9.0 torchvision==0.24.0 torchaudio==2.9.0 --index-url https://download.pytorch.org/whl/cu128
2.10.0;12.8;https://huggingface.co/Wildminder/AI-windows-whl/resolve/main/flash_attn-2.8.3+cu128torch2.10.0cxx11abiTRUE-cp313-cp313-win_amd64.whl;pip install torch==2.10.0 torchvision==0.25.0 torchaudio==2.10.0 --index-url https://download.pytorch.org/whl/cu128

21
thirdparty/skintokens/requirements.txt vendored Normal file
View file

@ -0,0 +1,21 @@
transformers>=4.57.0
diffusers>=0.35.0
python-box
einops
omegaconf
lightning
addict
fast-simplification
bpy>=4.2
trimesh
huggingface_hub
numpy>=1.26.0
gradio
bottle
tornado
scipy
fastapi
uvicorn
python-multipart
requests
tqdm

489
thirdparty/skintokens/rig.py vendored Normal file
View file

@ -0,0 +1,489 @@
"""Clean, headless rigging entry point for 3D Gen Studio.
Distilled from ``demo.py`` with all Gradio / web-UI code removed. It exposes a
reusable :class:`RigPipeline` (load the model once, rig many meshes) plus a
small CLI so a mesh can be rigged in a single command:
python rig.py --input model.glb --output rigged.glb
The heavy Blender I/O (load / export / transfer) runs in a separate
``bpy_server.py`` process, exactly like the original demo, because ``bpy`` must
own its own process. The CLI starts that server automatically and tears it down
on exit. A long-running service can instead manage :class:`BpyServer` itself and
keep a single :class:`RigPipeline` warm across requests.
Prerequisite (run once): ``python download.py --model`` to fetch the checkpoints.
Requires an NVIDIA GPU with >= 14 GB of memory.
"""
import argparse
import atexit
import os
import signal
import subprocess
import sys
import tempfile
import time
from pathlib import Path
from typing import List, Optional
os.environ["XFORMERS_IGNORE_FLASH_VERSION_CHECK"] = "1"
import requests
from torch import Tensor
from tqdm import tqdm
from src.data.dataset import DatasetConfig, RigDatasetModule
from src.data.transform import Transform
from src.data.vertex_group import voxel_skin
from src.model.tokenrig import TokenRigResult
from src.rig_package.skeleton_template import (
SKELETON_TEMPLATE_KEYS,
apply_asset_joint_name_template,
normalize_skeleton_template,
)
from src.server.spec import (
BPY_SERVER,
bytes_to_object,
get_model,
object_to_bytes,
)
from src.tokenizer.parse import get_tokenizer
# Recommended TokenRig checkpoint (ArticulationXL 2.0 + VRoid + ModelsResource, GRPO refined).
DEFAULT_MODEL_CKPT = "experiments/articulation_xl_quantization_256_token_4/grpo_1400.ckpt"
# Bone-naming templates supported by the underlying skeleton_template module.
# "original" -> keep the model's own bone names
# "mixamo" -> Mixamo humanoid naming (mixamorig:Hips, ...)
# "ue5" -> Unreal Engine 5 humanoid naming (pelvis, spine_01, ...)
RENAME_BONES_CHOICES = list(SKELETON_TEMPLATE_KEYS) # ["original", "mixamo", "ue5"]
SUPPORTED_EXT = {".obj", ".fbx", ".glb"}
class BpyServer:
"""Manages the lifecycle of the ``bpy_server.py`` Blender worker process.
Usable as a context manager::
with BpyServer():
pipeline.rig(...)
"""
def __init__(self, timeout: float = 60.0):
self._timeout = timeout
self._proc: Optional[subprocess.Popen] = None
def start(self) -> "BpyServer":
if self._proc is not None:
return self
popen_kwargs = dict(
args=[sys.executable, "bpy_server.py"],
stdout=None,
stderr=None,
)
if os.name == "nt":
popen_kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
else:
popen_kwargs["preexec_fn"] = os.setsid
self._proc = subprocess.Popen(**popen_kwargs)
print(f"[rig] bpy_server.py started (pid={self._proc.pid})")
atexit.register(self.stop)
self._wait_ready()
return self
def _wait_ready(self) -> None:
t0 = time.time()
while True:
try:
requests.get(f"{BPY_SERVER}/ping", timeout=1)
print("[rig] bpy_server is ready")
return
except Exception:
if self._proc is not None and self._proc.poll() is not None:
raise RuntimeError("bpy_server exited before becoming ready")
if time.time() - t0 > self._timeout:
raise RuntimeError("bpy_server failed to start")
time.sleep(0.5)
def stop(self) -> None:
proc, self._proc = self._proc, None
if proc is None or proc.poll() is not None:
return
print(f"[rig] terminating bpy_server.py (pid={proc.pid})")
try:
if os.name == "nt":
proc.terminate()
else:
os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
except (ProcessLookupError, OSError):
pass
def __enter__(self) -> "BpyServer":
return self.start()
def __exit__(self, *exc) -> None:
self.stop()
def _post_bpy_payload(endpoint: str, payload) -> object:
"""POST a torch-serialized payload to the bpy_server and return the result."""
payload_path = None
try:
with tempfile.NamedTemporaryFile(
prefix=f"skintokens_{endpoint}_", suffix=".pt", delete=False
) as f:
f.write(object_to_bytes(payload))
payload_path = f.name
response = requests.post(
f"{BPY_SERVER}/{endpoint}",
data=object_to_bytes({"payload_path": payload_path}),
)
response.raise_for_status()
result = bytes_to_object(response.content)
if isinstance(result, dict) and result.get("error") is not None:
raise RuntimeError(result.get("traceback") or result["error"])
return result
finally:
if payload_path is not None:
try:
os.remove(payload_path)
except OSError:
pass
class RigPipeline:
"""Loads the TokenRig model once and rigs meshes.
A ``bpy_server`` must be running (see :class:`BpyServer`) for export/transfer.
"""
def __init__(
self,
model_ckpt: str = DEFAULT_MODEL_CKPT,
hf_path: Optional[str] = None,
device: str = "cuda",
):
self.model_ckpt = model_ckpt
self.hf_path = hf_path
self.device = device
self.model = None
self.tokenizer = None
self.transform = None
def load(self) -> "RigPipeline":
"""Load model + tokenizer + transform onto the device (idempotent)."""
if self.model is not None:
return self
print(f"[rig] loading model: {self.model_ckpt} (hf_path={self.hf_path})")
self.model = get_model(self.model_ckpt, hf_path=self.hf_path, device=self.device)
assert self.model.tokenizer_config is not None
self.tokenizer = get_tokenizer(**self.model.tokenizer_config)
self.transform = Transform.parse(
**self.model.transform_config["predict_transform"]
)
print("[rig] model loaded")
return self
def rig(
self,
input_path,
output_path,
*,
use_transfer: bool = True,
use_postprocess: bool = False,
rename_bones: str = "mixamo",
use_skeleton: bool = False,
top_k: int = 5,
top_p: float = 0.95,
temperature: float = 1.0,
repetition_penalty: float = 2.0,
num_beams: int = 10,
progress=None,
) -> Path:
"""Rig a single mesh and write the result to ``output_path`` (.glb).
Args:
use_transfer: Transfer the rig onto the original mesh, preserving its
texture and scale (recommended). If False, exports the internally
normalized/processed mesh instead.
use_postprocess: Apply voxel-based skin cleanup to reduce weight bleed.
rename_bones: One of ``"original"``, ``"mixamo"``, ``"ue5"``.
use_skeleton: Reuse an existing skeleton in the input (skin-only).
progress: Optional ``callable(stage: str, frac: float, message: str)``
invoked as the pipeline advances (0.0 -> 1.0). Used by the rig
service to stream live progress to 3D Gen Studio.
"""
outputs = self._run(
[Path(input_path)],
[Path(output_path)],
use_transfer=use_transfer,
use_postprocess=use_postprocess,
rename_bones=rename_bones,
use_skeleton=use_skeleton,
top_k=top_k,
top_p=top_p,
temperature=temperature,
repetition_penalty=repetition_penalty,
num_beams=num_beams,
progress=progress,
)
return outputs[0]
def _run(
self,
filepaths: List[Path],
output_paths: List[Path],
*,
use_transfer: bool,
use_postprocess: bool,
rename_bones: str,
use_skeleton: bool,
top_k: int,
top_p: float,
temperature: float,
repetition_penalty: float,
num_beams: int,
progress=None,
) -> List[Path]:
assert len(filepaths) == len(output_paths)
def report(stage: str, frac: float, message: str) -> None:
if progress is not None:
progress(stage, frac, message)
if self.model is None:
report("model", 0.02, "Loading rig model…")
self.load()
template = normalize_skeleton_template(rename_bones)
datapath = {
"data_name": None,
"loader": "bpy_server",
"filepaths": {"articulation": [str(p) for p in filepaths]},
}
dataset_config = DatasetConfig.parse(
shuffle=False,
batch_size=1,
num_workers=1,
pin_memory=True,
persistent_workers=False,
datapath=datapath,
).split_by_cls()
module = RigDatasetModule(
predict_dataset_config=dataset_config,
predict_transform=self.transform,
tokenizer=self.tokenizer,
process_fn=self.model._process_fn,
)
dataloader = module.predict_dataloader()["articulation"]
results_out: List[Path] = []
n = len(dataloader)
for i, batch in tqdm(enumerate(dataloader), total=n):
# Fraction covered by earlier meshes in a batch run, so multi-mesh
# progress advances smoothly rather than resetting each iteration.
base = 0.05 + (i / max(n, 1)) * 0.9
span = 0.9 / max(n, 1)
report("load", base, f"Loading mesh {i + 1}/{n}…")
batch = {
k: v.to(self.device) if isinstance(v, Tensor) else v
for k, v in batch.items()
}
if not use_skeleton:
batch.pop("skeleton_tokens", None)
batch.pop("skeleton_mask", None)
batch["generate_kwargs"] = dict(
max_length=2048,
top_k=int(top_k),
top_p=float(top_p),
temperature=float(temperature),
repetition_penalty=float(repetition_penalty),
num_return_sequences=1,
num_beams=int(num_beams),
do_sample=True,
)
if "skeleton_tokens" in batch and "skeleton_mask" in batch:
mask = batch["skeleton_mask"][0] == 1
skeleton_tokens = batch["skeleton_tokens"][0][mask].cpu().numpy()
else:
skeleton_tokens = None
report("generate", base + span * 0.15, "Generating skeleton & skin…")
preds: List[TokenRigResult] = self.model.predict_step(
batch,
skeleton_tokens=[skeleton_tokens] if skeleton_tokens is not None else None,
make_asset=True,
)["results"]
asset = preds[0].asset
assert asset is not None
report("rename", base + span * 0.75, f"Renaming bones → {template}…")
print(f"[rig] renaming bones -> {template}")
asset.joint_names = apply_asset_joint_name_template(
joint_names=asset.joint_names,
joints=asset.joints,
parents=asset.parents,
template=template,
)
if use_postprocess:
report("postprocess", base + span * 0.8, "Voxel-skin postprocess…")
print("[rig] applying voxel-skin postprocess")
voxel = asset.voxel(resolution=196)
asset.skin *= voxel_skin(
grid=0,
grid_coords=voxel.coords,
joints=asset.joints,
vertices=asset.vertices,
faces=asset.faces,
mode="square",
voxel_size=voxel.voxel_size,
)
asset.normalize_skin()
out_path = output_paths[i]
out_path.parent.mkdir(parents=True, exist_ok=True)
report("export", base + span * 0.9,
"Transferring rig onto mesh…" if use_transfer else "Exporting rigged GLB…")
if use_transfer:
res = _post_bpy_payload(
"transfer",
dict(
source_asset=asset,
target_path=asset.path,
export_path=str(out_path),
group_per_vertex=4,
),
)
else:
res = _post_bpy_payload(
"export",
dict(
asset=asset,
filepath=str(out_path),
group_per_vertex=4,
),
)
if res != "ok":
raise RuntimeError(f"bpy_server returned: {res}")
print(f"[rig] exported: {out_path}")
results_out.append(out_path)
report("done", 1.0, "Rigging complete.")
return results_out
def _collect_files(input_path: Path) -> List[Path]:
if input_path.is_file():
return [input_path]
return [
p for p in input_path.rglob("*") if p.suffix.lower() in SUPPORTED_EXT
]
def _map_output_path(in_path: Path, input_root: Path, output_root: Path) -> Path:
rel = in_path.relative_to(input_root)
return (output_root / rel).with_suffix(".glb")
def _resolve_outputs(files: List[Path], input_path: Path, output_path: Path) -> List[Path]:
if len(files) == 1 and output_path.suffix:
return [output_path]
return [_map_output_path(f, input_path, output_path) for f in files]
def main() -> None:
parser = argparse.ArgumentParser(
description="Rig a 3D mesh with SkinTokens/TokenRig (headless)."
)
parser.add_argument("--input", required=True, help="Input file or directory (.obj/.fbx/.glb)")
parser.add_argument("--output", required=True, help="Output file or directory (.glb)")
# Core rigging options requested by 3D Gen Studio.
transfer = parser.add_mutually_exclusive_group()
transfer.add_argument(
"--use_transfer",
dest="use_transfer",
action="store_true",
help="Transfer rig onto the original mesh, preserving texture and scale (default).",
)
transfer.add_argument(
"--no_transfer",
dest="use_transfer",
action="store_false",
help="Export the internally processed mesh instead of transferring.",
)
parser.set_defaults(use_transfer=True)
parser.add_argument(
"--use_postprocess",
action="store_true",
help="Apply voxel-based skin postprocessing.",
)
parser.add_argument(
"--rename_bones",
choices=RENAME_BONES_CHOICES,
default="mixamo",
help="Bone naming template (default: mixamo).",
)
parser.add_argument(
"--use_skeleton",
action="store_true",
help="Reuse an existing skeleton in the input (skin-only).",
)
# Generation parameters (sensible defaults from the reference demo).
parser.add_argument("--top_k", type=int, default=5)
parser.add_argument("--top_p", type=float, default=0.95)
parser.add_argument("--temperature", type=float, default=1.0)
parser.add_argument("--repetition_penalty", type=float, default=2.0)
parser.add_argument("--num_beams", type=int, default=10)
parser.add_argument("--model_ckpt", default=DEFAULT_MODEL_CKPT)
parser.add_argument("--hf_path", default=None)
args = parser.parse_args()
input_path = Path(args.input).resolve()
output_path = Path(args.output).resolve()
files = _collect_files(input_path)
if not files:
raise RuntimeError(f"No valid 3D files found under: {input_path}")
outputs = _resolve_outputs(files, input_path, output_path)
pipeline = RigPipeline(model_ckpt=args.model_ckpt, hf_path=args.hf_path)
with BpyServer():
pipeline.load()
pipeline._run(
files,
outputs,
use_transfer=args.use_transfer,
use_postprocess=args.use_postprocess,
rename_bones=args.rename_bones,
use_skeleton=args.use_skeleton,
top_k=args.top_k,
top_p=args.top_p,
temperature=args.temperature,
repetition_penalty=args.repetition_penalty,
num_beams=args.num_beams,
)
print(f"[rig] done. {len(outputs)} mesh(es) rigged.")
if __name__ == "__main__":
main()

265
thirdparty/skintokens/rig_server.py vendored Normal file
View file

@ -0,0 +1,265 @@
"""Dedicated rigging micro-service for 3D Gen Studio.
A tiny FastAPI app that wraps the headless :class:`RigPipeline` (see ``rig.py``)
so the Node backend can rig a mesh over HTTP. It deliberately mirrors the
request/response contract of the main mesh-tools service
(``python-server/app/routes/meshes.py``) so the browser client and the Node
proxy treat it identically:
Request : multipart/form-data
- meshFile : the mesh to rig (GLB/OBJ/FBX)
- options : JSON string of rig options (optional)
- format : ignored (rig output is always GLB)
Response : text/event-stream (SSE)
{"type":"progress","stage":"generate","frac":0.4,"message":"…"}
{"type":"done","format":"glb","mesh_b64":"…","stats":{…}}
{"type":"error","detail":"…"}
Why a separate service (not part of python-server): rigging needs a completely
different, heavy environment — torch + flash-attn + bpy + a ~14 GB CUDA model +
the bpy_server subprocess — which must not be mixed into the CPU/trimesh venv of
the mesh-tools service. Keeping it standalone means the model stays warm across
requests and the two dependency sets never collide.
Run it from THIS directory (the bpy_server.py launch + checkpoint paths are
relative), inside the SkinTokens venv:
python rig_server.py # binds RIGTOOLS_HOST:RIGTOOLS_PORT (default 0.0.0.0:8300)
Prerequisite (run once): ``python download.py --model``.
"""
from __future__ import annotations
import base64
import json
import os
import queue
import struct
import tempfile
import threading
from pathlib import Path
os.environ.setdefault("XFORMERS_IGNORE_FLASH_VERSION_CHECK", "1")
# The bpy_server.py subprocess and the checkpoint paths are resolved relative to
# the current working directory, so anchor it to this file's location regardless
# of where the service was launched from.
_HERE = Path(__file__).resolve().parent
os.chdir(_HERE)
import uvicorn
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse
from rig import DEFAULT_MODEL_CKPT, RENAME_BONES_CHOICES, BpyServer, RigPipeline
HOST = os.environ.get("RIGTOOLS_HOST", "0.0.0.0")
PORT = int(os.environ.get("RIGTOOLS_PORT", "8300") or "8300")
MODEL_CKPT = os.environ.get("RIGTOOLS_MODEL_CKPT", DEFAULT_MODEL_CKPT)
HF_PATH = os.environ.get("RIGTOOLS_HF_PATH") or None
MAX_UPLOAD_BYTES = int(os.environ.get("RIGTOOLS_MAX_UPLOAD_BYTES", str(512 * 1024 * 1024)))
ALLOWED_ORIGINS = [
o.strip()
for o in os.environ.get(
"RIGTOOLS_ALLOWED_ORIGINS", "http://localhost:5173,http://localhost:3001"
).split(",")
if o.strip()
]
SUPPORTED_EXT = {".glb", ".obj", ".fbx"}
app = FastAPI(title="3D Gen Studio — Rigging", version="0.1.0")
app.add_middleware(
CORSMiddleware,
allow_origins=ALLOWED_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
_SSE_HEADERS = {
"Cache-Control": "no-cache, no-transform",
"X-Accel-Buffering": "no",
"Connection": "keep-alive",
}
# Rigging is GPU-bound and single-threaded in practice; serialize requests and
# share one warm pipeline + bpy_server across them.
_lock = threading.Lock()
_bpy: BpyServer | None = None
_pipeline: RigPipeline | None = None
def _ensure_ready(report) -> RigPipeline:
"""Start the bpy_server and load the model once (idempotent, warm afterwards)."""
global _bpy, _pipeline
if _bpy is None:
report("init", 0.01, "Starting Blender worker…")
_bpy = BpyServer().start()
if _pipeline is None:
report("model", 0.03, "Loading rig model (first run may take a minute)…")
_pipeline = RigPipeline(model_ckpt=MODEL_CKPT, hf_path=HF_PATH).load()
return _pipeline
def _glb_bone_count(path: Path) -> int | None:
"""Best-effort count of skeleton joints in a GLB (parses the JSON chunk only)."""
try:
with open(path, "rb") as f:
data = f.read()
if data[:4] != b"glTF":
return None
# 12-byte header, then chunks: [uint32 length][uint32 type][data].
length = struct.unpack_from("<I", data, 12)[0]
chunk = data[20:20 + length]
doc = json.loads(chunk.decode("utf-8"))
skins = doc.get("skins") or []
if not skins:
return None
return sum(len(s.get("joints", [])) for s in skins)
except Exception:
return None
def _sse(obj: dict) -> str:
return f"data: {json.dumps(obj, separators=(',', ':'))}\n\n"
def _parse_options(raw: str | None) -> dict:
try:
data = json.loads(raw) if raw else {}
except json.JSONDecodeError as exc:
raise HTTPException(status_code=400, detail=f"Invalid options JSON: {exc}") from exc
if not isinstance(data, dict):
raise HTTPException(status_code=400, detail="options must be a JSON object.")
rename = data.get("rename_bones", "mixamo")
if rename not in RENAME_BONES_CHOICES:
raise HTTPException(
status_code=422,
detail=f"rename_bones must be one of {RENAME_BONES_CHOICES}, got {rename!r}.",
)
def _num(key, default, cast):
try:
return cast(data[key]) if key in data and data[key] is not None else default
except (TypeError, ValueError):
return default
return dict(
use_transfer=bool(data.get("use_transfer", True)),
use_postprocess=bool(data.get("use_postprocess", False)),
rename_bones=rename,
use_skeleton=bool(data.get("use_skeleton", False)),
top_k=_num("top_k", 5, int),
top_p=_num("top_p", 0.95, float),
temperature=_num("temperature", 1.0, float),
repetition_penalty=_num("repetition_penalty", 2.0, float),
num_beams=_num("num_beams", 10, int),
)
@app.get("/health")
def health() -> dict:
return {
"status": "ok",
"model_loaded": _pipeline is not None,
"bpy_ready": _bpy is not None,
}
@app.post("/meshes/rig")
async def rig(
meshFile: UploadFile = File(...),
options: str | None = Form(None),
format: str = Form("glb"),
) -> StreamingResponse:
opts = _parse_options(options)
data = await meshFile.read()
if not data:
raise HTTPException(status_code=400, detail="meshFile is empty.")
if len(data) > MAX_UPLOAD_BYTES:
raise HTTPException(status_code=413, detail="meshFile exceeds the maximum allowed size.")
src_name = meshFile.filename or "mesh.glb"
ext = Path(src_name).suffix.lower()
if ext not in SUPPORTED_EXT:
ext = ".glb"
events: "queue.Queue" = queue.Queue()
holder: dict = {}
def emit(stage, frac, message=""):
events.put({"type": "progress", "stage": stage, "frac": round(float(frac), 4), "message": message})
def worker():
tmpdir = Path(tempfile.mkdtemp(prefix="rig_"))
in_path = tmpdir / f"input{ext}"
out_path = tmpdir / "rigged.glb"
try:
in_path.write_bytes(data)
# Only one rig at a time — the model + bpy_server are shared singletons.
with _lock:
pipeline = _ensure_ready(emit)
pipeline.rig(
in_path,
out_path,
progress=emit,
**opts,
)
payload = out_path.read_bytes()
holder["payload"] = {
"format": "glb",
"mesh_b64": base64.b64encode(payload).decode("ascii"),
"stats": {
"tool": {
"bones": _glb_bone_count(out_path),
"rename_bones": opts["rename_bones"],
"transfer": opts["use_transfer"],
"postprocess": opts["use_postprocess"],
},
},
"preview_b64": None,
}
except Exception as exc: # noqa: BLE001 — surfaced to the client as an error event
holder["error"] = f"Rigging failed: {exc}"
finally:
for p in (in_path, out_path):
try:
p.unlink()
except OSError:
pass
try:
tmpdir.rmdir()
except OSError:
pass
events.put(None)
threading.Thread(target=worker, daemon=True).start()
def generate():
yield _sse({"type": "progress", "stage": "start", "frac": 0.0, "message": "Rigging starting…"})
while True:
try:
item = events.get(timeout=15)
except queue.Empty:
# Long silent stages (model load, autoregressive generation) emit
# nothing for a while; keep bytes flowing so the Node proxy's fetch
# body timeout doesn't abort the stream.
yield ": keepalive\n\n"
continue
if item is None:
break
yield _sse(item)
if "error" in holder:
yield _sse({"type": "error", "detail": holder["error"]})
else:
yield _sse({"type": "done", **holder["payload"]})
return StreamingResponse(generate(), media_type="text/event-stream", headers=_SSE_HEADERS)
if __name__ == "__main__":
print(f"[rig-server] listening on http://{HOST}:{PORT} (model={MODEL_CKPT})")
uvicorn.run(app, host=HOST, port=PORT, log_level="info")

127
thirdparty/skintokens/run_server.bat vendored Normal file
View file

@ -0,0 +1,127 @@
@echo off
:: Start the 3D Gen Studio rigging micro-service (rig_server.py).
::
:: On first run this uses `uv` to provision a pinned standalone Python (see
:: .python-version -> 3.13, the version bpy and the flash-attn wheels target),
:: create a local virtual environment, and install the full stack: the SkinTokens
:: requirements, torch matched to a prebuilt flash-attn wheel for this Python+CUDA
:: (building flash-attn from source on Windows is painfully slow), the flash-attn
:: wheel itself, and the model checkpoints.
::
:: Pinning Python via uv makes the flash-attn wheel selection deterministic: the
:: cpXYZ tag is always known, so only CUDA has to be matched. uv is auto-installed
:: if absent.
::
:: Env overrides:
:: RIGTOOLS_PORT=8300 bind port (also RIGTOOLS_HOST)
:: RIGTOOLS_CUDA=12.8 force the CUDA build to target (skip nvidia-smi)
:: RIGTOOLS_SKIP_FLASH=1 don't install flash-attn
:: RIGTOOLS_SKIP_MODEL=1 don't download the model checkpoints
setlocal enabledelayedexpansion
cd /d "%~dp0"
set "PYVER=3.13"
call :ensure_uv || goto :error
if not exist ".venv\Scripts\python.exe" (
call :setup || goto :error
) else (
call ".venv\Scripts\activate.bat"
:: In case the venv predates the HTTP service (e.g. made per the README).
python -c "import fastapi, uvicorn, multipart" 2>nul || "%UV%" pip install fastapi uvicorn python-multipart
)
python rig_server.py
goto :eof
:ensure_uv
set "UV="
where uv >nul 2>nul && set "UV=uv"
if not defined UV if exist "%USERPROFILE%\.local\bin\uv.exe" set "UV=%USERPROFILE%\.local\bin\uv.exe"
if not defined UV (
echo Installing uv ^(Python toolchain manager^)...
powershell -NoProfile -ExecutionPolicy Bypass -Command "irm https://astral.sh/uv/install.ps1 | iex" || exit /b 1
set "UV=%USERPROFILE%\.local\bin\uv.exe"
)
exit /b 0
:setup
echo Provisioning Python %PYVER% via uv...
"%UV%" python install %PYVER% || exit /b 1
echo Creating virtual environment ^(Python %PYVER%^)...
"%UV%" venv .venv --python %PYVER% || exit /b 1
call ".venv\Scripts\activate.bat"
:: --- Pick a prebuilt flash-attn wheel + its matching torch install ----------
:: select_flash_attn.py reads flash_attention_windows.txt and, on a CUDA match,
:: prints two lines:
:: WHEEL=<flash-attn wheel url>
:: TORCHARGS=<torch==.. torchvision==.. [torchaudio==..] --index-url ..>
:: (TORCHARGS is the curated per-wheel torch command, ABI-matched to the wheel,
:: with torchvision/torchaudio versions pinned so nothing drags torch off-version.)
:: Prints nothing on no match. Python is pinned to 3.13 by uv, so the wheels
:: (all cp313) always fit; only CUDA has to be matched.
echo.
echo Detecting CUDA to select a flash-attn wheel...
set "WHEEL="
set "TORCHARGS="
for /f "tokens=1* delims==" %%a in ('python select_flash_attn.py') do set "%%a=%%b"
echo.
echo Installing SkinTokens requirements...
"%UV%" pip install -r requirements.txt || exit /b 1
:: Install torch AFTER requirements so it overrides the torch that `lightning`
:: pulls in. The curated TORCHARGS pins torch + torchvision (+torchaudio) to the
:: exact versions the flash-attn wheel was built against, so the ABI matches.
echo.
if defined TORCHARGS (
echo Installing torch: %TORCHARGS%
"%UV%" pip install %TORCHARGS% || exit /b 1
) else (
echo No matching prebuilt flash-attn wheel -- installing default torch 2.7.0 ^(cu128^)...
"%UV%" pip install torch==2.7.0 torchvision==0.22.0 torchaudio==2.7.0 --index-url https://download.pytorch.org/whl/cu128 || exit /b 1
)
:: --- flash-attn -------------------------------------------------------------
echo.
if defined RIGTOOLS_SKIP_FLASH (
echo RIGTOOLS_SKIP_FLASH set -- skipping flash-attn.
) else (
if defined WHEEL (
echo Downloading + installing prebuilt flash-attn wheel...
:: `pip install <hf-url>` 403s on Hugging Face Xet-backed files, so fetch the
:: wheel to a local path via the huggingface_hub client first, then install it.
set "FA_INSTALLED="
for /f "delims=" %%p in ('python download_wheel.py "%WHEEL%"') do (
"%UV%" pip install "%%p" && set "FA_INSTALLED=1"
)
if not defined FA_INSTALLED echo [warn] flash-attn not installed ^(download or install failed^); continuing without it.
) else (
echo [warn] No prebuilt flash-attn wheel matched this Python + CUDA.
echo flash-attn was NOT installed. To add it later, build from source:
echo uv pip install flash-attn --no-build-isolation
)
)
:: --- model checkpoints ------------------------------------------------------
echo.
if defined RIGTOOLS_SKIP_MODEL (
echo RIGTOOLS_SKIP_MODEL set -- skipping checkpoint download.
) else (
echo Downloading model checkpoints ^(large; first run only^)...
python download.py --model || echo [warn] model download failed; run "python download.py --model" manually before rigging.
)
echo.
echo Setup complete.
exit /b 0
:error
echo.
echo Setup failed. See the messages above.
exit /b 1

79
thirdparty/skintokens/run_server.sh vendored Normal file
View file

@ -0,0 +1,79 @@
#!/usr/bin/env bash
# Start the 3D Gen Studio rigging micro-service (rig_server.py) on Linux.
#
# Rigging (SkinTokens/TokenRig) needs an NVIDIA GPU (CUDA), so it runs on Windows
# and Linux only. On macOS this script exits early with a clear message.
#
# On first run it uses `uv` to provision a pinned standalone Python (see
# .python-version -> 3.13) and installs the SkinTokens requirements, torch, a
# flash-attn wheel, and the model checkpoints. Unlike Windows (which needs the
# curated flash_attention_windows.txt wheels), Linux gets flash-attn straight
# from pip, which resolves a prebuilt wheel for the installed torch/CUDA/Python
# (or builds it — needs the CUDA toolkit + ninja). uv is auto-installed if absent.
#
# Env overrides: RIGTOOLS_PORT/HOST, RIGTOOLS_SKIP_FLASH=1, RIGTOOLS_SKIP_MODEL=1.
set -euo pipefail
cd "$(dirname "$0")"
PYVER=3.13
if [ "$(uname)" = "Darwin" ]; then
echo "Rigging (SkinTokens) requires an NVIDIA GPU (CUDA), which macOS does not"
echo "provide. The rigging service is not available on macOS; Auto Rig will be"
echo "disabled. (The mesh-tools service and the rest of the app still work.)"
exit 0
fi
# --- Ensure uv is available -------------------------------------------------
if command -v uv >/dev/null 2>&1; then
UV="uv"
elif [ -x "$HOME/.local/bin/uv" ]; then
UV="$HOME/.local/bin/uv"
else
echo "Installing uv (Python toolchain manager)..."
curl -LsSf https://astral.sh/uv/install.sh | sh
UV="$HOME/.local/bin/uv"
fi
if [ ! -x ".venv/bin/python" ]; then
echo "Provisioning Python $PYVER via uv..."
"$UV" python install "$PYVER"
echo "Creating virtual environment (Python $PYVER)..."
"$UV" venv .venv --python "$PYVER"
# shellcheck disable=SC1091
source .venv/bin/activate
echo
echo "Installing SkinTokens requirements..."
"$UV" pip install -r requirements.txt
# torch AFTER requirements so it overrides the torch `lightning` pulls in. On
# Linux the default PyPI torch wheels bundle CUDA, so no custom index is needed.
echo
echo "Installing torch (CUDA build)..."
"$UV" pip install torch torchvision torchaudio
echo
if [ -n "${RIGTOOLS_SKIP_FLASH:-}" ]; then
echo "RIGTOOLS_SKIP_FLASH set -- skipping flash-attn."
else
echo "Installing flash-attn (prebuilt wheel if available, else builds from source)..."
"$UV" pip install flash-attn --no-build-isolation || echo "[warn] flash-attn install failed; continuing without it."
fi
echo
if [ -n "${RIGTOOLS_SKIP_MODEL:-}" ]; then
echo "RIGTOOLS_SKIP_MODEL set -- skipping checkpoint download."
else
echo "Downloading model checkpoints (large; first run only)..."
python download.py --model || echo "[warn] model download failed; run 'python download.py --model' manually before rigging."
fi
echo
echo "Setup complete."
else
# shellcheck disable=SC1091
source .venv/bin/activate
python -c "import fastapi, uvicorn, multipart" 2>/dev/null || "$UV" pip install fastapi uvicorn python-multipart
fi
python rig_server.py

View file

@ -0,0 +1,113 @@
"""Pick the prebuilt flash-attn wheel + matching torch install for this machine.
Building flash-attn from source on Windows takes ages, so we prefer a
precompiled wheel. ``flash_attention_windows.txt`` lists, per row:
Torch;Cuda;Link;PyTorchLink
│ │ │ └ the exact `pip install torch... --index-url ...` command
│ │ │ that pairs with this flash-attn wheel (ABI-matched)
│ │ └ flash-attn wheel URL
│ └ CUDA build the wheel targets (match key against the driver)
└ torch version (informational; also encoded in the wheel + PyTorchLink)
Python is pinned to 3.13 by uv (see .python-version) so it is no longer a match
key — every wheel here is cp313. We just pick the newest CUDA build the driver
can run and hand the caller both pieces to install.
On a match it prints two `KEY=value` lines to stdout:
WHEEL=https://.../flash_attn-...cp313-win_amd64.whl
TORCHARGS=torch==2.12.0 torchvision==0.27.0 --index-url https://download.pytorch.org/whl/cu130
(``TORCHARGS`` is column 4 with the leading ``pip install`` stripped, so the
caller can run it with ``uv pip install``.) On no match it prints nothing.
Diagnostics go to stderr. Standard library + nvidia-smi only.
Override CUDA detection with RIGTOOLS_CUDA (e.g. "12.8").
"""
from __future__ import annotations
import os
import re
import shutil
import subprocess
import sys
from pathlib import Path
WHEELS_FILE = Path(__file__).resolve().parent / "flash_attention_windows.txt"
def driver_cuda() -> float | None:
"""Max CUDA version the NVIDIA driver supports (from nvidia-smi), or None."""
override = os.environ.get("RIGTOOLS_CUDA")
if override:
try:
return float(override)
except ValueError:
pass
exe = shutil.which("nvidia-smi")
if not exe:
return None
try:
out = subprocess.run([exe], capture_output=True, text=True, timeout=20).stdout
except Exception:
return None
m = re.search(r"CUDA(?:\s+\w+)?\s+Version:\s*(\d+)\.(\d+)", out)
return float(f"{m.group(1)}.{m.group(2)}") if m else None
def parse_rows():
"""Yield (torch_ver, cuda: float, wheel_url, torch_args) from the wheels file."""
rows = []
for line in WHEELS_FILE.read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line or line.lower().startswith("torch;"):
continue
parts = [p.strip() for p in line.split(";")]
if len(parts) < 4:
continue
torch_ver, cuda, link, pytorch_cmd = parts[0], parts[1], parts[2], parts[3]
try:
cuda_f = float(cuda)
except ValueError:
continue
# Strip the leading "pip install" (or "uv pip install") so the caller can
# run it via `uv pip install <args>`.
args = re.sub(r"^\s*(uv\s+)?pip\s+install\s+", "", pytorch_cmd).strip()
rows.append((torch_ver, cuda_f, link, args))
return rows
def main() -> None:
py = f"{sys.version_info.major}.{sys.version_info.minor}"
cuda = driver_cuda()
if cuda is None:
print("[flash-attn] No NVIDIA GPU / CUDA detected; skipping prebuilt wheel.", file=sys.stderr)
return
rows = parse_rows()
if not rows:
print("[flash-attn] No usable rows in flash_attention_windows.txt.", file=sys.stderr)
return
# Rows whose CUDA build the driver can run (wheel_cuda <= driver_cuda),
# taking the newest such CUDA build.
candidates = [r for r in rows if r[1] <= cuda + 1e-6]
if not candidates:
avail = sorted({r[1] for r in rows})
print(f"[flash-attn] Driver CUDA {cuda} is older than every listed wheel "
f"(CUDA builds available: {avail}); skipping prebuilt wheel.", file=sys.stderr)
return
torch_ver, wheel_cuda, link, torch_args = max(candidates, key=lambda r: r[1])
if py != "3.13":
print(f"[flash-attn] WARNING: running Python {py}, but the wheels are cp313. "
f"Expect an install failure unless the venv is Python 3.13.", file=sys.stderr)
print(f"[flash-attn] driver CUDA {cuda} -> wheel CUDA {wheel_cuda}, torch {torch_ver}.",
file=sys.stderr)
print(f"WHEEL={link}")
print(f"TORCHARGS={torch_args}")
if __name__ == "__main__":
main()

0
thirdparty/skintokens/src/__init__.py vendored Normal file
View file

View file

View file

@ -0,0 +1 @@
# -*- coding: utf-8 -*-

View file

@ -0,0 +1,30 @@
import torch
from .models.tsal.sal_perceiver import AlignedShapeLatentPerceiver, ShapeAsLatentPerceiverEncoder
def get_encoder(
pretrained_path: str=None,
freeze_decoder: bool=False,
**kwargs
) -> AlignedShapeLatentPerceiver:
model = AlignedShapeLatentPerceiver(**kwargs)
if pretrained_path is not None:
state_dict = torch.load(pretrained_path, weights_only=True)
model.load_state_dict(state_dict)
if freeze_decoder:
model.geo_decoder.requires_grad_(False)
model.encoder.query.requires_grad_(False)
model.pre_kl.requires_grad_(False)
model.post_kl.requires_grad_(False)
model.transformer.requires_grad_(False)
return model
def get_encoder_simplified(
pretrained_path: str=None,
**kwargs
) -> ShapeAsLatentPerceiverEncoder:
model = ShapeAsLatentPerceiverEncoder(**kwargs)
if pretrained_path is not None:
state_dict = torch.load(pretrained_path, weights_only=True)
model.load_state_dict(state_dict)
return model

View file

@ -0,0 +1 @@
# -*- coding: utf-8 -*-

View file

@ -0,0 +1,3 @@
# -*- coding: utf-8 -*-
from .checkpoint import checkpoint

View file

@ -0,0 +1,69 @@
# -*- coding: utf-8 -*-
"""
Adapted from: https://github.com/openai/guided-diffusion/blob/22e0df8183507e13a7813f8d38d51b072ca1e67c/guided_diffusion/nn.py#L124
"""
import torch
from typing import Callable, Iterable, Sequence, Union
def checkpoint(
func: Callable[..., Union[torch.Tensor, Sequence[torch.Tensor]]],
inputs: Sequence[torch.Tensor],
params: Iterable[torch.Tensor],
flag: bool,
use_deepspeed: bool = False
):
"""
Evaluate a function without caching intermediate activations, allowing for
reduced memory at the expense of extra compute in the backward pass.
:param func: the function to evaluate.
:param inputs: the argument sequence to pass to `func`.
:param params: a sequence of parameters `func` depends on but does not
explicitly take as arguments.
:param flag: if False, disable gradient checkpointing.
:param use_deepspeed: if True, use deepspeed
"""
if flag:
if use_deepspeed:
import deepspeed
return deepspeed.checkpointing.checkpoint(func, *inputs)
args = tuple(inputs) + tuple(params)
return CheckpointFunction.apply(func, len(inputs), *args)
else:
return func(*inputs)
class CheckpointFunction(torch.autograd.Function):
@staticmethod
@torch.amp.custom_fwd(device_type='cuda')
def forward(ctx, run_function, length, *args):
ctx.run_function = run_function
ctx.input_tensors = list(args[:length])
ctx.input_params = list(args[length:])
with torch.no_grad():
output_tensors = ctx.run_function(*ctx.input_tensors)
return output_tensors
@staticmethod
@torch.amp.custom_bwd(device_type='cuda')
def backward(ctx, *output_grads):
ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors]
with torch.enable_grad():
# Fixes a bug where the first op in run_function modifies the
# Tensor storage in place, which is not allowed for detach()'d
# Tensors.
shallow_copies = [x.view_as(x) for x in ctx.input_tensors]
output_tensors = ctx.run_function(*shallow_copies)
input_grads = torch.autograd.grad(
output_tensors,
ctx.input_tensors + ctx.input_params,
output_grads,
allow_unused=True,
)
del ctx.input_tensors
del ctx.input_params
del output_tensors
return (None, None) + input_grads

View file

@ -0,0 +1,100 @@
import torch
import numpy as np
from typing import Union, List
class AbstractDistribution(object):
def sample(self):
raise NotImplementedError()
def mode(self):
raise NotImplementedError()
class DiracDistribution(AbstractDistribution):
def __init__(self, value):
self.value = value
def sample(self):
return self.value
def mode(self):
return self.value
class DiagonalGaussianDistribution(object):
def __init__(self, parameters: Union[torch.Tensor, List[torch.Tensor]], deterministic=False, feat_dim=1):
self.feat_dim = feat_dim
self.parameters = parameters
if isinstance(parameters, list):
self.mean = parameters[0]
self.logvar = parameters[1]
else:
self.mean, self.logvar = torch.chunk(parameters, 2, dim=feat_dim)
self.logvar = torch.clamp(self.logvar, -30.0, 20.0)
self.deterministic = deterministic
self.std = torch.exp(0.5 * self.logvar)
self.var = torch.exp(self.logvar)
if self.deterministic:
self.var = self.std = torch.zeros_like(self.mean)
def sample(self):
x = self.mean + self.std * torch.randn_like(self.mean)
return x
def kl(self, other=None, dims=(1, 2, 3)):
if self.deterministic:
return torch.Tensor([0.])
else:
if other is None:
return 0.5 * torch.mean(torch.pow(self.mean, 2)
+ self.var - 1.0 - self.logvar,
dim=dims)
else:
return 0.5 * torch.mean(
torch.pow(self.mean - other.mean, 2) / other.var
+ self.var / other.var - 1.0 - self.logvar + other.logvar,
dim=dims)
def nll(self, sample, dims=(1, 2, 3)):
if self.deterministic:
return torch.Tensor([0.])
logtwopi = np.log(2.0 * np.pi)
return 0.5 * torch.sum(
logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var,
dim=dims)
def mode(self):
return self.mean
def normal_kl(mean1, logvar1, mean2, logvar2):
"""
source: https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/losses.py#L12
Compute the KL divergence between two gaussians.
Shapes are automatically broadcasted, so batches can be compared to
scalars, among other use cases.
"""
tensor = None
for obj in (mean1, logvar1, mean2, logvar2):
if isinstance(obj, torch.Tensor):
tensor = obj
break
assert tensor is not None, "at least one argument must be a Tensor"
# Force variances to be Tensors. Broadcasting helps convert scalars to
# Tensors, but it does not work for torch.exp().
logvar1, logvar2 = [
x if isinstance(x, torch.Tensor) else torch.tensor(x).to(tensor)
for x in (logvar1, logvar2)
]
return 0.5 * (
-1.0
+ logvar2
- logvar1
+ torch.exp(logvar1 - logvar2)
+ ((mean1 - mean2) ** 2) * torch.exp(-logvar2)
)

View file

@ -0,0 +1,213 @@
# -*- coding: utf-8 -*-
import numpy as np
import torch
import torch.nn as nn
import math
VALID_EMBED_TYPES = ["identity", "fourier", "hashgrid", "sphere_harmonic", "triplane_fourier"]
class FourierEmbedder(nn.Module):
"""The sin/cosine positional embedding. Given an input tensor `x` of shape [n_batch, ..., c_dim], it converts
each feature dimension of `x[..., i]` into:
[
sin(x[..., i]),
sin(f_1*x[..., i]),
sin(f_2*x[..., i]),
...
sin(f_N * x[..., i]),
cos(x[..., i]),
cos(f_1*x[..., i]),
cos(f_2*x[..., i]),
...
cos(f_N * x[..., i]),
x[..., i] # only present if include_input is True.
], here f_i is the frequency.
Denote the space is [0 / num_freqs, 1 / num_freqs, 2 / num_freqs, 3 / num_freqs, ..., (num_freqs - 1) / num_freqs].
If logspace is True, then the frequency f_i is [2^(0 / num_freqs), ..., 2^(i / num_freqs), ...];
Otherwise, the frequencies are linearly spaced between [1.0, 2^(num_freqs - 1)].
Args:
num_freqs (int): the number of frequencies, default is 6;
logspace (bool): If logspace is True, then the frequency f_i is [..., 2^(i / num_freqs), ...],
otherwise, the frequencies are linearly spaced between [1.0, 2^(num_freqs - 1)];
input_dim (int): the input dimension, default is 3;
include_input (bool): include the input tensor or not, default is True.
Attributes:
frequencies (torch.Tensor): If logspace is True, then the frequency f_i is [..., 2^(i / num_freqs), ...],
otherwise, the frequencies are linearly spaced between [1.0, 2^(num_freqs - 1);
out_dim (int): the embedding size, if include_input is True, it is input_dim * (num_freqs * 2 + 1),
otherwise, it is input_dim * num_freqs * 2.
"""
def __init__(self,
num_freqs: int = 6,
logspace: bool = True,
input_dim: int = 3,
include_input: bool = True,
include_pi: bool = True) -> None:
"""The initialization"""
super().__init__()
if logspace:
frequencies = 2.0 ** torch.arange(
num_freqs,
dtype=torch.float32
)
else:
frequencies = torch.linspace(
1.0,
2.0 ** (num_freqs - 1),
num_freqs,
dtype=torch.float32
)
if include_pi:
frequencies *= torch.pi
self.register_buffer("frequencies", frequencies, persistent=False)
self.include_input = include_input
self.num_freqs = num_freqs
self.out_dim = self.get_dims(input_dim)
def get_dims(self, input_dim):
temp = 1 if self.include_input or self.num_freqs == 0 else 0
out_dim = input_dim * (self.num_freqs * 2 + temp)
return out_dim
def forward(self, x: torch.Tensor) -> torch.Tensor:
""" Forward process.
Args:
x: tensor of shape [..., dim]
Returns:
embedding: an embedding of `x` of shape [..., dim * (num_freqs * 2 + temp)]
where temp is 1 if include_input is True and 0 otherwise.
"""
if self.num_freqs > 0:
embed = (x[..., None].contiguous() * self.frequencies).view(*x.shape[:-1], -1)
if self.include_input:
return torch.cat((x, embed.sin(), embed.cos()), dim=-1)
else:
return torch.cat((embed.sin(), embed.cos()), dim=-1)
else:
return x
class LearnedFourierEmbedder(nn.Module):
""" following @crowsonkb "s lead with learned sinusoidal pos emb """
""" https://github.com/crowsonkb/v-diffusion-jax/blob/master/diffusion/models/danbooru_128.py#L8 """
def __init__(self, in_channels, dim):
super().__init__()
assert (dim % 2) == 0
half_dim = dim // 2
per_channel_dim = half_dim // in_channels
self.weights = nn.Parameter(torch.randn(per_channel_dim))
def forward(self, x):
"""
Args:
x (torch.FloatTensor): [..., c]
Returns:
x (torch.FloatTensor): [..., d]
"""
# [b, t, c, 1] * [1, d] = [b, t, c, d] -> [b, t, c * d]
freqs = (x[..., None] * self.weights[None] * 2 * np.pi).view(*x.shape[:-1], -1)
fouriered = torch.cat((x, freqs.sin(), freqs.cos()), dim=-1)
return fouriered
class TriplaneLearnedFourierEmbedder(nn.Module):
def __init__(self, in_channels, dim):
super().__init__()
self.yz_plane_embedder = LearnedFourierEmbedder(in_channels, dim)
self.xz_plane_embedder = LearnedFourierEmbedder(in_channels, dim)
self.xy_plane_embedder = LearnedFourierEmbedder(in_channels, dim)
self.out_dim = in_channels + dim
def forward(self, x):
yz_embed = self.yz_plane_embedder(x)
xz_embed = self.xz_plane_embedder(x)
xy_embed = self.xy_plane_embedder(x)
embed = yz_embed + xz_embed + xy_embed
return embed
def sequential_pos_embed(num_len, embed_dim):
assert embed_dim % 2 == 0
pos = torch.arange(num_len, dtype=torch.float32)
omega = torch.arange(embed_dim // 2, dtype=torch.float32)
omega /= embed_dim / 2.
omega = 1. / 10000 ** omega # (D/2,)
pos = pos.reshape(-1) # (M,)
out = torch.einsum("m,d->md", pos, omega) # (M, D/2), outer product
emb_sin = torch.sin(out) # (M, D/2)
emb_cos = torch.cos(out) # (M, D/2)
embeddings = torch.cat([emb_sin, emb_cos], dim=1) # (M, D)
return embeddings
def timestep_embedding(timesteps, dim, max_period=10000):
"""
Create sinusoidal timestep embeddings.
:param timesteps: a 1-D Tensor of N indices, one per batch element.
These may be fractional.
:param dim: the dimension of the output.
:param max_period: controls the minimum frequency of the embeddings.
:return: an [N x dim] Tensor of positional embeddings.
"""
half = dim // 2
freqs = torch.exp(
-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
).to(device=timesteps.device)
args = timesteps[:, None].to(timesteps.dtype) * freqs[None]
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
if dim % 2:
embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
return embedding
def get_embedder(embed_type="fourier", num_freqs=-1, input_dim=3, degree=4,
num_levels=16, level_dim=2, per_level_scale=2, base_resolution=16,
log2_hashmap_size=19, desired_resolution=None):
if embed_type == "identity" or (embed_type == "fourier" and num_freqs == -1):
return nn.Identity(), input_dim
elif embed_type == "fourier":
embedder_obj = FourierEmbedder(num_freqs=num_freqs, input_dim=input_dim,
logspace=True, include_input=True)
return embedder_obj, embedder_obj.out_dim
elif embed_type == "hashgrid":
raise NotImplementedError
elif embed_type == "sphere_harmonic":
raise NotImplementedError
else:
raise ValueError(f"{embed_type} is not valid. Currently only supprts {VALID_EMBED_TYPES}")

View file

@ -0,0 +1,327 @@
# -*- coding: utf-8 -*-
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Optional
import os
from .checkpoint import checkpoint
from ...utils.misc import use_flash3
if use_flash3.is_use:
from flash_attn_interface import flash_attn_func
print("use flash attention 3.")
else:
print("use flash attention 2.")
def init_linear(l, stddev):
nn.init.normal_(l.weight, std=stddev)
if l.bias is not None:
nn.init.constant_(l.bias, 0.0)
def flash_attention(q, k, v):
with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=True, enable_mem_efficient=False):
if use_flash3.is_use:
out, _ = flash_attn_func(q.contiguous(), k.contiguous(), v.contiguous())
# out = flash_attn_func(q, k, v)
# q_ = q.transpose(1, 2)
# k_ = k.transpose(1, 2)
# v_ = v.transpose(1, 2)
# # print(q.shape, k.shape, v.shape)
# out_ = F.scaled_dot_product_attention(q_, k_, v_)
# out_ = out_.transpose(1, 2)
# # print(torch.abs(out - out_).mean())
# assert torch.abs(out - out_).mean() < 1e-2, f"the error {torch.abs(out - out_).mean()} is too large"
# out = out_
# print("use flash_atten 3")
else:
q = q.transpose(1, 2)
k = k.transpose(1, 2)
v = v.transpose(1, 2)
out = F.scaled_dot_product_attention(q, k, v)
out = out.transpose(1, 2)
# print("use flash atten 2")
return out
class MultiheadAttention(nn.Module):
def __init__(
self,
*,
device: torch.device,
dtype: torch.dtype,
n_ctx: int,
width: int,
heads: int,
init_scale: float,
qkv_bias: bool,
flash: bool = False
):
super().__init__()
self.n_ctx = n_ctx
self.width = width
self.heads = heads
self.c_qkv = nn.Linear(width, width * 3, bias=qkv_bias, device=device, dtype=dtype)
self.c_proj = nn.Linear(width, width, device=device, dtype=dtype)
self.attention = QKVMultiheadAttention(device=device, dtype=dtype, heads=heads, n_ctx=n_ctx, flash=flash)
init_linear(self.c_qkv, init_scale)
init_linear(self.c_proj, init_scale)
def forward(self, x):
x = self.c_qkv(x)
x = checkpoint(self.attention, (x,), (), False)
x = self.c_proj(x)
return x
class QKVMultiheadAttention(nn.Module):
def __init__(self, *, device: torch.device, dtype: torch.dtype, heads: int, n_ctx: int, flash: bool = False):
super().__init__()
self.device = device
self.dtype = dtype
self.heads = heads
self.n_ctx = n_ctx
self.flash = flash
def forward(self, qkv):
bs, n_ctx, width = qkv.shape
attn_ch = width // self.heads // 3
scale = 1 / math.sqrt(math.sqrt(attn_ch))
qkv = qkv.view(bs, n_ctx, self.heads, -1)
q, k, v = torch.split(qkv, attn_ch, dim=-1)
if self.flash:
out = flash_attention(q, k, v)
out = out.reshape(out.shape[0], out.shape[1], -1)
else:
weight = torch.einsum(
"bthc,bshc->bhts", q * scale, k * scale
) # More stable with f16 than dividing afterwards
wdtype = weight.dtype
weight = torch.softmax(weight.float(), dim=-1).type(wdtype)
out = torch.einsum("bhts,bshc->bthc", weight, v).reshape(bs, n_ctx, -1)
return out
class ResidualAttentionBlock(nn.Module):
def __init__(
self,
*,
device: torch.device,
dtype: torch.dtype,
n_ctx: int,
width: int,
heads: int,
init_scale: float = 1.0,
qkv_bias: bool = True,
flash: bool = False,
use_checkpoint: bool = False
):
super().__init__()
self.use_checkpoint = use_checkpoint
self.attn = MultiheadAttention(
device=device,
dtype=dtype,
n_ctx=n_ctx,
width=width,
heads=heads,
init_scale=init_scale,
qkv_bias=qkv_bias,
flash=flash
)
self.ln_1 = nn.LayerNorm(width, device=device, dtype=dtype)
self.mlp = MLP(device=device, dtype=dtype, width=width, init_scale=init_scale)
self.ln_2 = nn.LayerNorm(width, device=device, dtype=dtype)
def _forward(self, x: torch.Tensor):
x = x + self.attn(self.ln_1(x))
x = x + self.mlp(self.ln_2(x))
return x
def forward(self, x: torch.Tensor):
return checkpoint(self._forward, (x,), self.parameters(), self.use_checkpoint)
class MultiheadCrossAttention(nn.Module):
def __init__(
self,
*,
device: torch.device,
dtype: torch.dtype,
width: int,
heads: int,
init_scale: float,
qkv_bias: bool = True,
flash: bool = False,
n_data: Optional[int] = None,
data_width: Optional[int] = None,
):
super().__init__()
self.n_data = n_data
self.width = width
self.heads = heads
self.data_width = width if data_width is None else data_width
self.c_q = nn.Linear(width, width, bias=qkv_bias, device=device, dtype=dtype)
self.c_kv = nn.Linear(self.data_width, width * 2, bias=qkv_bias, device=device, dtype=dtype)
self.c_proj = nn.Linear(width, width, device=device, dtype=dtype)
self.attention = QKVMultiheadCrossAttention(
device=device, dtype=dtype, heads=heads, n_data=n_data, flash=flash
)
init_linear(self.c_q, init_scale)
init_linear(self.c_kv, init_scale)
init_linear(self.c_proj, init_scale)
def forward(self, x, data):
x = self.c_q(x)
data = self.c_kv(data)
x = checkpoint(self.attention, (x, data), (), False)
x = self.c_proj(x)
return x
class QKVMultiheadCrossAttention(nn.Module):
def __init__(self, *, device: torch.device, dtype: torch.dtype, heads: int,
flash: bool = False, n_data: Optional[int] = None):
super().__init__()
self.device = device
self.dtype = dtype
self.heads = heads
self.n_data = n_data
self.flash = flash
def forward(self, q, kv):
_, n_ctx, _ = q.shape
bs, n_data, width = kv.shape
attn_ch = width // self.heads // 2
scale = 1 / math.sqrt(math.sqrt(attn_ch))
q = q.view(bs, n_ctx, self.heads, -1)
kv = kv.view(bs, n_data, self.heads, -1)
k, v = torch.split(kv, attn_ch, dim=-1)
if self.flash:
out = flash_attention(q, k, v)
out = out.reshape(out.shape[0], out.shape[1], -1)
else:
weight = torch.einsum(
"bthc,bshc->bhts", q * scale, k * scale
) # More stable with f16 than dividing afterwards
wdtype = weight.dtype
weight = torch.softmax(weight.float(), dim=-1).type(wdtype)
out = torch.einsum("bhts,bshc->bthc", weight, v).reshape(bs, n_ctx, -1)
return out
class ResidualCrossAttentionBlock(nn.Module):
def __init__(
self,
*,
device: Optional[torch.device],
dtype: Optional[torch.dtype],
n_data: Optional[int] = None,
width: int,
heads: int,
data_width: Optional[int] = None,
mlp_width_scale: int = 4,
init_scale: float = 0.25,
qkv_bias: bool = True,
flash: bool = False
):
super().__init__()
if data_width is None:
data_width = width
self.attn = MultiheadCrossAttention(
device=device,
dtype=dtype,
n_data=n_data,
width=width,
heads=heads,
data_width=data_width,
init_scale=init_scale,
qkv_bias=qkv_bias,
flash=flash,
)
self.ln_1 = nn.LayerNorm(width, device=device, dtype=dtype)
self.ln_2 = nn.LayerNorm(data_width, device=device, dtype=dtype)
self.mlp = MLP(device=device, dtype=dtype, width=width, hidden_width_scale=mlp_width_scale, init_scale=init_scale)
self.ln_3 = nn.LayerNorm(width, device=device, dtype=dtype)
def forward(self, x: torch.Tensor, data: torch.Tensor):
x = x + self.attn(self.ln_1(x), self.ln_2(data))
x = x + self.mlp(self.ln_3(x))
return x
class MLP(nn.Module):
def __init__(self, *,
device: Optional[torch.device],
dtype: Optional[torch.dtype],
width: int,
hidden_width_scale: int = 4,
init_scale: float):
super().__init__()
self.width = width
self.c_fc = nn.Linear(width, width * hidden_width_scale, device=device, dtype=dtype)
self.c_proj = nn.Linear(width * hidden_width_scale, width, device=device, dtype=dtype)
self.gelu = nn.GELU()
init_linear(self.c_fc, init_scale)
init_linear(self.c_proj, init_scale)
def forward(self, x):
return self.c_proj(self.gelu(self.c_fc(x)))
class Transformer(nn.Module):
def __init__(
self,
*,
device: Optional[torch.device],
dtype: Optional[torch.dtype],
n_ctx: int,
width: int,
layers: int,
heads: int,
init_scale: float = 0.25,
qkv_bias: bool = True,
flash: bool = False,
use_checkpoint: bool = False
):
super().__init__()
self.n_ctx = n_ctx
self.width = width
self.layers = layers
self.resblocks = nn.ModuleList(
[
ResidualAttentionBlock(
device=device,
dtype=dtype,
n_ctx=n_ctx,
width=width,
heads=heads,
init_scale=init_scale,
qkv_bias=qkv_bias,
flash=flash,
use_checkpoint=use_checkpoint
)
for _ in range(layers)
]
)
def forward(self, x: torch.Tensor):
for block in self.resblocks:
x = block(x)
return x

View file

@ -0,0 +1 @@
# -*- coding: utf-8 -*-

View file

@ -0,0 +1,454 @@
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Optional, Tuple, Dict
from ..modules.distributions import DiagonalGaussianDistribution
from ...utils.eval import compute_psnr
from ...utils import misc
import numpy as np
from copy import deepcopy
def logits_to_sdf(logits):
return torch.sigmoid(logits) * 2 - 1
class KLNearFar(nn.Module):
def __init__(self,
near_weight: float = 0.1,
kl_weight: float = 1.0,
num_near_samples: Optional[int] = None):
super().__init__()
self.near_weight = near_weight
self.kl_weight = kl_weight
self.num_near_samples = num_near_samples
self.geo_criterion = nn.BCEWithLogitsLoss()
def forward(self,
posteriors: Optional[DiagonalGaussianDistribution],
logits: torch.FloatTensor,
labels: torch.FloatTensor,
split: Optional[str] = "train", **kwargs) -> Tuple[torch.FloatTensor, Dict[str, float]]:
"""
Args:
posteriors (DiagonalGaussianDistribution or torch.distributions.Normal):
logits (torch.FloatTensor): [B, 2*N], logits[:, 0:N] is the volume points; logits[:, N:2N] is the near points;
labels (torch.FloatTensor): [B, 2*N], labels[:, 0:N] is the volume points; labels[:, N:2N] is the near points;
split (str):
**kwargs:
Returns:
loss (torch.Tensor): (,)
log (dict):
"""
if self.num_near_samples is None:
num_vol = logits.shape[1] // 2
else:
num_vol = logits.shape[1] - self.num_near_samples
vol_logits = logits[:, 0:num_vol]
vol_labels = labels[:, 0:num_vol]
near_logits = logits[:, num_vol:]
near_labels = labels[:, num_vol:]
# occupancy loss
# vol_bce = self.geo_criterion(vol_logits, vol_labels)
# near_bce = self.geo_criterion(near_logits, near_labels)
vol_bce = self.geo_criterion(vol_logits.float(), vol_labels.float())
near_bce = self.geo_criterion(near_logits.float(), near_labels.float())
if posteriors is None:
kl_loss = torch.tensor(0.0, dtype=vol_logits.dtype, device=vol_logits.device)
else:
kl_loss = posteriors.kl(dims=(1, 2))
kl_loss = torch.mean(kl_loss)
loss = vol_bce + near_bce * self.near_weight + kl_loss * self.kl_weight
with torch.no_grad():
preds = logits >= 0
accuracy = (preds == labels).float()
accuracy = accuracy.mean()
pos_ratio = torch.mean(labels)
log = {
"{}/total_loss".format(split): loss.clone().detach(),
"{}/near".format(split): near_bce.detach(),
"{}/far".format(split): vol_bce.detach(),
"{}/kl".format(split): kl_loss.detach(),
"{}/accuracy".format(split): accuracy,
"{}/pos_ratio".format(split): pos_ratio
}
if posteriors is not None:
log[f"{split}/mean"] = posteriors.mean.mean().detach()
log[f"{split}/std_mean"] = posteriors.std.mean().detach()
log[f"{split}/std_max"] = posteriors.std.max().detach()
return loss, log
class KLNearFarColor(nn.Module):
def __init__(self,
near_weight: float = 0.1,
kl_weight: float = 1.0,
color_weight: float = 1.0,
color_criterion: str = "mse",
num_near_samples: Optional[int] = None):
super().__init__()
self.color_weight = color_weight
self.near_weight = near_weight
self.kl_weight = kl_weight
self.num_near_samples = num_near_samples
if color_criterion == "mse":
self.color_criterion = nn.MSELoss()
elif color_criterion == "l1":
self.color_criterion = nn.L1Loss()
else:
raise ValueError(f"{color_criterion} must be [`mse`, `l1`].")
self.geo_criterion = nn.BCEWithLogitsLoss()
def forward(self,
posteriors: Optional[DiagonalGaussianDistribution],
logits: torch.FloatTensor,
labels: torch.FloatTensor,
pred_colors: torch.FloatTensor,
gt_colors: torch.FloatTensor,
split: Optional[str] = "train", **kwargs) -> Tuple[torch.FloatTensor, Dict[str, float]]:
"""
Args:
posteriors (DiagonalGaussianDistribution or torch.distributions.Normal):
logits (torch.FloatTensor): [B, 2*N], logits[:, 0:N] is the volume points; logits[:, N:2N] is the near points;
labels (torch.FloatTensor): [B, 2*N], labels[:, 0:N] is the volume points; labels[:, N:2N] is the near points;
pred_colors (torch.FloatTensor): [B, M, 3]
gt_colors (torch.FloatTensor): [B, M, 3]
split (str):
**kwargs:
Returns:
loss (torch.Tensor): (,)
log (dict):
"""
if self.num_near_samples is None:
num_vol = logits.shape[1] // 2
else:
num_vol = logits.shape[1] - self.num_near_samples
vol_logits = logits[:, 0:num_vol]
vol_labels = labels[:, 0:num_vol]
near_logits = logits[:, num_vol:]
near_labels = labels[:, num_vol:]
# occupancy loss
# vol_bce = self.geo_criterion(vol_logits, vol_labels)
# near_bce = self.geo_criterion(near_logits, near_labels)
vol_bce = self.geo_criterion(vol_logits.float(), vol_labels.float())
near_bce = self.geo_criterion(near_logits.float(), near_labels.float())
# surface color loss
color = self.color_criterion(pred_colors, gt_colors)
if posteriors is None:
kl_loss = torch.tensor(0.0, dtype=pred_colors.dtype, device=pred_colors.device)
else:
kl_loss = posteriors.kl(dims=(1, 2))
kl_loss = torch.mean(kl_loss)
loss = vol_bce + near_bce * self.near_weight + color * self.color_weight + kl_loss * self.kl_weight
with torch.no_grad():
preds = logits >= 0
accuracy = (preds == labels).float()
accuracy = accuracy.mean()
psnr = compute_psnr(pred_colors, gt_colors)
log = {
"{}/total_loss".format(split): loss.clone().detach(),
"{}/near".format(split): near_bce.detach(),
"{}/far".format(split): vol_bce.detach(),
"{}/color".format(split): color.detach(),
"{}/kl".format(split): kl_loss.detach(),
"{}/psnr".format(split): psnr.detach(),
"{}/accuracy".format(split): accuracy
}
return loss, log
class ContrastKLNearFar(nn.Module):
def __init__(self,
contrast_weight: float = 1.0,
near_weight: float = 0.1,
kl_weight: float = 1.0,
normal_weight: float = 0.0,
surface_weight: float = 0.0,
eikonal_weight: float = 0.0,
sdf_bce_weight: float = 0.0,
sdf_l1l2_weight: float = 1.0,
num_near_samples: Optional[int] = None,
sdf_trunc_val: float = 0.05,
gt_sdf_soft: bool = False,
normal_supervision_type: str = "cosine",
supervision_type: str = 'occupancy'):
super().__init__()
self.labels = None
self.last_local_batch_size = None
self.supervision_type = supervision_type
assert normal_supervision_type in ["l1", "l2", "cosine", "l1_cosine", "l2_cosine", "von_mises"]
self.normal_supervision_type = normal_supervision_type
self.contrast_weight = contrast_weight
self.near_weight = near_weight
self.kl_weight = kl_weight
self.normal_weight = normal_weight
self.surface_weight = surface_weight
self.eikonal_weight = eikonal_weight
self.sdf_bce_weight = sdf_bce_weight # only used in sigmoid-sdf
self.sdf_l1l2_weight = sdf_l1l2_weight # only used in sigmoid-sdf
self.sdf_trunc_val = sdf_trunc_val
self.gt_sdf_soft = gt_sdf_soft
self.num_near_samples = num_near_samples
self.geo_criterion = nn.BCEWithLogitsLoss()
self.geo_criterion_sdf = nn.MSELoss()
def sdf_loss(self, pred_sdf, gt_sdf):
scaled_sdf = gt_sdf / self.sdf_trunc_val
greater_mask = scaled_sdf > 1.
smaller_mask = scaled_sdf < -1.
inside_mask = 1. - greater_mask - smaller_mask
greater_loss = F.smooth_l1_loss(F.relu(1. - pred_sdf), torch.zeros_like(pred_sdf), reduction="none") * greater_mask
smaller_loss = F.smooth_l1_loss(F.relu(pred_sdf + 1.), torch.zeros_like(pred_sdf), reduction="none") * smaller_mask
inside_loss = F.smooth_l1_loss(pred_sdf, gt_sdf, beta=1e-2, reduction="none") * inside_mask
loss = (greater_loss + smaller_loss + inside_loss).mean()
return loss
def von_mises(self, x, y, k=1):
cos = F.cosine_similarity(x, y, dim=-1)
exp = torch.exp(k * (cos - 1))
return 1 - exp
def forward(self,
shape_embed: torch.FloatTensor,
text_embed: torch.FloatTensor,
image_embed: torch.FloatTensor,
logit_scale: torch.FloatTensor,
posteriors: Optional[DiagonalGaussianDistribution],
latents: torch.FloatTensor,
shape_logits: torch.FloatTensor,
shape_labels: torch.FloatTensor,
surface_logits: Optional[torch.FloatTensor],
surface_normals: Optional[torch.FloatTensor],
gt_surface_normals: Optional[torch.FloatTensor],
split: Optional[str] = "train", **kwargs):
if self.supervision_type == 'occupancy':
shape_logits = shape_logits.squeeze(-1)
shape_labels[shape_labels>=0] = 1
shape_labels[shape_labels<0] = 0
elif self.supervision_type == 'occupancy-shapenet':
shape_logits = shape_logits.squeeze(-1)
elif self.supervision_type == 'occupancy-w-surface':
shape_logits = shape_logits.squeeze(-1)
shape_labels[shape_labels==10] = 0
shape_labels[shape_labels>0] = 1
shape_labels[shape_labels<0] = 0
elif 'sdf' in self.supervision_type:
shape_logits = shape_logits.squeeze(-1)
if self.gt_sdf_soft:
shape_labels_sdf = torch.tanh(shape_labels / self.sdf_trunc_val)# * self.sdf_trunc_val
else:
shape_labels_sdf = torch.clamp(shape_labels, min=-self.sdf_trunc_val, max=self.sdf_trunc_val) / self.sdf_trunc_val
else:
raise ValueError(f"Invalid supervision_type {self.supervision_type}")
local_batch_size = shape_embed.size(0)
if local_batch_size != self.last_local_batch_size:
self.labels = local_batch_size * misc.get_rank() + torch.arange(
local_batch_size, device=shape_embed.device
).long()
self.last_local_batch_size = local_batch_size
if text_embed is not None and image_embed is not None:
# normalized features
shape_embed = F.normalize(shape_embed, dim=-1, p=2)
text_embed = F.normalize(text_embed, dim=-1, p=2)
image_embed = F.normalize(image_embed, dim=-1, p=2)
# gather features from all GPUs
shape_embed_all, text_embed_all, image_embed_all = misc.all_gather_batch(
[shape_embed, text_embed, image_embed]
)
# cosine similarity as logits
logits_per_shape_text = logit_scale * shape_embed @ text_embed_all.t()
logits_per_text_shape = logit_scale * text_embed @ shape_embed_all.t()
logits_per_shape_image = logit_scale * shape_embed @ image_embed_all.t()
logits_per_image_shape = logit_scale * image_embed @ shape_embed_all.t()
contrast_loss = (F.cross_entropy(logits_per_shape_text, self.labels) +
F.cross_entropy(logits_per_text_shape, self.labels)) / 2 + \
(F.cross_entropy(logits_per_shape_image, self.labels) +
F.cross_entropy(logits_per_image_shape, self.labels)) / 2
else:
contrast_loss = torch.tensor(0.0, dtype=shape_logits.dtype, device=shape_logits.device)
# shape reconstruction
if self.num_near_samples is None:
num_vol = shape_logits.shape[1] // 2
else:
num_vol = shape_logits.shape[1] - self.num_near_samples
# occupancy/sdf loss
if self.supervision_type == 'occupancy' or self.supervision_type == 'occupancy-shapenet':
vol_logits = shape_logits[:, 0:num_vol]
vol_labels = shape_labels[:, 0:num_vol]
near_logits = shape_logits[:, num_vol:]
near_labels = shape_labels[:, num_vol:]
vol_loss = self.geo_criterion(vol_logits.float(), vol_labels.float())
near_loss = self.geo_criterion(near_logits.float(), near_labels.float())
elif 'sdf' in self.supervision_type:
if self.supervision_type == "sigmoid-sdf":
shape_sdfs = logits_to_sdf(shape_logits)
else:
shape_sdfs = shape_logits
vol_logits = shape_logits[:, 0:num_vol]
vol_sdfs = shape_sdfs[:, 0:num_vol]
vol_labels_sdf = shape_labels_sdf[:, 0:num_vol]
near_logits= shape_logits[:, num_vol:]
near_sdfs = shape_sdfs[:, num_vol:]
near_labels_sdf = shape_labels_sdf[:, num_vol:]
# use both sdf loss and occupancy loss
vol_loss = torch.mean(torch.abs(vol_sdfs - vol_labels_sdf)) + torch.mean((vol_sdfs - vol_labels_sdf) ** 2) #+ self.geo_criterion(vol_logits_sdf, vol_labels)
near_loss = torch.mean(torch.abs(near_sdfs - near_labels_sdf)) + torch.mean((near_sdfs - near_labels_sdf) ** 2) #+ self.geo_criterion(near_logits_sdf, near_labels)
if self.supervision_type == "sigmoid-sdf":
vol_labels = (vol_labels_sdf + 1) / 2
near_labels = (near_labels_sdf + 1) / 2
vol_loss = self.sdf_l1l2_weight * vol_loss + self.sdf_bce_weight * self.geo_criterion(vol_logits, vol_labels)
near_loss = self.sdf_l1l2_weight * near_loss + self.sdf_bce_weight * self.geo_criterion(near_logits, near_labels)
# print(vol_loss, self.sdf_bce_weight * self.geo_criterion(vol_logits, vol_labels))
# surface loss
if "sdf" in self.supervision_type and surface_logits is not None:
if self.supervision_type == "sigmoid-sdf":
surface_sdfs = logits_to_sdf(surface_logits)
else:
surface_sdfs = surface_logits
surface_loss = torch.mean(surface_sdfs ** 2)
else:
surface_loss = torch.tensor(0.0, dtype=shape_logits.dtype, device=shape_logits.device)
if surface_normals is not None and gt_surface_normals is not None and "sdf" in self.supervision_type:
valid_mask = surface_sdfs.squeeze(-1) < (self.sdf_trunc_val * 0.8)
if valid_mask is not None:
surface_normals = surface_normals[valid_mask]
gt_surface_normals = gt_surface_normals[valid_mask]
# eikonal loss
surface_normals_norm = torch.norm(surface_normals, dim=-1)
eikonal_loss = F.mse_loss(surface_normals_norm * self.sdf_trunc_val, surface_normals_norm.new_ones(surface_normals_norm.shape), reduction="mean")
# surface normal loss
# surface_normals = F.normalize(surface_normals, dim=-1)
surface_normals = surface_normals * self.sdf_trunc_val
gt_surface_normals = F.normalize(gt_surface_normals, dim=-1)
if self.normal_supervision_type == "cosine":
# use cosine similarity loss
normal_loss = 1 - F.cosine_similarity(F.normalize(surface_normals, dim=-1), gt_surface_normals, dim=-1).mean()
elif self.normal_supervision_type == "l1":
# use l1 loss
normal_loss = F.l1_loss(surface_normals, gt_surface_normals)
elif self.normal_supervision_type == "l2":
normal_loss = F.mse_loss(surface_normals, gt_surface_normals)
elif self.normal_supervision_type == "von_mises":
normal_loss = self.von_mises(surface_normals, gt_surface_normals).mean()
elif self.normal_supervision_type == "l1_cosine":
normal_loss_cos = 1 - F.cosine_similarity(F.normalize(surface_normals, dim=-1), gt_surface_normals, dim=-1).mean()
normal_loss_l1 = F.l1_loss(surface_normals, gt_surface_normals)
normal_loss = normal_loss_cos + normal_loss_l1
elif self.normal_supervision_type == "l2_cosine":
normal_loss_cos = 1 - F.cosine_similarity(F.normalize(surface_normals, dim=-1), gt_surface_normals, dim=-1).mean()
normal_loss_l2 = F.mse_loss(surface_normals, gt_surface_normals)
normal_loss = normal_loss_cos + normal_loss_l2
else:
raise NotImplementedError
else:
normal_loss = torch.tensor(0.0, dtype=shape_logits.dtype, device=shape_logits.device)
eikonal_loss = torch.tensor(0.0, dtype=shape_logits.dtype, device=shape_logits.device)
surface_normals_norm = torch.tensor(0.0, dtype=shape_logits.dtype, device=shape_logits.device)
if posteriors is None:
kl_loss = torch.tensor(0.0, dtype=shape_logits.dtype, device=shape_logits.device)
else:
kl_loss = posteriors.kl(dims=(1, 2))
kl_loss = torch.mean(kl_loss)
loss = vol_loss + near_loss * self.near_weight + kl_loss * self.kl_weight + contrast_loss * self.contrast_weight + normal_loss * self.normal_weight + self.eikonal_weight * eikonal_loss + self.surface_weight * surface_loss
# compute accuracy
with torch.no_grad():
if "sdf" in self.supervision_type:
preds = shape_sdfs >= 0
sdf_labels = shape_labels_sdf >= 0
accuracy = (preds == sdf_labels).float()
else:
preds = shape_logits >= 0
accuracy = (preds == shape_labels).float()
accuracy = accuracy.mean()
log = {
# "{}/contrast".format(split): contrast_loss.clone().detach(),
"{}/near".format(split): near_loss.detach(),
"{}/far".format(split): vol_loss.detach(),
"{}/normal".format(split): normal_loss.detach(),
"{}/surface".format(split): surface_loss.detach(),
"{}/eikonal".format(split): eikonal_loss.detach(),
"{}/kl".format(split): kl_loss.detach(),
"{}/surface_grad_norm".format(split): surface_normals_norm.mean().detach(),
# "{}/shape_text_acc".format(split): shape_text_acc,
# "{}/shape_image_acc".format(split): shape_image_acc,
"{}/total_loss".format(split): loss.clone().detach(),
"{}/accuracy".format(split): accuracy,
}
if posteriors is not None:
log[f"{split}/posteriors_mean"] = posteriors.mean.mean().detach()
log[f"{split}/posteriors_std_mean"] = posteriors.std.mean().detach()
log[f"{split}/posteriors_std_max"] = posteriors.std.max().detach()
return loss, log, near_loss

View file

@ -0,0 +1,723 @@
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
from typing import Optional, Union
from einops import repeat
import math
import random
import time
import numpy as np
from ..modules import checkpoint
from ..modules.embedder import FourierEmbedder
from ..modules.distributions import DiagonalGaussianDistribution
from ..modules.transformer_blocks import (
ResidualCrossAttentionBlock,
Transformer
)
from ...utils.misc import use_flash3
from .tsal_base import ShapeAsLatentModule
from .loss import logits_to_sdf
from ....utils import fps
class CrossAttentionEncoder(nn.Module):
def __init__(self, *,
device: Optional[torch.device],
dtype: Optional[torch.dtype],
num_latents: int,
fourier_embedder: FourierEmbedder,
point_feats: int,
width: int,
heads: int,
layers: int,
init_scale: float = 0.25,
qkv_bias: bool = True,
flash: bool = False,
use_ln_post: bool = False,
use_checkpoint: bool = False,
query_method: bool = False,
use_full_input: bool = True,
token_num: int = 256,
no_query: bool=False):
super().__init__()
self.query_method = query_method
self.token_num = token_num
self.use_full_input = use_full_input
self.use_checkpoint = use_checkpoint
self.num_latents = num_latents
if no_query:
self.query = None
else:
self.query = nn.Parameter(torch.randn((num_latents, width), device=device, dtype=dtype) * 0.02)
self.fourier_embedder = fourier_embedder
self.input_proj = nn.Linear(self.fourier_embedder.out_dim + point_feats, width, device=device, dtype=dtype)
self.cross_attn = ResidualCrossAttentionBlock(
device=device,
dtype=dtype,
width=width,
heads=heads,
init_scale=init_scale,
qkv_bias=qkv_bias,
flash=flash,
)
self.self_attn = Transformer(
device=device,
dtype=dtype,
n_ctx=num_latents,
width=width,
layers=layers,
heads=heads,
init_scale=init_scale,
qkv_bias=qkv_bias,
flash=flash,
use_checkpoint=False
)
if use_ln_post:
self.ln_post = nn.LayerNorm(width, dtype=dtype, device=device)
else:
self.ln_post = None
def _forward(self, pc, feats):
"""
Args:
pc (torch.FloatTensor): [B, N, 3]
feats (torch.FloatTensor or None): [B, N, C]
Returns:
"""
if self.query_method:
token_num = self.num_latents
bs = pc.shape[0] #pc [10, 204800, 3]
data = self.fourier_embedder(pc) #[10, 204800, 51]
if feats is not None: #[10, 204800, 3]
data = torch.cat([data, feats], dim=-1)
data = self.input_proj(data) #[10, 204800, 768]
query = repeat(self.query, "m c -> b m c", b=bs) #[10, 257, 768]
latents = self.cross_attn(query, data)
latents = self.self_attn(latents)
if self.ln_post is not None:
latents = self.ln_post(latents)
pre_pc = None
else:
if isinstance(self.token_num, int):
token_num = self.token_num
else:
token_num = random.choice(self.token_num)
# print(token_num,'-----------------------', flush=True)
if self.training:
rng = np.random.default_rng()
else:
rng = np.random.default_rng(seed=0)
ind = rng.choice(pc.shape[1], token_num * 4, replace=token_num * 4 > pc.shape[1])
pre_pc = pc[:,ind,:]
pre_feats = feats[:,ind,:]
B, N, D = pre_pc.shape #[10, 204800, 3]
C = pre_feats.shape[-1]
###### fps
pos = pre_pc.view(B*N, D)
pos_feats = pre_feats.view(B*N, C)
batch = torch.arange(B).to(pc.device)
batch = torch.repeat_interleave(batch, N)
# ratio = 1.0 * token_num / N
idx = fps(pos, batch, ratio=1. / 4, random_start=self.training)
sampled_pc = pos[idx]
sampled_pc = sampled_pc.view(B, -1, 3)
sampled_feats = pos_feats[idx]
sampled_feats = sampled_feats.view(B, -1, C)
######
if self.use_full_input:
data = self.fourier_embedder(pc) #[B, 20480, 51]
else:
data = self.fourier_embedder(pre_pc) # [B, 4 * token_num, 51]
if feats is not None: #[10, 204800, 3]
if not self.use_full_input:
feats = pre_feats
data = torch.cat([data, feats], dim=-1) #[10, 204800, 54]
data = self.input_proj(data) #[10, 204800, 768]
# print(data.shape)
sampled_data = self.fourier_embedder(sampled_pc) #[10, 256, 51]
if feats is not None: #[10, 256, 3]
sampled_data = torch.cat([sampled_data, sampled_feats], dim=-1) #[10, 256, 54]
sampled_data = self.input_proj(sampled_data) #[10, 256, 768]
latents = self.cross_attn(sampled_data, data) #[10, 256, 768]
latents = self.self_attn(latents)
if self.ln_post is not None:
latents = self.ln_post(latents)
pre_pc = torch.cat([pre_pc, pre_feats], dim=-1)
return latents, pc, token_num, pre_pc
def forward(self, pc: torch.FloatTensor, feats: Optional[torch.FloatTensor] = None):
"""
Args:
pc (torch.FloatTensor): [B, N, 3]
feats (torch.FloatTensor or None): [B, N, C]
Returns:
dict
"""
return checkpoint(self._forward, (pc, feats), self.parameters(), self.use_checkpoint)
class CrossAttentionDecoder(nn.Module):
def __init__(self, *,
device: Optional[torch.device],
dtype: Optional[torch.dtype],
num_latents: int,
out_channels: int,
fourier_embedder: FourierEmbedder,
width: int,
heads: int,
init_scale: float = 0.25,
qkv_bias: bool = True,
flash: bool = False,
use_checkpoint: bool = False,
mlp_width_scale: int = 4,
supervision_type: str = 'occupancy'):
super().__init__()
self.use_checkpoint = use_checkpoint
self.fourier_embedder = fourier_embedder
self.supervision_type = supervision_type
self.query_proj = nn.Linear(self.fourier_embedder.out_dim, width, device=device, dtype=dtype)
self.cross_attn_decoder = ResidualCrossAttentionBlock(
device=device,
dtype=dtype,
n_data=num_latents,
width=width,
heads=heads,
init_scale=init_scale,
qkv_bias=qkv_bias,
flash=flash,
mlp_width_scale=mlp_width_scale,
)
self.ln_post = nn.LayerNorm(width, device=device, dtype=dtype)
self.output_proj = nn.Linear(width, out_channels, device=device, dtype=dtype)
if self.supervision_type == 'occupancy-sdf':
self.output_proj_sdf = nn.Linear(width, out_channels, device=device, dtype=dtype)
def _forward(self, queries: torch.FloatTensor, latents: torch.FloatTensor):
if next(self.query_proj.parameters()).dtype == torch.float16:
queries = queries.half()
latents = latents.half()
# print(f"queries: {queries.dtype}, {queries.device}")
# print(f"latents: {latents.dtype}, {latents.device}"z)
queries = self.query_proj(self.fourier_embedder(queries))
x = self.cross_attn_decoder(queries, latents)
x = self.ln_post(x)
x_1 = self.output_proj(x)
if self.supervision_type == 'occupancy-sdf':
x_2 = self.output_proj_sdf(x)
return x_1, x_2
else:
return x_1
def forward(self, queries: torch.FloatTensor, latents: torch.FloatTensor):
return checkpoint(self._forward, (queries, latents), self.parameters(), self.use_checkpoint)
class ShapeAsLatentPerceiver(ShapeAsLatentModule):
def __init__(self, *,
device: Optional[torch.device],
dtype: Optional[torch.dtype],
num_latents: int,
point_feats: int = 0,
embed_dim: int = 0,
num_freqs: int = 8,
include_pi: bool = True,
width: int,
heads: int,
num_encoder_layers: int,
num_decoder_layers: int,
decoder_width: Optional[int] = None,
init_scale: float = 0.25,
qkv_bias: bool = True,
flash: bool = False,
use_ln_post: bool = False,
use_checkpoint: bool = False,
supervision_type: str = 'occupancy',
query_method: bool = False,
token_num: int = 256,
grad_type: str = "numerical",
grad_interval: float = 0.005,
use_full_input: bool = True,
freeze_encoder: bool = False,
decoder_mlp_width_scale: int = 4,
residual_kl: bool = False,
):
super().__init__()
self.use_checkpoint = use_checkpoint
self.num_latents = num_latents
assert grad_type in ["numerical", "analytical"]
self.grad_type = grad_type
self.grad_interval = grad_interval
self.supervision_type = supervision_type
self.fourier_embedder = FourierEmbedder(num_freqs=num_freqs, include_pi=include_pi)
init_scale = init_scale * math.sqrt(1.0 / width)
self.encoder = CrossAttentionEncoder(
device=device,
dtype=dtype,
fourier_embedder=self.fourier_embedder,
num_latents=num_latents,
point_feats=point_feats,
width=width,
heads=heads,
layers=num_encoder_layers,
init_scale=init_scale,
qkv_bias=qkv_bias,
flash=flash,
use_ln_post=use_ln_post,
use_checkpoint=use_checkpoint,
query_method=query_method,
use_full_input=use_full_input,
token_num=token_num
)
self.embed_dim = embed_dim
self.residual_kl = residual_kl
if decoder_width is None:
decoder_width = width
if embed_dim > 0:
# VAE embed
self.pre_kl = nn.Linear(width, embed_dim * 2, device=device, dtype=dtype)
self.post_kl = nn.Linear(embed_dim, decoder_width, device=device, dtype=dtype)
self.latent_shape = (num_latents, embed_dim)
if self.residual_kl:
assert self.post_kl.out_features % self.post_kl.in_features == 0
assert self.pre_kl.in_features % self.pre_kl.out_features == 0
else:
self.latent_shape = (num_latents, width)
print("decoder width = ", decoder_width)
self.transformer = Transformer(
device=device,
dtype=dtype,
n_ctx=num_latents,
width=decoder_width,
layers=num_decoder_layers,
heads=heads,
init_scale=init_scale,
qkv_bias=qkv_bias,
flash=flash,
use_checkpoint=use_checkpoint
)
# geometry decoder
self.geo_decoder = CrossAttentionDecoder(
device=device,
dtype=dtype,
fourier_embedder=self.fourier_embedder,
out_channels=1,
num_latents=num_latents,
width=decoder_width,
heads=heads,
init_scale=init_scale,
qkv_bias=qkv_bias,
flash=flash,
use_checkpoint=use_checkpoint,
supervision_type=supervision_type,
mlp_width_scale=decoder_mlp_width_scale
)
if freeze_encoder:
for p in self.encoder.parameters():
p.requires_grad = False
for p in self.pre_kl.parameters():
p.requires_grad = False
print("freeze encoder and pre kl")
def encode(self,
pc: torch.FloatTensor,
feats: Optional[torch.FloatTensor] = None,
sample_posterior: bool = True):
"""
Args:
pc (torch.FloatTensor): [B, N, 3]
feats (torch.FloatTensor or None): [B, N, C]
sample_posterior (bool):
Returns:
latents (torch.FloatTensor)
center_pos (torch.FloatTensor or None):
posterior (DiagonalGaussianDistribution or None):
"""
latents, center_pos = self.encoder(pc, feats)
posterior = None
if self.embed_dim > 0:
moments = self.pre_kl(latents)
if self.residual_kl:
B, N = latents.shape[:2]
moments = moments + latents.view(B, N, -1, self.pre_kl.out_features).mean(dim=-2)
posterior = DiagonalGaussianDistribution(moments, feat_dim=-1)
if sample_posterior:
latents = posterior.sample()
else:
latents = posterior.mode()
return latents, center_pos, posterior
def decode(self, latents: torch.FloatTensor):
if self.residual_kl:
latents = latents.repeat_interleave(self.post_kl.out_features // self.post_kl.in_features, dim=-1) + self.post_kl(latents)
else:
latents = self.post_kl(latents)
return self.transformer(latents)
def query_geometry(self, queries: torch.FloatTensor, latents: torch.FloatTensor, grad: bool = False):
# logits = self.geo_decoder(queries, latents).squeeze(-1)
if grad:
# with torch.autocast(device_type="cuda", dtype=torch.float32):
if self.grad_type == "numerical":
raise NotImplementedError
interval = self.grad_interval
# print('grad interval = ', interval)
grad_value = []
for offset in [(interval, 0, 0), (0, interval, 0), (0, 0, interval)]:
offset_tensor = torch.tensor(offset, device=queries.device)[None, :]
res_p = self.geo_decoder(queries + offset_tensor, latents)[..., 0]
res_n = self.geo_decoder(queries - offset_tensor, latents)[..., 0]
grad_value.append((res_p - res_n) / (2 * interval))
grad_value = torch.stack(grad_value, dim=-1)
else:
# print("auto grad")
queries_d = torch.clone(queries)
queries_d.requires_grad = True
with torch.enable_grad():
with use_flash3.disable_flash3():
logits = self.geo_decoder(queries_d, latents)
if self.supervision_type == "sigmoid-sdf":
sdfs = logits_to_sdf(logits)
grad_value = torch.autograd.grad(sdfs, [queries_d],
grad_outputs=torch.ones_like(sdfs),
create_graph=self.geo_decoder.training)[0]
else:
logits = self.geo_decoder(queries, latents)
grad_value = None
return logits, grad_value
def forward(self,
pc: torch.FloatTensor,
feats: torch.FloatTensor,
volume_queries: torch.FloatTensor,
sample_posterior: bool = True):
"""
Args:
pc (torch.FloatTensor): [B, N, 3]
feats (torch.FloatTensor or None): [B, N, C]
volume_queries (torch.FloatTensor): [B, P, 3]
sample_posterior (bool):
Returns:
logits (torch.FloatTensor): [B, P]
center_pos (torch.FloatTensor): [B, M, 3]
posterior (DiagonalGaussianDistribution or None).
"""
latents, center_pos, posterior = self.encode(pc, feats, sample_posterior=sample_posterior)
latents = self.decode(latents)
logits = self.query_geometry(volume_queries, latents)
return logits, center_pos, posterior
class AlignedShapeLatentPerceiver(ShapeAsLatentPerceiver):
def __init__(self, *,
device: Optional[torch.device],
dtype: Optional[str],
num_latents: int,
point_feats: int = 0,
embed_dim: int = 0,
num_freqs: int = 8,
include_pi: bool = True,
width: int,
heads: int,
num_encoder_layers: int,
num_decoder_layers: int,
decoder_width: Optional[int] = None,
init_scale: float = 0.25,
qkv_bias: bool = True,
flash: bool = False,
use_ln_post: bool = False,
use_checkpoint: bool = False,
supervision_type: str = 'occupancy',
grad_type: str = "numerical",
grad_interval: float = 0.005,
query_method: bool = False,
use_full_input: bool = True,
token_num: int = 256,
freeze_encoder: bool = False,
decoder_mlp_width_scale: int = 4,
residual_kl: bool = False,
):
MAP_DTYPE = {
'float32': torch.float32,
'float16': torch.float16,
'bfloat16': torch.bfloat16,
}
if dtype is not None:
dtype = MAP_DTYPE[dtype]
super().__init__(
device=device,
dtype=dtype,
num_latents=1 + num_latents,
point_feats=point_feats,
embed_dim=embed_dim,
num_freqs=num_freqs,
include_pi=include_pi,
width=width,
decoder_width=decoder_width,
heads=heads,
num_encoder_layers=num_encoder_layers,
num_decoder_layers=num_decoder_layers,
init_scale=init_scale,
qkv_bias=qkv_bias,
flash=flash,
use_ln_post=use_ln_post,
use_checkpoint=use_checkpoint,
supervision_type=supervision_type,
grad_type=grad_type,
grad_interval=grad_interval,
query_method=query_method,
token_num=token_num,
use_full_input=use_full_input,
freeze_encoder=freeze_encoder,
decoder_mlp_width_scale=decoder_mlp_width_scale,
residual_kl=residual_kl,
)
self.width = width
def encode(self,
pc: torch.FloatTensor,
feats: Optional[torch.FloatTensor] = None,
sample_posterior: bool = True,
only_shape: bool=False):
"""
Args:
pc (torch.FloatTensor): [B, N, 3]
feats (torch.FloatTensor or None): [B, N, c]
sample_posterior (bool):
Returns:
shape_embed (torch.FloatTensor)
kl_embed (torch.FloatTensor):
posterior (DiagonalGaussianDistribution or None):
"""
shape_embed, latents, token_num, pre_pc = self.encode_latents(pc, feats)
if only_shape:
return shape_embed
kl_embed, posterior = self.encode_kl_embed(latents, sample_posterior)
return shape_embed, kl_embed, posterior, token_num, pre_pc
def encode_latents(self,
pc: torch.FloatTensor,
feats: Optional[torch.FloatTensor] = None):
x, _, token_num, pre_pc = self.encoder(pc, feats)
shape_embed = x[:, 0]
# latents = x[:, 1:]
# use all tokens
latents = x
return shape_embed, latents, token_num, pre_pc
def encode_kl_embed(self, latents: torch.FloatTensor, sample_posterior: bool = True):
posterior = None
if self.embed_dim > 0:
moments = self.pre_kl(latents)
if self.residual_kl:
B, N = latents.shape[:2]
moments = moments + latents.view(B, N, -1, self.pre_kl.out_features).mean(dim=-2)
posterior = DiagonalGaussianDistribution(moments, feat_dim=-1)
if sample_posterior:
kl_embed = posterior.sample()
else:
kl_embed = posterior.mode()
else:
kl_embed = latents
return kl_embed, posterior
def forward(self,
pc: torch.FloatTensor,
feats: torch.FloatTensor,
volume_queries: torch.FloatTensor,
sample_posterior: bool = True):
"""
Args:
pc (torch.FloatTensor): [B, N, 3]
feats (torch.FloatTensor or None): [B, N, C]
volume_queries (torch.FloatTensor): [B, P, 3]
sample_posterior (bool):
Returns:
shape_embed (torch.FloatTensor): [B, projection_dim]
logits (torch.FloatTensor): [B, M]
posterior (DiagonalGaussianDistribution or None).
"""
shape_embed, kl_embed, posterior, token_num, pre_pc = self.encode(pc, feats, sample_posterior=sample_posterior)
latents = self.decode(kl_embed)
logits, grad = self.query_geometry(volume_queries, latents)
return shape_embed, logits, posterior, token_num, pre_pc, grad
#####################################################
# a simplified verstion of perceiver encoder
#####################################################
class ShapeAsLatentPerceiverEncoder(ShapeAsLatentModule):
def __init__(self, *,
device: Optional[torch.device],
dtype: Optional[Union[torch.dtype, str]],
num_latents: int,
point_feats: int = 0,
embed_dim: int = 0,
num_freqs: int = 8,
include_pi: bool = True,
width: int,
heads: int,
num_encoder_layers: int,
init_scale: float = 0.25,
qkv_bias: bool = True,
flash: bool = False,
use_ln_post: bool = False,
use_checkpoint: bool = False,
supervision_type: str = 'occupancy',
query_method: bool = False,
token_num: int = 256,
grad_type: str = "numerical",
grad_interval: float = 0.005,
use_full_input: bool = True,
freeze_encoder: bool = False,
residual_kl: bool = False,
):
super().__init__()
MAP_DTYPE = {
'float32': torch.float32,
'float16': torch.float16,
'bfloat16': torch.bfloat16,
}
if dtype is not None and isinstance(dtype, str):
dtype = MAP_DTYPE[dtype]
self.use_checkpoint = use_checkpoint
self.num_latents = num_latents
assert grad_type in ["numerical", "analytical"]
self.grad_type = grad_type
self.grad_interval = grad_interval
self.supervision_type = supervision_type
self.fourier_embedder = FourierEmbedder(num_freqs=num_freqs, include_pi=include_pi)
init_scale = init_scale * math.sqrt(1.0 / width)
self.encoder = CrossAttentionEncoder(
device=device,
dtype=dtype,
fourier_embedder=self.fourier_embedder,
num_latents=num_latents,
point_feats=point_feats,
width=width,
heads=heads,
layers=num_encoder_layers,
init_scale=init_scale,
qkv_bias=qkv_bias,
flash=flash,
use_ln_post=use_ln_post,
use_checkpoint=use_checkpoint,
query_method=query_method,
use_full_input=use_full_input,
token_num=token_num,
no_query=True,
)
self.embed_dim = embed_dim
self.residual_kl = residual_kl
if freeze_encoder:
for p in self.encoder.parameters():
p.requires_grad = False
print("freeze encoder")
self.width = width
def encode_latents(self,
pc: torch.FloatTensor,
feats: Optional[torch.FloatTensor] = None):
x, _, token_num, pre_pc = self.encoder(pc, feats)
shape_embed = x[:, 0]
latents = x
return shape_embed, latents, token_num, pre_pc
def forward(self):
raise NotImplementedError()

View file

@ -0,0 +1,121 @@
# -*- coding: utf-8 -*-
import torch.nn as nn
from typing import Tuple, List, Optional
import lightning.pytorch as pl
class Point2MeshOutput(object):
def __init__(self):
self.mesh_v = None
self.mesh_f = None
self.center = None
self.pc = None
class Latent2MeshOutput(object):
def __init__(self):
self.mesh_v = None
self.mesh_f = None
class AlignedMeshOutput(object):
def __init__(self):
self.mesh_v = None
self.mesh_f = None
self.surface = None
self.image = None
self.text: Optional[str] = None
self.shape_text_similarity: Optional[float] = None
self.shape_image_similarity: Optional[float] = None
class ShapeAsLatentPLModule(pl.LightningModule):
latent_shape: Tuple[int]
def encode(self, surface, *args, **kwargs):
raise NotImplementedError
def decode(self, z_q, *args, **kwargs):
raise NotImplementedError
def latent2mesh(self, latents, *args, **kwargs) -> List[Latent2MeshOutput]:
raise NotImplementedError
def point2mesh(self, *args, **kwargs) -> List[Point2MeshOutput]:
raise NotImplementedError
class ShapeAsLatentModule(nn.Module):
latent_shape: Tuple[int, int]
def __init__(self, *args, **kwargs):
super().__init__()
def encode(self, *args, **kwargs):
raise NotImplementedError
def decode(self, *args, **kwargs):
raise NotImplementedError
def query_geometry(self, *args, **kwargs):
raise NotImplementedError
class AlignedShapeAsLatentPLModule(pl.LightningModule):
latent_shape: Tuple[int]
def set_shape_model_only(self):
raise NotImplementedError
def encode(self, surface, *args, **kwargs):
raise NotImplementedError
def decode(self, z_q, *args, **kwargs):
raise NotImplementedError
def latent2mesh(self, latents, *args, **kwargs) -> List[Latent2MeshOutput]:
raise NotImplementedError
def point2mesh(self, *args, **kwargs) -> List[Point2MeshOutput]:
raise NotImplementedError
class AlignedShapeAsLatentModule(nn.Module):
shape_model: ShapeAsLatentModule
latent_shape: Tuple[int, int]
def __init__(self, *args, **kwargs):
super().__init__()
def set_shape_model_only(self):
raise NotImplementedError
def encode_image_embed(self, *args, **kwargs):
raise NotImplementedError
def encode_text_embed(self, *args, **kwargs):
raise NotImplementedError
def encode_shape_embed(self, *args, **kwargs):
raise NotImplementedError
class TexturedShapeAsLatentModule(nn.Module):
def __init__(self, *args, **kwargs):
super().__init__()
def encode(self, *args, **kwargs):
raise NotImplementedError
def decode(self, *args, **kwargs):
raise NotImplementedError
def query_geometry(self, *args, **kwargs):
raise NotImplementedError
def query_color(self, *args, **kwargs):
raise NotImplementedError

View file

@ -0,0 +1,4 @@
# -*- coding: utf-8 -*-
from .misc import get_config_from_file
from .misc import instantiate_from_config

View file

@ -0,0 +1,12 @@
# -*- coding: utf-8 -*-
import torch
def compute_psnr(x, y, data_range: float = 2, eps: float = 1e-7):
mse = torch.mean((x - y) ** 2)
psnr = 10 * torch.log10(data_range / (mse + eps))
return psnr

View file

@ -0,0 +1,262 @@
# -*- coding: utf-8 -*-
import importlib
from omegaconf import OmegaConf, DictConfig, ListConfig
import time
import torch
import torch.distributed as dist
from typing import Union, Any, Optional
from collections import defaultdict
from torch.optim import lr_scheduler
import os
from dataclasses import dataclass, field
from contextlib import contextmanager
import logging
logger = logging.getLogger(__name__)
def calc_num_train_steps(num_data, batch_size, max_epochs, num_nodes, num_cards=8):
return int(num_data / (num_nodes * num_cards * batch_size)) * max_epochs
OmegaConf.register_new_resolver("calc_num_train_steps", calc_num_train_steps)
OmegaConf.register_new_resolver("mul", lambda a, b: a * b)
@dataclass
class ExperimentConfig:
task: str = "vae"
output_dir: str = "outputs"
resume: Optional[str] = None
data: dict = field(default_factory=dict)
model: dict = field(default_factory=dict)
trainer: dict = field(default_factory=dict)
checkpoint: dict = field(default_factory=dict)
wandb: dict = field(default_factory=dict)
def parse_structured(fields: Any, cfg: Optional[Union[dict, DictConfig]] = None) -> Any:
scfg = OmegaConf.merge(OmegaConf.structured(fields), cfg)
return scfg
def get_config_from_file(config_file: str, cli_args: list = [], **kwargs) -> Union[DictConfig, ListConfig]:
config_file = OmegaConf.load(config_file)
cli_conf = OmegaConf.from_cli(cli_args)
if 'base_config' in config_file.keys():
if config_file['base_config'] == "default_base":
base_config = OmegaConf.create()
# base_config = get_default_config()
elif config_file['base_config'].endswith(".yaml"):
base_config = get_config_from_file(config_file['base_config'])
else:
raise ValueError(f"{config_file} must be `.yaml` file or it contains `base_config` key.")
config_file = {key: value for key, value in config_file.items() if key != "base_config"}
cfg = OmegaConf.merge(base_config, config_file, cli_conf, kwargs)
else:
cfg = OmegaConf.merge(config_file, cli_conf, kwargs)
scfg: ExperimentConfig = parse_structured(ExperimentConfig, cfg)
return scfg
def get_obj_from_str(string, reload=False):
module, cls = string.rsplit(".", 1)
if reload:
module_imp = importlib.import_module(module)
importlib.reload(module_imp)
return getattr(importlib.import_module(module, package=None), cls)
def get_obj_from_config(config):
if "target" not in config:
raise KeyError("Expected key `target` to instantiate.")
return get_obj_from_str(config["target"])
def instantiate_from_config(config, **kwargs):
if "target" not in config:
raise KeyError("Expected key `target` to instantiate.")
cls = get_obj_from_str(config["target"])
params = config.get("params", dict())
# params.update(kwargs)
# instance = cls(**params)
kwargs.update(params)
instance = cls(**kwargs)
return instance
def is_dist_avail_and_initialized():
if not dist.is_available():
return False
if not dist.is_initialized():
return False
return True
def get_rank():
if not is_dist_avail_and_initialized():
return 0
return dist.get_rank()
def get_world_size():
if not is_dist_avail_and_initialized():
return 1
return dist.get_world_size()
def get_free_space(path):
fs_stats = os.statvfs(path)
free_space = fs_stats.f_bsize * fs_stats.f_bfree
return free_space
def get_device_type():
return torch.cuda.get_device_name(0)
def get_hostname():
import socket
return socket.gethostname()
def all_gather_batch(tensors):
"""
Performs all_gather operation on the provided tensors.
"""
# Queue the gathered tensors
world_size = get_world_size()
# There is no need for reduction in the single-proc case
if world_size == 1:
return tensors
tensor_list = []
output_tensor = []
for tensor in tensors:
tensor_all = [torch.ones_like(tensor) for _ in range(world_size)]
dist.all_gather(
tensor_all,
tensor,
async_op=False # performance opt
)
tensor_list.append(tensor_all)
for tensor_all in tensor_list:
output_tensor.append(torch.cat(tensor_all, dim=0))
return output_tensor
def get_scheduler(name):
if hasattr(lr_scheduler, name):
return getattr(lr_scheduler, name)
else:
raise NotImplementedError
def parse_scheduler(config, optimizer):
interval = config.get("interval", "epoch")
assert interval in ["epoch", "step"]
if config.name == "SequentialLR":
scheduler = {
"scheduler": lr_scheduler.SequentialLR(
optimizer,
[
parse_scheduler(conf, optimizer)["scheduler"]
for conf in config.schedulers
],
milestones=config.milestones,
),
"interval": interval,
}
elif config.name == "ChainedScheduler":
scheduler = {
"scheduler": lr_scheduler.ChainedScheduler(
[
parse_scheduler(conf, optimizer)["scheduler"]
for conf in config.schedulers
]
),
"interval": interval,
}
else:
scheduler = {
"scheduler": get_scheduler(config.name)(optimizer, **config.args),
"interval": interval,
}
return scheduler
class TimeRecorder:
_instance = None
def __init__(self):
self.items = {}
self.accumulations = defaultdict(list)
self.time_scale = 1000.0 # ms
self.time_unit = "ms"
self.enabled = False
def __new__(cls):
# singleton
if cls._instance is None:
cls._instance = super(TimeRecorder, cls).__new__(cls)
return cls._instance
def enable(self, enabled: bool) -> None:
self.enabled = enabled
def start(self, name: str) -> None:
if not self.enabled:
return
torch.cuda.synchronize()
self.items[name] = time.time()
def end(self, name: str, accumulate: bool = False) -> float:
if not self.enabled or name not in self.items:
return
torch.cuda.synchronize()
start_time = self.items.pop(name)
delta = time.time() - start_time
if accumulate:
self.accumulations[name].append(delta)
t = delta * self.time_scale
logger.info(f"{name}: {t:.2f}{self.time_unit}")
def get_accumulation(self, name: str, average: bool = False) -> float:
if not self.enabled or name not in self.accumulations:
return
acc = self.accumulations.pop(name)
total = sum(acc)
if average:
t = total / len(acc) * self.time_scale
else:
t = total * self.time_scale
logger.info(f"{name} for {len(acc)} times: {t:.2f}{self.time_unit}")
### global time recorder
time_recorder = TimeRecorder()
class FLASH3:
def __init__(self) -> None:
self.available = "H100" in get_device_type()
self.use = os.environ.get("USE_FLASH3", False)
@property
def is_use(self):
return self.available and self.use
@contextmanager
def disable_flash3(self):
use = self.use
self.set_use(False)
yield
self.set_use(use)
def set_use(self, use=True):
self.use = use
use_flash3 = FLASH3()

View file

@ -0,0 +1,28 @@
from copy import deepcopy
from dataclasses import dataclass
from .michelangelo.get_model import get_encoder as get_encoder_michelangelo
from .michelangelo.get_model import AlignedShapeLatentPerceiver
from .michelangelo.get_model import get_encoder_simplified as get_encoder_michelangelo_encoder
from .michelangelo.get_model import ShapeAsLatentPerceiverEncoder
from .skin_vae.autoencoders.autoencoder_kl_tripo2 import Tripo2Encoder
@dataclass(frozen=True)
class _MAP_MESH_ENCODER:
michelangelo = AlignedShapeLatentPerceiver
michelangelo_encoder = ShapeAsLatentPerceiverEncoder
tripo = Tripo2Encoder
MAP_MESH_ENCODER = _MAP_MESH_ENCODER()
def get_mesh_encoder(**kwargs):
MAP = {
'michelangelo': get_encoder_michelangelo,
'michelangelo_encoder': get_encoder_michelangelo_encoder,
'tripo': Tripo2Encoder,
}
__target__ = kwargs['__target__']
del kwargs['__target__']
assert __target__ in MAP, f"expect: [{','.join(MAP.keys())}], found: {__target__}"
return MAP[__target__](**deepcopy(kwargs))

View file

@ -0,0 +1,283 @@
import inspect
import math
from typing import Callable, List, Optional, Tuple, Union
import torch
import torch.nn.functional as F
from diffusers.models.attention_processor import Attention
from diffusers.utils import logging
from diffusers.utils.import_utils import is_torch_npu_available, is_xformers_available
from diffusers.utils.torch_utils import is_torch_version, maybe_allow_in_graph
from torch import nn
try:
from flash_attn_interface import flash_attn_func
except Exception as e:
def flash_attn_func(q, k, v):
q = q.permute(0, 2, 1, 3) # (B, H, L, D)
k = k.permute(0, 2, 1, 3)
v = v.permute(0, 2, 1, 3)
if q.shape[1] != k.shape[1]:
repeat_factor = q.shape[1] // k.shape[1]
k = k.repeat_interleave(repeat_factor, dim=1)
v = v.repeat_interleave(repeat_factor, dim=1)
out = torch.nn.functional.scaled_dot_product_attention(q, k, v)
return out.permute(0, 2, 1, 3), None # (B, L, H, D)
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
class Tripo2AttnProcessor2_0:
r"""
Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0). This is
used in the Tripo2DiT model. It applies a s normalization layer and rotary embedding on query and key vector.
"""
def __init__(self):
if not hasattr(F, "scaled_dot_product_attention"):
raise ImportError(
"AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0."
)
def __call__(
self,
attn: Attention,
hidden_states: torch.Tensor,
encoder_hidden_states: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
temb: Optional[torch.Tensor] = None,
image_rotary_emb: Optional[torch.Tensor] = None,
) -> torch.Tensor:
from diffusers.models.embeddings import apply_rotary_emb
residual = hidden_states
if attn.spatial_norm is not None:
hidden_states = attn.spatial_norm(hidden_states, temb)
input_ndim = hidden_states.ndim
if input_ndim == 4:
batch_size, channel, height, width = hidden_states.shape
hidden_states = hidden_states.view(
batch_size, channel, height * width
).transpose(1, 2)
batch_size, sequence_length, _ = (
hidden_states.shape
if encoder_hidden_states is None
else encoder_hidden_states.shape
)
if attention_mask is not None:
attention_mask = attn.prepare_attention_mask(
attention_mask, sequence_length, batch_size
)
# scaled_dot_product_attention expects attention_mask shape to be
# (batch, heads, source_length, target_length)
attention_mask = attention_mask.view(
batch_size, attn.heads, -1, attention_mask.shape[-1]
)
if attn.group_norm is not None:
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(
1, 2
)
query = attn.to_q(hidden_states)
if encoder_hidden_states is None:
encoder_hidden_states = hidden_states
elif attn.norm_cross:
encoder_hidden_states = attn.norm_encoder_hidden_states(
encoder_hidden_states
)
key = attn.to_k(encoder_hidden_states)
value = attn.to_v(encoder_hidden_states)
# NOTE that tripo2 split heads first then split qkv or kv, like .view(..., attn.heads, 3, dim)
# instead of .view(..., 3, attn.heads, dim). So we need to re-split here.
if not attn.is_cross_attention:
qkv = torch.cat((query, key, value), dim=-1)
split_size = qkv.shape[-1] // attn.heads // 3
qkv = qkv.view(batch_size, -1, attn.heads, split_size * 3)
query, key, value = torch.split(qkv, split_size, dim=-1)
else:
kv = torch.cat((key, value), dim=-1)
split_size = kv.shape[-1] // attn.heads // 2
kv = kv.view(batch_size, -1, attn.heads, split_size * 2)
key, value = torch.split(kv, split_size, dim=-1)
head_dim = key.shape[-1]
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
if attn.norm_q is not None:
query = attn.norm_q(query)
if attn.norm_k is not None:
key = attn.norm_k(key)
# Apply RoPE if needed
if image_rotary_emb is not None:
query = apply_rotary_emb(query, image_rotary_emb)
if not attn.is_cross_attention:
key = apply_rotary_emb(key, image_rotary_emb)
# the output of sdp = (batch, num_heads, seq_len, head_dim)
# TODO: add support for attn.scale when we move to Torch 2.1
# with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=True, enable_mem_efficient=True):
hidden_states = flash_attn_func(query.transpose(1, 2), key.transpose(1, 2), value.transpose(1, 2))
if type(hidden_states) == tuple:
hidden_states = hidden_states[0]
# hidden_states = F.scaled_dot_product_attention(
# query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
# )
#hidden_states =
hidden_states = hidden_states.reshape(
batch_size, -1, attn.heads * head_dim
)
hidden_states = hidden_states.to(query.dtype)
# linear proj
hidden_states = attn.to_out[0](hidden_states)
# dropout
hidden_states = attn.to_out[1](hidden_states)
if input_ndim == 4:
hidden_states = hidden_states.transpose(-1, -2).reshape(
batch_size, channel, height, width
)
if attn.residual_connection:
hidden_states = hidden_states + residual
hidden_states = hidden_states / attn.rescale_output_factor
return hidden_states
class FusedTripo2AttnProcessor2_0:
r"""
Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0) with fused
projection layers. This is used in the HunyuanDiT model. It applies a s normalization layer and rotary embedding on
query and key vector.
"""
def __init__(self):
if not hasattr(F, "scaled_dot_product_attention"):
raise ImportError(
"FusedTripo2AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0."
)
def __call__(
self,
attn: Attention,
hidden_states: torch.Tensor,
encoder_hidden_states: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
temb: Optional[torch.Tensor] = None,
image_rotary_emb: Optional[torch.Tensor] = None,
) -> torch.Tensor:
from diffusers.models.embeddings import apply_rotary_emb
residual = hidden_states
if attn.spatial_norm is not None:
hidden_states = attn.spatial_norm(hidden_states, temb)
input_ndim = hidden_states.ndim
if input_ndim == 4:
batch_size, channel, height, width = hidden_states.shape
hidden_states = hidden_states.view(
batch_size, channel, height * width
).transpose(1, 2)
batch_size, sequence_length, _ = (
hidden_states.shape
if encoder_hidden_states is None
else encoder_hidden_states.shape
)
if attention_mask is not None:
attention_mask = attn.prepare_attention_mask(
attention_mask, sequence_length, batch_size
)
# scaled_dot_product_attention expects attention_mask shape to be
# (batch, heads, source_length, target_length)
attention_mask = attention_mask.view(
batch_size, attn.heads, -1, attention_mask.shape[-1]
)
if attn.group_norm is not None:
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(
1, 2
)
# NOTE that tripo2 split heads first, then split qkv
if encoder_hidden_states is None:
qkv = attn.to_qkv(hidden_states)
split_size = qkv.shape[-1] // attn.heads // 3
qkv = qkv.view(batch_size, -1, attn.heads, split_size * 3)
query, key, value = torch.split(qkv, split_size, dim=-1)
else:
if attn.norm_cross:
encoder_hidden_states = attn.norm_encoder_hidden_states(
encoder_hidden_states
)
query = attn.to_q(hidden_states)
kv = attn.to_kv(encoder_hidden_states)
split_size = kv.shape[-1] // attn.heads // 2
kv = kv.view(batch_size, -1, attn.heads, split_size * 2)
key, value = torch.split(kv, split_size, dim=-1)
head_dim = key.shape[-1]
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
if attn.norm_q is not None:
query = attn.norm_q(query)
if attn.norm_k is not None:
key = attn.norm_k(key)
# Apply RoPE if needed
if image_rotary_emb is not None:
query = apply_rotary_emb(query, image_rotary_emb)
if not attn.is_cross_attention:
key = apply_rotary_emb(key, image_rotary_emb)
# the output of sdp = (batch, num_heads, seq_len, head_dim)
# TODO: add support for attn.scale when we move to Torch 2.1
hidden_states = F.scaled_dot_product_attention(
query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
)
hidden_states = hidden_states.transpose(1, 2).reshape(
batch_size, -1, attn.heads * head_dim
)
hidden_states = hidden_states.to(query.dtype)
# linear proj
hidden_states = attn.to_out[0](hidden_states)
# dropout
hidden_states = attn.to_out[1](hidden_states)
if input_ndim == 4:
hidden_states = hidden_states.transpose(-1, -2).reshape(
batch_size, channel, height, width
)
if attn.residual_connection:
hidden_states = hidden_states + residual
hidden_states = hidden_states / attn.rescale_output_factor
return hidden_states

View file

@ -0,0 +1,191 @@
from __future__ import annotations
from functools import wraps, partial
from contextlib import nullcontext
from typing import List, Tuple
import torch
import torch.nn as nn
from torch.nn import Module
from torch import Tensor, int32
from torch.amp import autocast
from einops import rearrange, pack, unpack
# helper functions
def exists(v):
return v is not None
def default(*args):
for arg in args:
if exists(arg):
return arg
return None
def maybe(fn):
@wraps(fn)
def inner(x, *args, **kwargs):
if not exists(x):
return x
return fn(x, *args, **kwargs)
return inner
def pack_one(t, pattern):
return pack([t], pattern)
def unpack_one(t, ps, pattern):
return unpack(t, ps, pattern)[0]
# tensor helpers
def round_ste(z: Tensor) -> Tensor:
"""Round with straight through gradients."""
zhat = z.round()
return z + (zhat - z).detach()
# main class
class FSQ(Module):
def __init__(
self,
levels: List[int],
dim: int | None = None,
num_codebooks = 1,
keep_num_codebooks_dim: bool | None = None,
scale: float | None = None,
allowed_dtypes: Tuple[torch.dtype, ...] = (torch.float32, torch.float64),
channel_first: bool = False,
projection_has_bias: bool = True,
return_indices = True,
force_quantization_f32 = True
):
super().__init__()
_levels = torch.tensor(levels, dtype=int32)
self.register_buffer("_levels", _levels, persistent = False)
_basis = torch.cumprod(torch.tensor([1] + levels[:-1]), dim=0, dtype=int32)
self.register_buffer("_basis", _basis, persistent = False)
self.scale = scale
codebook_dim = len(levels)
self.codebook_dim = codebook_dim
effective_codebook_dim = codebook_dim * num_codebooks
self.num_codebooks = num_codebooks
self.effective_codebook_dim = effective_codebook_dim
keep_num_codebooks_dim = default(keep_num_codebooks_dim, num_codebooks > 1)
assert not (num_codebooks > 1 and not keep_num_codebooks_dim)
self.keep_num_codebooks_dim = keep_num_codebooks_dim
self.dim = default(dim, len(_levels) * num_codebooks)
self.channel_first = channel_first
has_projections = self.dim != effective_codebook_dim
self.project_in = nn.Linear(self.dim, effective_codebook_dim, bias = projection_has_bias) if has_projections else nn.Identity()
self.project_out = nn.Linear(effective_codebook_dim, self.dim, bias = projection_has_bias) if has_projections else nn.Identity()
self.has_projections = has_projections
self.return_indices = return_indices
if return_indices:
self.codebook_size: int = self._levels.prod().item()
implicit_codebook = self._indices_to_codes(torch.arange(self.codebook_size))
self.register_buffer("implicit_codebook", implicit_codebook, persistent = False)
self.allowed_dtypes = allowed_dtypes
self.force_quantization_f32 = force_quantization_f32
def bound(self, z, eps: float = 1e-3):
""" Bound `z`, an array of shape (..., d). """
half_l = (self._levels - 1) * (1 + eps) / 2
offset = torch.where(self._levels % 2 == 0, 0.5, 0.0)
shift = (offset / half_l).atanh()
return (z + shift).tanh() * half_l - offset
def quantize(self, z):
""" Quantizes z, returns quantized zhat, same shape as z. """
quantized = round_ste(self.bound(z))
half_width = self._levels // 2 # Renormalize to [-1, 1].
return quantized / half_width
def _scale_and_shift(self, zhat_normalized):
half_width = self._levels // 2
return (zhat_normalized * half_width) + half_width
def _scale_and_shift_inverse(self, zhat):
half_width = self._levels // 2
return (zhat - half_width) / half_width
def _indices_to_codes(self, indices):
level_indices = self.indices_to_level_indices(indices)
codes = self._scale_and_shift_inverse(level_indices)
return codes
def codes_to_indices(self, zhat):
""" Converts a `code` to an index in the codebook. """
assert zhat.shape[-1] == self.codebook_dim
zhat = self._scale_and_shift(zhat)
return (zhat * self._basis).sum(dim=-1).to(int32)
def indices_to_level_indices(self, indices):
""" Converts indices to indices at each level, perhaps needed for a transformer with factorized embeddings """
indices = rearrange(indices, '... -> ... 1')
codes_non_centered = (indices // self._basis) % self._levels
return codes_non_centered
def indices_to_codes(self, indices):
""" Inverse of `codes_to_indices`. """
assert exists(indices)
is_img_or_video = indices.ndim >= (3 + int(self.keep_num_codebooks_dim))
codes = self._indices_to_codes(indices)
if self.keep_num_codebooks_dim:
codes = rearrange(codes, '... c d -> ... (c d)')
codes = self.project_out(codes)
if is_img_or_video or self.channel_first:
codes = rearrange(codes, 'b ... d -> b d ...')
return codes
def dequantize(self, indices):
codes = self._indices_to_codes(indices)
out = self.project_out(codes)
return out
def forward(self, z):
"""
einstein notation
b - batch
n - sequence (or flattened spatial dimensions)
d - feature dimension
c - number of codebook dim
"""
assert z.shape[-1] == self.dim, f'expected dimension of {self.dim} but found dimension of {z.shape[-1]}'
z = self.project_in(z)
z = rearrange(z, 'b n (c d) -> b n c d', c = self.num_codebooks)
# whether to force quantization step to be full precision or not
force_f32 = self.force_quantization_f32
quantization_context = partial(autocast, 'cuda', enabled = False) if force_f32 else nullcontext
with quantization_context():
orig_dtype = z.dtype
if force_f32 and orig_dtype not in self.allowed_dtypes:
z = z.float()
codes = self.quantize(z)
# returning indices could be optional
indices = None
if self.return_indices:
indices = self.codes_to_indices(codes)
codes = rearrange(codes, 'b n c d -> b n (c d)')
codes = codes.type(orig_dtype)
# project out
out = self.project_out(codes)
if not self.keep_num_codebooks_dim and self.return_indices:
indices = maybe(rearrange)(indices, '... 1 -> ...')
# return quantized output and indices
return out, indices, None

View file

@ -0,0 +1,197 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from einops import rearrange
class SimVQ(nn.Module):
"""
Improved version over VectorQuantizer, can be used as a drop-in replacement. Mostly
avoids costly matrix multiplications and allows for post-hoc remapping of indices.
"""
# NOTE: due to a bug the beta term was applied to the wrong term. for
# backwards compatibility we use the buggy version by default, but you can
# specify legacy=False to fix it.
def __init__(self, n_e, e_dim, beta=0.25, remap=None, unknown_index="random",
same_index_shape=False, legacy=True):
super().__init__()
self.n_e = n_e
self.e_dim = e_dim
self.beta = beta
self.legacy = legacy
self.embedding = nn.Embedding(self.n_e, self.e_dim)
self.codebook_size = self.n_e
nn.init.normal_(self.embedding.weight, mean=0, std=self.e_dim**-0.5)
for p in self.embedding.parameters():
p.requires_grad = False
self.embedding_proj = nn.Linear(self.e_dim, self.e_dim)
self.remap = remap
if self.remap is not None:
self.register_buffer("used", torch.tensor(np.load(self.remap)))
self.re_embed = self.used.shape[0]
self.unknown_index = unknown_index # "random" or "extra" or integer
if self.unknown_index == "extra":
self.unknown_index = self.re_embed
self.re_embed = self.re_embed+1
print(f"Remapping {self.n_e} indices to {self.re_embed} indices. "
f"Using {self.unknown_index} for unknown indices.")
else:
self.re_embed = n_e
self.same_index_shape = same_index_shape
def remap_to_used(self, inds):
ishape = inds.shape
assert len(ishape)>1
inds = inds.reshape(ishape[0],-1)
used = self.used.to(inds)
match = (inds[:,:,None]==used[None,None,...]).long()
new = match.argmax(-1)
unknown = match.sum(2)<1
if self.unknown_index == "random":
new[unknown]=torch.randint(0,self.re_embed,size=new[unknown].shape).to(device=new.device)
else:
new[unknown] = self.unknown_index
return new.reshape(ishape)
def unmap_to_all(self, inds):
ishape = inds.shape
assert len(ishape)>1
inds = inds.reshape(ishape[0],-1)
used = self.used.to(inds)
if self.re_embed > self.used.shape[0]: # extra token
inds[inds>=self.used.shape[0]] = 0 # simply set to zero
back=torch.gather(used[None,:][inds.shape[0]*[0],:], 1, inds)
return back.reshape(ishape)
def forward(self, z):
# reshape z -> (batch, height, width, channel) and flatten
z = rearrange(z, 'b c h w -> b h w c').contiguous()
assert z.shape[-1] == self.e_dim
z_flattened = z.view(-1, self.e_dim)
# distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
quant_codebook = self.embedding_proj(self.embedding.weight)
d = torch.sum(z_flattened ** 2, dim=1, keepdim=True) + \
torch.sum(quant_codebook**2, dim=1) - 2 * \
torch.einsum('bd,dn->bn', z_flattened, rearrange(quant_codebook, 'n d -> d n'))
min_encoding_indices = torch.argmin(d, dim=1)
z_q = F.embedding(min_encoding_indices, quant_codebook).view(z.shape)
# compute loss for embedding
if not self.legacy:
quantization_loss = self.beta * torch.mean((z_q.detach()-z)**2) + \
torch.mean((z_q - z.detach()) ** 2)
else:
quantization_loss = torch.mean((z_q.detach()-z)**2) + self.beta * \
torch.mean((z_q - z.detach()) ** 2)
# preserve gradients
z_q = z + (z_q - z).detach()
# reshape back to match original input shape
z_q = rearrange(z_q, 'b h w c -> b c h w').contiguous()
if self.remap is not None:
min_encoding_indices = min_encoding_indices.reshape(z.shape[0],-1) # add batch axis
min_encoding_indices = self.remap_to_used(min_encoding_indices)
min_encoding_indices = min_encoding_indices.reshape(-1,1) # flatten
if self.same_index_shape:
min_encoding_indices = min_encoding_indices.reshape(
z_q.shape[0], z_q.shape[2], z_q.shape[3])
return z_q, min_encoding_indices, quantization_loss
def get_codebook_entry(self, indices, shape):
# shape specifying (batch, height, width, channel)
if self.remap is not None:
indices = indices.reshape(shape[0],-1) # add batch axis
indices = self.unmap_to_all(indices)
indices = indices.reshape(-1) # flatten again
# get quantized latent vectors
z_q = self.embedding(indices)
if shape is not None:
z_q = z_q.view(shape)
# reshape back to match original input shape
z_q = z_q.permute(0, 3, 1, 2).contiguous()
return z_q
def indices_to_codes(self, indices):
return self.get_codebook_entry(indices, None)
def entropy(prob):
return (-prob * log(prob)).sum(dim=-1)
class SimVQ1D(SimVQ):
def __init__(self, n_e, e_dim, dim, beta=0.25, remap=None, unknown_index="random", same_index_shape=True, legacy=True):
super().__init__(n_e, e_dim, beta, remap, unknown_index, same_index_shape, legacy)
self.project_in = nn.Linear(dim, e_dim)
self.project_out = nn.Linear(e_dim, dim)
def forward(self, z):
# reshape z -> (batch, height, width, channel) and flatten
#assert z.shape[-1] == self.e_dim
z = self.project_in(z)
z_flattened = z.view(-1, self.e_dim)
# distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
quant_codebook = self.embedding_proj(self.embedding.weight)
# # Use IBQ
# logits = torch.matmul(z_flattened, quant_codebook.t())
# Ind_soft = torch.softmax(logits, dim=1)
# indices = torch.argmax(Ind_soft, dim=1)
# Ind_hard = F.one_hot(indices, num_classes=Ind_soft.shape[1])
# Ind = Ind_hard - Ind_soft.detach() + Ind_soft
# z_q = torch.matmul(Ind, quant_codebook).view(z.shape)
# if not self.legacy:
# quantization_loss = self.beta * torch.mean((z_q.detach()-z)**2) + \
# torch.mean((z_q - z.detach()) ** 2)
# else:
# quantization_loss = torch.mean((z_q.detach()-z)**2) + self.beta * \
# torch.mean((z_q - z.detach()) ** 2)
# return z_q, indices, quantization_loss
d = torch.sum(z_flattened ** 2, dim=1, keepdim=True) + \
torch.sum(quant_codebook**2, dim=1) - 2 * \
torch.einsum('bd,dn->bn', z_flattened, rearrange(quant_codebook, 'n d -> d n'))
min_encoding_indices = torch.argmin(d, dim=1)
z_q = F.embedding(min_encoding_indices, quant_codebook).view(z.shape)
# compute loss for embedding
if not self.legacy:
quantization_loss = self.beta * torch.mean((z_q.detach()-z)**2) + \
torch.mean((z_q - z.detach()) ** 2)
else:
quantization_loss = torch.mean((z_q.detach()-z)**2) + self.beta * \
torch.mean((z_q - z.detach()) ** 2)
# preserve gradients
z_q = z + (z_q - z).detach()
if self.remap is not None:
min_encoding_indices = min_encoding_indices.reshape(z.shape[0],-1) # add batch axis
min_encoding_indices = self.remap_to_used(min_encoding_indices)
min_encoding_indices = min_encoding_indices.reshape(-1,1) # flatten
if self.same_index_shape:
min_encoding_indices = min_encoding_indices.view(z.shape[0], z.shape[1])
z_q = self.project_out(z_q.view(z.shape))
return z_q, min_encoding_indices, quantization_loss

View file

@ -0,0 +1 @@
from .skin_fsq_cvae_model import SkinFSQCVAEModel

View file

@ -0,0 +1,254 @@
from typing import Dict, List, Optional, Tuple, Union
import numpy as np
import torch
import torch.nn as nn
from diffusers.models.normalization import LayerNorm
from diffusers.utils import logging
from einops import repeat
import math
from ..embeddings import FrequencyPositionalEmbedding
from ..transformers.tripo2_transformer import DiTBlock
from ...utils import fps
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
def init_linear(l, stddev):
nn.init.normal_(l.weight, std=stddev)
if l.bias is not None:
nn.init.constant_(l.bias, 0.0)
class Tripo2Encoder(nn.Module):
def __init__(
self,
in_channels: int = 3,
dim: int = 512,
num_attention_heads: int = 8,
num_layers: int = 8,
is_learned_queries: bool = False,
sample_tokens: int = 32,
embed_frequency: int = 8,
embed_include_pi: bool = False,
fps: bool = False,
is_miche: bool = False,
):
super().__init__()
self.fps = fps
if fps and not is_learned_queries:
self.embedder = FrequencyPositionalEmbedding(
num_freqs=embed_frequency,
logspace=True,
input_dim=3,
include_pi=embed_include_pi,
)
self.proj_k = nn.Linear(3+self.embedder.out_dim, dim, bias=True)
self.proj_in = nn.Linear(in_channels-3+self.embedder.out_dim, dim, bias=True)
else:
self.proj_in = nn.Linear(in_channels, dim, bias=True)
self.output_channels = dim
self.is_miche = is_miche
init_scale = 0.25 * math.sqrt(1.0 / dim)
init_linear(self.proj_in, init_scale)
self.blocks = nn.ModuleList(
[
DiTBlock(
dim=dim,
num_attention_heads=num_attention_heads,
use_self_attention=False,
use_cross_attention=True,
cross_attention_dim=dim,
cross_attention_norm_type="layer_norm",
activation_fn="gelu",
norm_type="fp32_layer_norm",
norm_eps=1e-5,
qk_norm=False,
qkv_bias=False,
) # cross attention
]
+ [
DiTBlock(
dim=dim,
num_attention_heads=num_attention_heads,
use_self_attention=True,
self_attention_norm_type="fp32_layer_norm",
use_cross_attention=False,
use_cross_attention_2=False,
activation_fn="gelu",
norm_type="fp32_layer_norm",
norm_eps=1e-5,
qk_norm=False,
qkv_bias=False,
)
for _ in range(num_layers) # self attention
]
)
self.norm_out = LayerNorm(dim)
self.is_learned_queries = is_learned_queries
if is_learned_queries:
self.learned_queries = nn.Parameter(torch.randn(sample_tokens, dim) * 0.02)
def forward(self, sample_1: torch.Tensor, sample_2: torch.Tensor, num_tokens: int=1024):
if self.is_learned_queries or not self.fps:
hidden_states = self.proj_in(sample_1) if not self.is_learned_queries else repeat(self.learned_queries[:sample_1.shape[1], :], 'n d -> b n d', b=sample_1.shape[0])
encoder_hidden_states = self.proj_in(sample_2)
else:
x_q, x_kv = self.get_qkv(x=sample_1, num_tokens=num_tokens)
hidden_states = self.proj_k(x_q)
encoder_hidden_states = self.proj_in(x_kv)
if not self.is_miche:
for layer, block in enumerate(self.blocks):
if layer == 0:
hidden_states = block(
hidden_states, encoder_hidden_states=encoder_hidden_states
)
else:
hidden_states = block(hidden_states)
else:
for layer, block in enumerate(self.blocks):
if layer == 0:
hidden_states = block(hidden_states, encoder_hidden_states)
else:
hidden_states = block(hidden_states)
hidden_states = self.norm_out(hidden_states)
return hidden_states
def _sample_features(
self, x: torch.Tensor, num_tokens: int = 1024, seed: Optional[int] = None
):
"""
Sample points from features of the input point cloud.
Args:
x (torch.Tensor): The input point cloud. shape: (B, N, C)
num_tokens (int, optional): The number of points to sample. Defaults to 1024.
seed (Optional[int], optional): The random seed. Defaults to None.
"""
rng = np.random.default_rng(seed)
indices = rng.choice(
x.shape[1], num_tokens * 4, replace=num_tokens * 4 > x.shape[1]
)
selected_points = x[:, indices]
batch_size, num_points, num_channels = selected_points.shape
flattened_points = selected_points.view(batch_size * num_points, num_channels)
batch_indices = (
torch.arange(batch_size).to(x.device).repeat_interleave(num_points)
)
# fps sampling
sampling_ratio = 1.0 / 4
sampled_indices = fps(
flattened_points[:, :3],
batch_indices,
ratio=sampling_ratio,
random_start=self.training,
)
sampled_points = flattened_points[sampled_indices].view(
batch_size, -1, num_channels
)
return sampled_points
def get_qkv(self, x: torch.Tensor, num_tokens: int = 1024, seed: Optional[int] = None):
positions, features = x[..., :3], x[..., 3:]
x_kv = torch.cat([self.embedder(positions), features], dim=-1)
sampled_x = self._sample_features(x, num_tokens, seed)
positions, features = (
sampled_x[..., :3],
sampled_x[..., 3:],
)
x_q = torch.cat([self.embedder(positions), features], dim=-1)
return x_q, x_kv
class Tripo2Decoder(nn.Module):
def __init__(
self,
in_channels: int = 3,
out_channels: int = 1,
dim: int = 512,
num_attention_heads: int = 8,
num_layers: int = 16,
grad_type: str = "analytical",
grad_interval: float = 0.001,
is_miche: bool = False,
):
super().__init__()
if grad_type not in ["numerical", "analytical"]:
raise ValueError(f"grad_type must be one of ['numerical', 'analytical']")
self.grad_type = grad_type
self.grad_interval = grad_interval
self.is_miche = is_miche
self.blocks = nn.ModuleList(
[
DiTBlock(
dim=dim,
num_attention_heads=num_attention_heads,
use_self_attention=True,
self_attention_norm_type="fp32_layer_norm",
use_cross_attention=False,
use_cross_attention_2=False,
activation_fn="gelu",
norm_type="fp32_layer_norm",
norm_eps=1e-5,
qk_norm=False,
qkv_bias=False,
)
for _ in range(num_layers) # self attention
]
+ [
DiTBlock(
dim=dim,
num_attention_heads=num_attention_heads,
use_self_attention=False,
use_cross_attention=True,
cross_attention_dim=dim,
cross_attention_norm_type="layer_norm",
activation_fn="gelu",
norm_type="fp32_layer_norm",
norm_eps=1e-5,
qk_norm=False,
qkv_bias=False,
) # cross attention
]
)
self.proj_query = nn.Linear(in_channels, dim, bias=True)
self.norm_out = LayerNorm(dim)
self.proj_out = nn.Linear(dim, out_channels, bias=True)
self.sigmoid = nn.Sigmoid()
init_scale = 0.25 * math.sqrt(1.0 / dim)
init_linear(self.proj_query, init_scale)
init_linear(self.proj_out, init_scale)
def forward(
self,
sample: torch.Tensor,
queries: torch.Tensor,
kv_cache: Optional[torch.Tensor] = None,
) -> Tuple[torch.Tensor, torch.Tensor]:
if kv_cache is None:
hidden_states = sample
for _, block in enumerate(self.blocks[:-1]):
hidden_states = block(hidden_states)
kv_cache = hidden_states
# query grid logits by cross attention
q = self.proj_query(queries)
if self.is_miche:
l = self.blocks[-1](q, kv_cache)
else:
l = self.blocks[-1](q, encoder_hidden_states=kv_cache)
logits = self.proj_out(self.norm_out(l))
logits = self.sigmoid(logits)
assert kv_cache is not None
return logits, kv_cache

View file

@ -0,0 +1,22 @@
from .skin_cvae_model import SkinCVAEModel
from .skin_fsq_cvae_model import SkinFSQCVAEModel
def get_model_cvae(
pretrained_path: str=None,
**kwargs
) -> SkinCVAEModel:
model = SkinCVAEModel(**kwargs)
if pretrained_path is not None:
state_dict = torch.load(pretrained_path, weights_only=True)
model.load_state_dict(state_dict)
return model
def get_model_fsq_cvae(
pretrained_path: str=None,
**kwargs
) -> SkinFSQCVAEModel:
model = SkinFSQCVAEModel(**kwargs)
if pretrained_path is not None:
state_dict = torch.load(pretrained_path, weights_only=True)
model.load_state_dict(state_dict)
return model

View file

@ -0,0 +1,395 @@
# -*- coding: utf-8 -*-
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Optional
import os
# -*- coding: utf-8 -*-
"""
Adapted from: https://github.com/openai/guided-diffusion/blob/22e0df8183507e13a7813f8d38d51b072ca1e67c/guided_diffusion/nn.py#L124
"""
import torch
from typing import Callable, Iterable, Sequence, Union
def checkpoint(
func: Callable[..., Union[torch.Tensor, Sequence[torch.Tensor]]],
inputs: Sequence[torch.Tensor],
params: Iterable[torch.Tensor],
flag: bool,
use_deepspeed: bool = False
):
"""
Evaluate a function without caching intermediate activations, allowing for
reduced memory at the expense of extra compute in the backward pass.
:param func: the function to evaluate.
:param inputs: the argument sequence to pass to `func`.
:param params: a sequence of parameters `func` depends on but does not
explicitly take as arguments.
:param flag: if False, disable gradient checkpointing.
:param use_deepspeed: if True, use deepspeed
"""
if flag:
if use_deepspeed:
import deepspeed
return deepspeed.checkpointing.checkpoint(func, *inputs)
args = tuple(inputs) + tuple(params)
return CheckpointFunction.apply(func, len(inputs), *args)
else:
return func(*inputs)
class CheckpointFunction(torch.autograd.Function):
@staticmethod
@torch.amp.custom_fwd(device_type='cuda')
def forward(ctx, run_function, length, *args):
ctx.run_function = run_function
ctx.input_tensors = list(args[:length])
ctx.input_params = list(args[length:])
with torch.no_grad():
output_tensors = ctx.run_function(*ctx.input_tensors)
return output_tensors
@staticmethod
@torch.amp.custom_bwd(device_type='cuda')
def backward(ctx, *output_grads):
ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors]
with torch.enable_grad():
# Fixes a bug where the first op in run_function modifies the
# Tensor storage in place, which is not allowed for detach()'d
# Tensors.
shallow_copies = [x.view_as(x) for x in ctx.input_tensors]
output_tensors = ctx.run_function(*shallow_copies)
input_grads = torch.autograd.grad(
output_tensors,
ctx.input_tensors + ctx.input_params,
output_grads,
allow_unused=True,
)
del ctx.input_tensors
del ctx.input_params
del output_tensors
return (None, None) + input_grads
try:
from flash_attn_interface import flash_attn_func
print("use flash attention 3.")
_use_flash3 = True
except:
print("use flash attention 2.")
_use_flash3 = False
def init_linear(l, stddev):
nn.init.normal_(l.weight, std=stddev)
if l.bias is not None:
nn.init.constant_(l.bias, 0.0)
def flash_attention(q, k, v):
with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=True, enable_mem_efficient=False):
if _use_flash3:
out, _ = flash_attn_func(q.contiguous(), k.contiguous(), v.contiguous())
# out = flash_attn_func(q, k, v)
# q_ = q.transpose(1, 2)
# k_ = k.transpose(1, 2)
# v_ = v.transpose(1, 2)
# # print(q.shape, k.shape, v.shape)
# out_ = F.scaled_dot_product_attention(q_, k_, v_)
# out_ = out_.transpose(1, 2)
# # print(torch.abs(out - out_).mean())
# assert torch.abs(out - out_).mean() < 1e-2, f"the error {torch.abs(out - out_).mean()} is too large"
# out = out_
# print("use flash_atten 3")
else:
q = q.transpose(1, 2)
k = k.transpose(1, 2)
v = v.transpose(1, 2)
out = F.scaled_dot_product_attention(q, k, v)
out = out.transpose(1, 2)
# print("use flash atten 2")
return out
class MultiheadAttention(nn.Module):
def __init__(
self,
*,
device: torch.device,
dtype: torch.dtype,
n_ctx: int,
width: int,
heads: int,
init_scale: float,
qkv_bias: bool,
flash: bool = False
):
super().__init__()
self.n_ctx = n_ctx
self.width = width
self.heads = heads
self.c_qkv = nn.Linear(width, width * 3, bias=qkv_bias, device=device, dtype=dtype)
self.c_proj = nn.Linear(width, width, device=device, dtype=dtype)
self.attention = QKVMultiheadAttention(device=device, dtype=dtype, heads=heads, n_ctx=n_ctx, flash=flash)
init_linear(self.c_qkv, init_scale)
init_linear(self.c_proj, init_scale)
def forward(self, x):
x = self.c_qkv(x)
x = checkpoint(self.attention, (x,), (), False)
x = self.c_proj(x)
return x
class QKVMultiheadAttention(nn.Module):
def __init__(self, *, device: torch.device, dtype: torch.dtype, heads: int, n_ctx: int, flash: bool = False):
super().__init__()
self.device = device
self.dtype = dtype
self.heads = heads
self.n_ctx = n_ctx
self.flash = flash
def forward(self, qkv):
bs, n_ctx, width = qkv.shape
attn_ch = width // self.heads // 3
scale = 1 / math.sqrt(math.sqrt(attn_ch))
qkv = qkv.view(bs, n_ctx, self.heads, -1)
q, k, v = torch.split(qkv, attn_ch, dim=-1)
if self.flash:
out = flash_attention(q, k, v)
out = out.reshape(out.shape[0], out.shape[1], -1)
else:
weight = torch.einsum(
"bthc,bshc->bhts", q * scale, k * scale
) # More stable with f16 than dividing afterwards
wdtype = weight.dtype
weight = torch.softmax(weight.float(), dim=-1).type(wdtype)
out = torch.einsum("bhts,bshc->bthc", weight, v).reshape(bs, n_ctx, -1)
return out
class ResidualAttentionBlock(nn.Module):
def __init__(
self,
*,
device: torch.device,
dtype: torch.dtype,
n_ctx: int,
width: int,
heads: int,
init_scale: float = 1.0,
qkv_bias: bool = True,
flash: bool = False,
use_checkpoint: bool = False
):
super().__init__()
self.use_checkpoint = use_checkpoint
self.attn = MultiheadAttention(
device=device,
dtype=dtype,
n_ctx=n_ctx,
width=width,
heads=heads,
init_scale=init_scale,
qkv_bias=qkv_bias,
flash=flash
)
self.ln_1 = nn.LayerNorm(width, device=device, dtype=dtype)
self.mlp = MLP(device=device, dtype=dtype, width=width, init_scale=init_scale)
self.ln_2 = nn.LayerNorm(width, device=device, dtype=dtype)
def _forward(self, x: torch.Tensor):
x = x + self.attn(self.ln_1(x))
x = x + self.mlp(self.ln_2(x))
return x
def forward(self, x: torch.Tensor):
return checkpoint(self._forward, (x,), self.parameters(), self.use_checkpoint)
class MultiheadCrossAttention(nn.Module):
def __init__(
self,
*,
device: torch.device,
dtype: torch.dtype,
width: int,
heads: int,
init_scale: float,
qkv_bias: bool = True,
flash: bool = False,
n_data: Optional[int] = None,
data_width: Optional[int] = None,
):
super().__init__()
self.n_data = n_data
self.width = width
self.heads = heads
self.data_width = width if data_width is None else data_width
self.c_q = nn.Linear(width, width, bias=qkv_bias, device=device, dtype=dtype)
self.c_kv = nn.Linear(self.data_width, width * 2, bias=qkv_bias, device=device, dtype=dtype)
self.c_proj = nn.Linear(width, width, device=device, dtype=dtype)
self.attention = QKVMultiheadCrossAttention(
device=device, dtype=dtype, heads=heads, n_data=n_data, flash=flash
)
init_linear(self.c_q, init_scale)
init_linear(self.c_kv, init_scale)
init_linear(self.c_proj, init_scale)
def forward(self, x, data):
x = self.c_q(x)
data = self.c_kv(data)
x = checkpoint(self.attention, (x, data), (), False)
x = self.c_proj(x)
return x
class QKVMultiheadCrossAttention(nn.Module):
def __init__(self, *, device: torch.device, dtype: torch.dtype, heads: int,
flash: bool = False, n_data: Optional[int] = None):
super().__init__()
self.device = device
self.dtype = dtype
self.heads = heads
self.n_data = n_data
self.flash = flash
def forward(self, q, kv):
_, n_ctx, _ = q.shape
bs, n_data, width = kv.shape
attn_ch = width // self.heads // 2
scale = 1 / math.sqrt(math.sqrt(attn_ch))
q = q.view(bs, n_ctx, self.heads, -1)
kv = kv.view(bs, n_data, self.heads, -1)
k, v = torch.split(kv, attn_ch, dim=-1)
if self.flash:
out = flash_attention(q, k, v)
out = out.reshape(out.shape[0], out.shape[1], -1)
else:
weight = torch.einsum(
"bthc,bshc->bhts", q * scale, k * scale
) # More stable with f16 than dividing afterwards
wdtype = weight.dtype
weight = torch.softmax(weight.float(), dim=-1).type(wdtype)
out = torch.einsum("bhts,bshc->bthc", weight, v).reshape(bs, n_ctx, -1)
return out
class ResidualCrossAttentionBlock(nn.Module):
def __init__(
self,
*,
device: Optional[torch.device],
dtype: Optional[torch.dtype],
n_data: Optional[int] = None,
width: int,
heads: int,
data_width: Optional[int] = None,
mlp_width_scale: int = 4,
init_scale: float = 0.25,
qkv_bias: bool = True,
flash: bool = False
):
super().__init__()
if data_width is None:
data_width = width
self.attn = MultiheadCrossAttention(
device=device,
dtype=dtype,
n_data=n_data,
width=width,
heads=heads,
data_width=data_width,
init_scale=init_scale,
qkv_bias=qkv_bias,
flash=flash,
)
self.ln_1 = nn.LayerNorm(width, device=device, dtype=dtype)
self.ln_2 = nn.LayerNorm(data_width, device=device, dtype=dtype)
self.mlp = MLP(device=device, dtype=dtype, width=width, hidden_width_scale=mlp_width_scale, init_scale=init_scale)
self.ln_3 = nn.LayerNorm(width, device=device, dtype=dtype)
def forward(self, x: torch.Tensor, data: torch.Tensor):
x = x + self.attn(self.ln_1(x), self.ln_2(data))
x = x + self.mlp(self.ln_3(x))
return x
class MLP(nn.Module):
def __init__(self, *,
device: Optional[torch.device],
dtype: Optional[torch.dtype],
width: int,
hidden_width_scale: int = 4,
init_scale: float):
super().__init__()
self.width = width
self.c_fc = nn.Linear(width, width * hidden_width_scale, device=device, dtype=dtype)
self.c_proj = nn.Linear(width * hidden_width_scale, width, device=device, dtype=dtype)
self.gelu = nn.GELU()
init_linear(self.c_fc, init_scale)
init_linear(self.c_proj, init_scale)
def forward(self, x):
return self.c_proj(self.gelu(self.c_fc(x)))
class Transformer(nn.Module):
def __init__(
self,
*,
device: Optional[torch.device],
dtype: Optional[torch.dtype],
n_ctx: int,
width: int,
layers: int,
heads: int,
init_scale: float = 0.25,
qkv_bias: bool = True,
flash: bool = False,
use_checkpoint: bool = False
):
super().__init__()
self.n_ctx = n_ctx
self.width = width
self.layers = layers
self.resblocks = nn.ModuleList(
[
ResidualAttentionBlock(
device=device,
dtype=dtype,
n_ctx=n_ctx,
width=width,
heads=heads,
init_scale=init_scale,
qkv_bias=qkv_bias,
flash=flash,
use_checkpoint=use_checkpoint
)
for _ in range(layers)
]
)
def forward(self, x: torch.Tensor):
for block in self.resblocks:
x = block(x)
return x

View file

@ -0,0 +1,304 @@
from typing import Dict, List, Optional, Tuple, Union
import numpy as np
import torch
import torch.nn as nn
from diffusers.configuration_utils import ConfigMixin, register_to_config
from diffusers.models.attention_processor import Attention, AttentionProcessor
from diffusers.models.modeling_utils import ModelMixin
from einops import repeat
import math
from ..attention_processor import Tripo2AttnProcessor2_0
from ..embeddings import FrequencyPositionalEmbedding
from .autoencoder_kl_tripo2 import Tripo2Encoder, Tripo2Decoder
from .FSQ import FSQ
from .SimVQ import SimVQ1D
from ...utils import fps
def init_linear(l, stddev):
nn.init.normal_(l.weight, std=stddev)
if l.bias is not None:
nn.init.constant_(l.bias, 0.0)
class SkinFSQCVAEModel(ModelMixin, ConfigMixin):
@register_to_config
def __init__(
self,
in_channels: int = 4,
cond_channels: int = 3,
latent_channels: int = 64,
num_attention_heads: int = 8,
width_encoder: int = 512,
width_decoder: int = 1024,
num_layers_encoder: int = 8,
num_layers_decoder: int = 16,
embedding_type: str = "frequency",
embed_frequency: int = 8,
embed_include_pi: bool = False,
sample_tokens: int = 32,
**kwargs
):
super().__init__()
self.out_channels = 1
if embedding_type == "frequency":
self.embedder = FrequencyPositionalEmbedding(
num_freqs=embed_frequency,
logspace=True,
input_dim=3,
include_pi=embed_include_pi,
use_pmpe=kwargs.get('use_pmpe', False),
)
else:
raise NotImplementedError(
f"Embedding type {embedding_type} is not supported."
)
self.is_learned_queries = kwargs['is_learned_queries']
is_miche = kwargs.get('is_miche', False)
self.encoder = Tripo2Encoder(
in_channels=in_channels + self.embedder.out_dim,
dim=width_encoder,
num_attention_heads=num_attention_heads,
num_layers=num_layers_encoder,
is_learned_queries=self.is_learned_queries,
sample_tokens=sample_tokens,
is_miche=is_miche,
)
self.cond_encoder = Tripo2Encoder(
in_channels=cond_channels + self.embedder.out_dim,
dim=width_encoder,
num_attention_heads=num_attention_heads,
num_layers=num_layers_encoder,
is_miche=is_miche,
)
self.decoder = Tripo2Decoder(
in_channels=self.embedder.out_dim + self.cond_channels,
out_channels=self.out_channels,
dim=width_decoder,
num_attention_heads=num_attention_heads,
num_layers=num_layers_decoder,
is_miche=is_miche,
)
self.cond_quant = nn.Linear(width_encoder, latent_channels, bias=True)
self.quant = nn.Linear(width_encoder, latent_channels, bias=True)
self.post_quant = nn.Linear(latent_channels, width_decoder, bias=True)
init_scale = 0.25 * math.sqrt(1.0 / width_encoder)
init_linear(self.cond_quant, init_scale)
init_linear(self.quant, init_scale)
init_scale = 0.25 * math.sqrt(1.0 / latent_channels)
init_linear(self.post_quant, init_scale)
self.use_slicing = False
self.slicing_length = 1
if kwargs.get('FSQ_dict', None) is not None:
self.FSQ = FSQ(**kwargs['FSQ_dict'])
else:
self.FSQ = SimVQ1D(**kwargs['SimVQ_dict'])
@property
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
def attn_processors(self) -> Dict[str, AttentionProcessor]:
r"""
Returns:
`dict` of attention processors: A dictionary containing all attention processors used in the model with
indexed by its weight name.
"""
# set recursively
processors = {}
def fn_recursive_add_processors(
name: str,
module: torch.nn.Module,
processors: Dict[str, AttentionProcessor],
):
if hasattr(module, "get_processor"):
processors[f"{name}.processor"] = module.get_processor()
for sub_name, child in module.named_children():
fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
return processors
for name, module in self.named_children():
fn_recursive_add_processors(name, module, processors)
return processors
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
def set_attn_processor(
self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]
):
r"""
Sets the attention processor to use to compute attention.
Parameters:
processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
The instantiated processor class or a dictionary of processor classes that will be set as the processor
for **all** `Attention` layers.
If `processor` is a dict, the key needs to define the path to the corresponding cross attention
processor. This is strongly recommended when setting trainable attention processors.
"""
count = len(self.attn_processors.keys())
if isinstance(processor, dict) and len(processor) != count:
raise ValueError(
f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
)
def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
if hasattr(module, "set_processor"):
if not isinstance(processor, dict):
module.set_processor(processor)
else:
module.set_processor(processor.pop(f"{name}.processor"))
for sub_name, child in module.named_children():
fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
for name, module in self.named_children():
fn_recursive_attn_processor(name, module, processor)
def set_default_attn_processor(self):
"""
Disables custom attention processors and sets the default attention implementation.
"""
self.set_attn_processor(Tripo2AttnProcessor2_0())
def enable_slicing(self, slicing_length: int = 1) -> None:
r"""
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
"""
self.use_slicing = True
self.slicing_length = slicing_length
def disable_slicing(self) -> None:
r"""
Disable sliced VAE decoding. If `enable_slicing` was previously enabled, this method will go back to computing
decoding in one step.
"""
self.use_slicing = False
def _sample_features(
self, x: torch.Tensor, num_tokens: int = 128, seed: Optional[int] = None
):
"""
Sample points from features of the input point cloud.
Args:
x (torch.Tensor): The input point cloud. shape: (B, N, C)
num_tokens (int, optional): The number of points to sample. Defaults to 2048.
seed (Optional[int], optional): The random seed. Defaults to None.
"""
rng = np.random.default_rng(seed)
indices = rng.choice(
x.shape[1], num_tokens * 4, replace=num_tokens * 4 > x.shape[1]
)
selected_points = x[:, indices]
batch_size, num_points, num_channels = selected_points.shape
flattened_points = selected_points.view(batch_size * num_points, num_channels)
batch_indices = (
torch.arange(batch_size).to(x.device).repeat_interleave(num_points)
)
# fps sampling
sampling_ratio = 1.0 / 4
sampled_indices = fps(
flattened_points[:, :3],
batch_indices,
ratio=sampling_ratio,
random_start=self.training,
)
sampled_points = flattened_points[sampled_indices].view(
batch_size, -1, num_channels
)
return sampled_points
def get_qkv(self, x: torch.Tensor, num_tokens: int = 128, seed: Optional[int] = None, not_get_q: bool=False):
positions, features = x[..., :3], x[..., 3:]
x_kv = torch.cat([self.embedder(positions), features], dim=-1)
if not_get_q:
x_q = torch.zeros((x.shape[0], num_tokens, x.shape[-1]), dtype=x.dtype, device=x.device)
else:
sampled_x = self._sample_features(x, num_tokens, seed)
positions, features = (
sampled_x[..., :3],
sampled_x[..., 3:],
)
x_q = torch.cat([self.embedder(positions), features], dim=-1)
return x_q, x_kv
def _encode(
self, x: torch.Tensor|None, cond: torch.Tensor|None, num_tokens: int = 128, cond_tokens: int = 128, seed: Optional[int] = None,
return_z: bool=True, return_cond: bool=True,
):
position_channels = 3
if return_z:
assert x is not None
x_q, x_kv = self.get_qkv(x, num_tokens, seed, not_get_q=self.is_learned_queries)
x = self.encoder(x_q, x_kv)
x = self.quant(x)
else:
x = None
if return_cond:
assert cond is not None
cond_q, cond_kv = self.get_qkv(cond, cond_tokens, seed)
cond_embed = self.cond_encoder(cond_q, cond_kv)
cond = self.cond_quant(cond_embed)
else:
cond = None
return x, cond
def _decode(
self, z: torch.Tensor,
cond: torch.Tensor,
sampled_points: torch.Tensor,
num_chunks: Optional[int] = None,
) -> torch.Tensor:
xyz_samples = sampled_points
z = self.post_quant(torch.cat([z, cond], dim=1))
num_points = xyz_samples.shape[1]
if num_chunks is None:
num_chunks = num_points
queries = sampled_points.to(z.device, dtype=z.dtype)
positions, features = (
queries[..., :3],
queries[..., 3:],
)
kv_cache = None
dec = []
for i in range(0, num_points, num_chunks):
queries = torch.cat([self.embedder(positions[:, i:i + num_chunks, :]), features[:, i:i + num_chunks, :]], dim=-1)
z, kv_cache = self.decoder(z, queries, kv_cache)
dec.append(z)
return torch.cat(dec, dim=1)
def compile_model(self):
self.encoder = torch.compile(self.encoder)
self.cond_encoder = torch.compile(self.cond_encoder)
self.decoder = torch.compile(self.decoder)
def forward(self, x: torch.Tensor):
pass

View file

@ -0,0 +1,73 @@
from typing import Optional, Tuple
import numpy as np
import torch
from diffusers.utils.torch_utils import randn_tensor
class DiagonalGaussianDistribution(object):
def __init__(
self,
parameters: torch.Tensor,
deterministic: bool = False,
feature_dim: int = 1,
):
self.parameters = parameters
self.feature_dim = feature_dim
self.mean, self.logvar = torch.chunk(parameters, 2, dim=feature_dim)
self.logvar = torch.clamp(self.logvar, -30.0, 20.0)
self.deterministic = deterministic
self.std = torch.exp(0.5 * self.logvar)
self.var = torch.exp(self.logvar)
if self.deterministic:
self.var = self.std = torch.zeros_like(
self.mean, device=self.parameters.device, dtype=self.parameters.dtype
)
def sample(self, generator: Optional[torch.Generator] = None) -> torch.Tensor:
# make sure sample is on the same device as the parameters and has same dtype
sample = randn_tensor(
self.mean.shape,
generator=generator,
device=self.parameters.device,
dtype=self.parameters.dtype,
)
x = self.mean + self.std * sample
return x
def kl(self, other: "DiagonalGaussianDistribution" = None) -> torch.Tensor:
if self.deterministic:
return torch.Tensor([0.0])
else:
if other is None:
return 0.5 * torch.mean(
torch.pow(self.mean, 2) + self.var - 1.0 - self.logvar,
)
elif isinstance(other, DiagonalGaussianDistribution):
return 0.5 * torch.mean(
torch.pow(self.mean - other.mean, 2) / other.var
+ self.var / other.var
- 1.0
- self.logvar
+ other.logvar,
)
elif isinstance(other, torch.Tensor):
return 0.5 * torch.mean(
torch.pow(self.mean - other, 2) + self.var - 1.0 - self.logvar,
)
else:
raise ValueError("Other must be a DiagonalGaussianDistribution or torch.Tensor")
def nll(
self, sample: torch.Tensor, dims: Tuple[int, ...] = [1, 2, 3]
) -> torch.Tensor:
if self.deterministic:
return torch.Tensor([0.0])
logtwopi = np.log(2.0 * np.pi)
return 0.5 * torch.sum(
logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var,
dim=dims,
)
def mode(self) -> torch.Tensor:
return self.mean

View file

@ -0,0 +1,111 @@
import torch
import torch.nn as nn
class FrequencyPositionalEmbedding(nn.Module):
"""The sin/cosine positional embedding. Given an input tensor `x` of shape [n_batch, ..., c_dim], it converts
each feature dimension of `x[..., i]` into:
[
sin(x[..., i]),
sin(f_1*x[..., i]),
sin(f_2*x[..., i]),
...
sin(f_N * x[..., i]),
cos(x[..., i]),
cos(f_1*x[..., i]),
cos(f_2*x[..., i]),
...
cos(f_N * x[..., i]),
x[..., i] # only present if include_input is True.
], here f_i is the frequency.
Denote the space is [0 / num_freqs, 1 / num_freqs, 2 / num_freqs, 3 / num_freqs, ..., (num_freqs - 1) / num_freqs].
If logspace is True, then the frequency f_i is [2^(0 / num_freqs), ..., 2^(i / num_freqs), ...];
Otherwise, the frequencies are linearly spaced between [1.0, 2^(num_freqs - 1)].
Args:
num_freqs (int): the number of frequencies, default is 6;
logspace (bool): If logspace is True, then the frequency f_i is [..., 2^(i / num_freqs), ...],
otherwise, the frequencies are linearly spaced between [1.0, 2^(num_freqs - 1)];
input_dim (int): the input dimension, default is 3;
include_input (bool): include the input tensor or not, default is True.
Attributes:
frequencies (torch.Tensor): If logspace is True, then the frequency f_i is [..., 2^(i / num_freqs), ...],
otherwise, the frequencies are linearly spaced between [1.0, 2^(num_freqs - 1);
out_dim (int): the embedding size, if include_input is True, it is input_dim * (num_freqs * 2 + 1),
otherwise, it is input_dim * num_freqs * 2.
"""
def __init__(
self,
num_freqs: int = 6,
logspace: bool = True,
input_dim: int = 3,
include_input: bool = True,
include_pi: bool = True,
use_pmpe: bool = False,
) -> None:
"""The initialization"""
super().__init__()
if logspace:
frequencies = 2.0 ** torch.arange(num_freqs, dtype=torch.float32)
else:
frequencies = torch.linspace(
1.0, 2.0 ** (num_freqs - 1), num_freqs, dtype=torch.float32
)
if include_pi:
frequencies *= torch.pi
self.register_buffer("frequencies", frequencies, persistent=False)
self.include_input = include_input
self.num_freqs = num_freqs
self.use_pmpe = use_pmpe
if use_pmpe:
phase = torch.arange(num_freqs, dtype=torch.float32)
for i in range(num_freqs):
phase[i] = torch.pow(torch.tensor(num_freqs), 1.0-(i+1)/num_freqs)+(i+1)/num_freqs
phase *= torch.pi*2
self.register_buffer("phase", phase, persistent=False)
self.out_dim = self.get_dims(input_dim)
def get_dims(self, input_dim):
temp = 1 if self.include_input or self.num_freqs == 0 else 0
out_dim = input_dim * (self.num_freqs * 2 + temp)
return out_dim
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""Forward process.
Args:
x: tensor of shape [..., dim]
Returns:
embedding: an embedding of `x` of shape [..., dim * (num_freqs * 2 + temp)]
where temp is 1 if include_input is True and 0 otherwise.
"""
if self.num_freqs > 0:
embed = (x[..., None].contiguous() * self.frequencies).view(
*x.shape[:-1], -1
)
if self.use_pmpe:
phase = (x[..., None].contiguous()*torch.pi*0.5 + self.phase).view(
*x.shape[:-1], -1
)
res = torch.cat((embed.sin()+phase.sin(), embed.cos()+phase.cos()), dim=-1)
else:
res = torch.cat((embed.sin(), embed.cos()), dim=-1)
if self.include_input:
return torch.cat((x, res), dim=-1)
else:
return res
else:
return x

View file

@ -0,0 +1,41 @@
from typing import Callable, Optional
from .tripo2_transformer import Tripo2DiTModel
def default_set_attn_proc_func(
name: str,
hidden_size: int,
cross_attention_dim: Optional[int],
ori_attn_proc: object,
) -> object:
return ori_attn_proc
def set_transformer_attn_processor(
transformer: Tripo2DiTModel,
set_self_attn_proc_func: Callable = default_set_attn_proc_func,
set_cross_attn_proc_func: Callable = default_set_attn_proc_func,
) -> None:
attn_procs = {}
for name, attn_processor in transformer.attn_processors.items():
hidden_size = transformer.config.width
if name.endswith("attn1.processor"):
# self attention
attn_procs[name] = set_self_attn_proc_func(
name, hidden_size, None, attn_processor
)
elif name.endswith("attn2.processor"):
# cross attention
cross_attention_dim = transformer.config.cross_attention_dim
attn_procs[name] = set_cross_attn_proc_func(
name, hidden_size, cross_attention_dim, attn_processor
)
elif name.endswith("attn2_2.processor"):
# cross attention 2
cross_attention_dim = transformer.config.cross_attention_2_dim
attn_procs[name] = set_cross_attn_proc_func(
name, hidden_size, cross_attention_dim, attn_processor
)
transformer.set_attn_processor(attn_procs)

View file

@ -0,0 +1,8 @@
from dataclasses import dataclass
import torch
@dataclass
class Transformer1DModelOutput:
sample: torch.FloatTensor

View file

@ -0,0 +1,664 @@
# Copyright 2024 HunyuanDiT Authors, Qixun Wang and The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Any, Dict, Optional, Tuple, Union
import torch
from diffusers.configuration_utils import ConfigMixin, register_to_config
from diffusers.models.attention import FeedForward
from diffusers.models.attention_processor import Attention, AttentionProcessor
from diffusers.models.embeddings import (
GaussianFourierProjection,
TimestepEmbedding,
Timesteps,
)
from diffusers.models.modeling_utils import ModelMixin
from diffusers.models.normalization import (
AdaLayerNormContinuous,
FP32LayerNorm,
LayerNorm,
)
from diffusers.utils import (
USE_PEFT_BACKEND,
is_torch_version,
logging,
scale_lora_layers,
unscale_lora_layers,
)
from diffusers.utils.torch_utils import maybe_allow_in_graph
from torch import nn
from ..attention_processor import FusedTripo2AttnProcessor2_0, Tripo2AttnProcessor2_0
from .modeling_outputs import Transformer1DModelOutput
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
@maybe_allow_in_graph
class DiTBlock(nn.Module):
r"""
Transformer block used in Hunyuan-DiT model (https://github.com/Tencent/HunyuanDiT). Allow skip connection and
QKNorm
Parameters:
dim (`int`):
The number of channels in the input and output.
num_attention_heads (`int`):
The number of headsto use for multi-head attention.
cross_attention_dim (`int`,*optional*):
The size of the encoder_hidden_states vector for cross attention.
dropout(`float`, *optional*, defaults to 0.0):
The dropout probability to use.
activation_fn (`str`,*optional*, defaults to `"geglu"`):
Activation function to be used in feed-forward. .
norm_elementwise_affine (`bool`, *optional*, defaults to `True`):
Whether to use learnable elementwise affine parameters for normalization.
norm_eps (`float`, *optional*, defaults to 1e-6):
A small constant added to the denominator in normalization layers to prevent division by zero.
final_dropout (`bool` *optional*, defaults to False):
Whether to apply a final dropout after the last feed-forward layer.
ff_inner_dim (`int`, *optional*):
The size of the hidden layer in the feed-forward block. Defaults to `None`.
ff_bias (`bool`, *optional*, defaults to `True`):
Whether to use bias in the feed-forward block.
skip (`bool`, *optional*, defaults to `False`):
Whether to use skip connection. Defaults to `False` for down-blocks and mid-blocks.
qk_norm (`bool`, *optional*, defaults to `True`):
Whether to use normalization in QK calculation. Defaults to `True`.
"""
def __init__(
self,
dim: int,
num_attention_heads: int,
use_self_attention: bool = True,
use_cross_attention: bool = False,
self_attention_norm_type: Optional[str] = None, # ada layer norm
cross_attention_dim: Optional[int] = None,
cross_attention_norm_type: Optional[str] = "fp32_layer_norm",
# parallel second cross attention
use_cross_attention_2: bool = False,
cross_attention_2_dim: Optional[int] = None,
cross_attention_2_norm_type: Optional[str] = None,
dropout=0.0,
activation_fn: str = "gelu",
norm_type: str = "fp32_layer_norm", # TODO
norm_elementwise_affine: bool = True,
norm_eps: float = 1e-5,
final_dropout: bool = False,
ff_inner_dim: Optional[int] = None, # int(dim * 4) if None
ff_bias: bool = True,
skip: bool = False,
skip_concat_front: bool = False, # [x, skip] or [skip, x]
skip_norm_last: bool = False, # this is an error
qk_norm: bool = True,
qkv_bias: bool = True,
):
super().__init__()
self.use_self_attention = use_self_attention
self.use_cross_attention = use_cross_attention
self.use_cross_attention_2 = use_cross_attention_2
self.skip_concat_front = skip_concat_front
self.skip_norm_last = skip_norm_last
# Define 3 blocks. Each block has its own normalization layer.
# NOTE: when new version comes, check norm2 and norm 3
# 1. Self-Attn
if use_self_attention:
if (
self_attention_norm_type == "fp32_layer_norm"
or self_attention_norm_type is None
):
self.norm1 = FP32LayerNorm(dim, norm_eps, norm_elementwise_affine)
else:
raise NotImplementedError
self.attn1 = Attention(
query_dim=dim,
cross_attention_dim=None,
dim_head=dim // num_attention_heads,
heads=num_attention_heads,
qk_norm="rms_norm" if qk_norm else None,
eps=1e-6,
bias=qkv_bias,
processor=Tripo2AttnProcessor2_0(),
)
# 2. Cross-Attn
if use_cross_attention:
assert cross_attention_dim is not None
self.norm2 = FP32LayerNorm(dim, norm_eps, norm_elementwise_affine)
self.attn2 = Attention(
query_dim=dim,
cross_attention_dim=cross_attention_dim,
dim_head=dim // num_attention_heads,
heads=num_attention_heads,
qk_norm="rms_norm" if qk_norm else None,
cross_attention_norm=cross_attention_norm_type,
eps=1e-6,
bias=qkv_bias,
processor=Tripo2AttnProcessor2_0(),
)
# 2'. Parallel Second Cross-Attn
if use_cross_attention_2:
assert cross_attention_2_dim is not None
self.norm2_2 = FP32LayerNorm(dim, norm_eps, norm_elementwise_affine)
self.attn2_2 = Attention(
query_dim=dim,
cross_attention_dim=cross_attention_2_dim,
dim_head=dim // num_attention_heads,
heads=num_attention_heads,
qk_norm="rms_norm" if qk_norm else None,
cross_attention_norm=cross_attention_2_norm_type,
eps=1e-6,
bias=qkv_bias,
processor=Tripo2AttnProcessor2_0(),
)
# 3. Feed-forward
self.norm3 = FP32LayerNorm(dim, norm_eps, norm_elementwise_affine)
self.ff = FeedForward(
dim,
dropout=dropout, ### 0.0
activation_fn=activation_fn, ### approx GeLU
final_dropout=final_dropout, ### 0.0
inner_dim=ff_inner_dim, ### int(dim * mlp_ratio)
bias=ff_bias,
)
# 4. Skip Connection
if skip:
self.skip_norm = FP32LayerNorm(dim, norm_eps, elementwise_affine=True)
self.skip_linear = nn.Linear(2 * dim, dim)
else:
self.skip_linear = None
# let chunk size default to None
self._chunk_size = None
self._chunk_dim = 0
# Copied from diffusers.models.attention.BasicTransformerBlock.set_chunk_feed_forward
def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int = 0):
# Sets chunk feed-forward
self._chunk_size = chunk_size
self._chunk_dim = dim
def forward(
self,
hidden_states: torch.Tensor,
encoder_hidden_states: Optional[torch.Tensor] = None,
encoder_hidden_states_2: Optional[torch.Tensor] = None,
temb: Optional[torch.Tensor] = None,
image_rotary_emb: Optional[torch.Tensor] = None,
skip: Optional[torch.Tensor] = None,
attention_kwargs: Optional[Dict[str, Any]] = None,
) -> torch.Tensor:
# Prepare attention kwargs
attention_kwargs = attention_kwargs or {}
# Notice that normalization is always applied before the real computation in the following blocks.
# 0. Long Skip Connection
if self.skip_linear is not None:
cat = torch.cat(
(
[skip, hidden_states]
if self.skip_concat_front
else [hidden_states, skip]
),
dim=-1,
)
if self.skip_norm_last:
# don't do this
hidden_states = self.skip_linear(cat)
hidden_states = self.skip_norm(hidden_states)
else:
cat = self.skip_norm(cat)
hidden_states = self.skip_linear(cat)
# 1. Self-Attention
if self.use_self_attention:
norm_hidden_states = self.norm1(hidden_states)
attn_output = self.attn1(
norm_hidden_states,
image_rotary_emb=image_rotary_emb,
**attention_kwargs,
)
hidden_states = hidden_states + attn_output
# 2. Cross-Attention
if self.use_cross_attention:
if self.use_cross_attention_2:
hidden_states = (
hidden_states
+ self.attn2(
self.norm2(hidden_states),
encoder_hidden_states=encoder_hidden_states,
image_rotary_emb=image_rotary_emb,
**attention_kwargs,
)
+ self.attn2_2(
self.norm2_2(hidden_states),
encoder_hidden_states=encoder_hidden_states_2,
image_rotary_emb=image_rotary_emb,
**attention_kwargs,
)
)
else:
hidden_states = hidden_states + self.attn2(
self.norm2(hidden_states),
encoder_hidden_states=encoder_hidden_states,
image_rotary_emb=image_rotary_emb,
**attention_kwargs,
)
# FFN Layer ### TODO: switch norm2 and norm3 in the state dict
mlp_inputs = self.norm3(hidden_states)
hidden_states = hidden_states + self.ff(mlp_inputs)
return hidden_states
class Tripo2DiTModel(ModelMixin, ConfigMixin):
"""
Tripo2DiT: Diffusion model with a Transformer backbone.
Inherit ModelMixin and ConfigMixin to be compatible with the sampler StableDiffusionPipeline of diffusers.
Parameters:
num_attention_heads (`int`, *optional*, defaults to 16):
The number of heads to use for multi-head attention.
attention_head_dim (`int`, *optional*, defaults to 88):
The number of channels in each head.
in_channels (`int`, *optional*):
The number of channels in the input and output (specify if the input is **continuous**).
patch_size (`int`, *optional*):
The size of the patch to use for the input.
activation_fn (`str`, *optional*, defaults to `"geglu"`):
Activation function to use in feed-forward.
sample_size (`int`, *optional*):
The width of the latent images. This is fixed during training since it is used to learn a number of
position embeddings.
dropout (`float`, *optional*, defaults to 0.0):
The dropout probability to use.
cross_attention_dim (`int`, *optional*):
The number of dimension in the clip text embedding.
hidden_size (`int`, *optional*):
The size of hidden layer in the conditioning embedding layers.
num_layers (`int`, *optional*, defaults to 1):
The number of layers of Transformer blocks to use.
mlp_ratio (`float`, *optional*, defaults to 4.0):
The ratio of the hidden layer size to the input size.
learn_sigma (`bool`, *optional*, defaults to `True`):
Whether to predict variance.
cross_attention_dim_t5 (`int`, *optional*):
The number dimensions in t5 text embedding.
pooled_projection_dim (`int`, *optional*):
The size of the pooled projection.
text_len (`int`, *optional*):
The length of the clip text embedding.
text_len_t5 (`int`, *optional*):
The length of the T5 text embedding.
use_style_cond_and_image_meta_size (`bool`, *optional*):
Whether or not to use style condition and image meta size. True for version <=1.1, False for version >= 1.2
"""
@register_to_config
def __init__(
self,
num_attention_heads: int = 16,
width: int = 2048,
in_channels: int = 64,
num_layers: int = 21,
cross_attention_dim: int = 768,
cross_attention_2_dim: int = 1024,
):
super().__init__()
self.out_channels = in_channels
self.num_heads = num_attention_heads
self.inner_dim = width
self.mlp_ratio = 4.0
time_embed_dim, timestep_input_dim = self._set_time_proj(
"positional",
inner_dim=self.inner_dim,
flip_sin_to_cos=False,
freq_shift=0,
time_embedding_dim=None,
)
self.time_proj = TimestepEmbedding(
timestep_input_dim, time_embed_dim, act_fn="gelu", out_dim=self.inner_dim
)
self.proj_in = nn.Linear(self.config.in_channels, self.inner_dim, bias=True)
self.blocks = nn.ModuleList(
[
DiTBlock(
dim=self.inner_dim,
num_attention_heads=self.config.num_attention_heads,
use_self_attention=True,
use_cross_attention=True,
self_attention_norm_type="fp32_layer_norm",
cross_attention_dim=self.config.cross_attention_dim,
cross_attention_norm_type=None,
use_cross_attention_2=True,
cross_attention_2_dim=self.config.cross_attention_2_dim,
cross_attention_2_norm_type=None,
activation_fn="gelu",
norm_type="fp32_layer_norm", # TODO
norm_eps=1e-5,
ff_inner_dim=int(self.inner_dim * self.mlp_ratio),
skip=layer > num_layers // 2,
skip_concat_front=True,
skip_norm_last=True, # this is an error
qk_norm=True, # See http://arxiv.org/abs/2302.05442 for details.
qkv_bias=False,
)
for layer in range(num_layers)
]
)
self.norm_out = LayerNorm(self.inner_dim)
self.proj_out = nn.Linear(self.inner_dim, self.out_channels, bias=True)
def _set_time_proj(
self,
time_embedding_type: str,
inner_dim: int,
flip_sin_to_cos: bool,
freq_shift: float,
time_embedding_dim: int,
) -> Tuple[int, int]:
if time_embedding_type == "fourier":
time_embed_dim = time_embedding_dim or inner_dim * 2
if time_embed_dim % 2 != 0:
raise ValueError(
f"`time_embed_dim` should be divisible by 2, but is {time_embed_dim}."
)
self.time_embed = GaussianFourierProjection(
time_embed_dim // 2,
set_W_to_weight=False,
log=False,
flip_sin_to_cos=flip_sin_to_cos,
)
timestep_input_dim = time_embed_dim
elif time_embedding_type == "positional":
time_embed_dim = time_embedding_dim or inner_dim * 4
self.time_embed = Timesteps(inner_dim, flip_sin_to_cos, freq_shift)
timestep_input_dim = inner_dim
else:
raise ValueError(
f"{time_embedding_type} does not exist. Please make sure to use one of `fourier` or `positional`."
)
return time_embed_dim, timestep_input_dim
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections with FusedAttnProcessor2_0->FusedTripo2AttnProcessor2_0
def fuse_qkv_projections(self):
"""
Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
are fused. For cross-attention modules, key and value projection matrices are fused.
<Tip warning={true}>
This API is 🧪 experimental.
</Tip>
"""
self.original_attn_processors = None
for _, attn_processor in self.attn_processors.items():
if "Added" in str(attn_processor.__class__.__name__):
raise ValueError(
"`fuse_qkv_projections()` is not supported for models having added KV projections."
)
self.original_attn_processors = self.attn_processors
for module in self.modules():
if isinstance(module, Attention):
module.fuse_projections(fuse=True)
self.set_attn_processor(FusedTripo2AttnProcessor2_0())
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
def unfuse_qkv_projections(self):
"""Disables the fused QKV projection if enabled.
<Tip warning={true}>
This API is 🧪 experimental.
</Tip>
"""
if self.original_attn_processors is not None:
self.set_attn_processor(self.original_attn_processors)
@property
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
def attn_processors(self) -> Dict[str, AttentionProcessor]:
r"""
Returns:
`dict` of attention processors: A dictionary containing all attention processors used in the model with
indexed by its weight name.
"""
# set recursively
processors = {}
def fn_recursive_add_processors(
name: str,
module: torch.nn.Module,
processors: Dict[str, AttentionProcessor],
):
if hasattr(module, "get_processor"):
processors[f"{name}.processor"] = module.get_processor()
for sub_name, child in module.named_children():
fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
return processors
for name, module in self.named_children():
fn_recursive_add_processors(name, module, processors)
return processors
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
def set_attn_processor(
self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]
):
r"""
Sets the attention processor to use to compute attention.
Parameters:
processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
The instantiated processor class or a dictionary of processor classes that will be set as the processor
for **all** `Attention` layers.
If `processor` is a dict, the key needs to define the path to the corresponding cross attention
processor. This is strongly recommended when setting trainable attention processors.
"""
count = len(self.attn_processors.keys())
if isinstance(processor, dict) and len(processor) != count:
raise ValueError(
f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
)
def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
if hasattr(module, "set_processor"):
if not isinstance(processor, dict):
module.set_processor(processor)
else:
module.set_processor(processor.pop(f"{name}.processor"))
for sub_name, child in module.named_children():
fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
for name, module in self.named_children():
fn_recursive_attn_processor(name, module, processor)
def set_default_attn_processor(self):
"""
Disables custom attention processors and sets the default attention implementation.
"""
self.set_attn_processor(Tripo2AttnProcessor2_0())
def forward(
self,
hidden_states: Optional[torch.Tensor],
timestep: Union[int, float, torch.LongTensor],
encoder_hidden_states: Optional[torch.Tensor] = None,
encoder_hidden_states_2: Optional[torch.Tensor] = None,
attention_kwargs: Optional[Dict[str, Any]] = None,
return_dict: bool = True,
):
"""
The [`HunyuanDiT2DModel`] forward method.
Args:
hidden_states (`torch.Tensor` of shape `(batch size, dim, height, width)`):
The input tensor.
timestep ( `torch.LongTensor`, *optional*):
Used to indicate denoising step.
encoder_hidden_states ( `torch.Tensor` of shape `(batch size, sequence len, embed dims)`, *optional*):
Conditional embeddings for cross attention layer.
encoder_hidden_states_2 ( `torch.Tensor` of shape `(batch size, sequence len, embed dims)`, *optional*):
Conditional embeddings for cross attention layer.
return_dict: bool
Whether to return a dictionary.
"""
if attention_kwargs is not None:
attention_kwargs = attention_kwargs.copy()
lora_scale = attention_kwargs.pop("scale", 1.0)
else:
lora_scale = 1.0
if USE_PEFT_BACKEND:
# weight the lora layers by setting `lora_scale` for each PEFT layer
scale_lora_layers(self, lora_scale)
else:
if (
attention_kwargs is not None
and attention_kwargs.get("scale", None) is not None
):
logger.warning(
"Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
)
_, N, _ = hidden_states.shape
temb = self.time_embed(timestep).to(hidden_states.dtype)
temb = self.time_proj(temb)
temb = temb.unsqueeze(dim=1) # unsqueeze to concat with hidden_states
hidden_states = self.proj_in(hidden_states)
# N + 1 token
hidden_states = torch.cat([temb, hidden_states], dim=1)
skips = []
for layer, block in enumerate(self.blocks):
if layer <= self.config.num_layers // 2:
hidden_states = block(
hidden_states,
temb=temb,
encoder_hidden_states=encoder_hidden_states,
encoder_hidden_states_2=encoder_hidden_states_2,
attention_kwargs=attention_kwargs,
) # (N, L, D)
else:
skip = skips.pop()
hidden_states = block(
hidden_states,
temb=temb,
encoder_hidden_states=encoder_hidden_states,
encoder_hidden_states_2=encoder_hidden_states_2,
skip=skip,
attention_kwargs=attention_kwargs,
) # (N, L, D)
if layer < self.config.num_layers // 2:
skips.append(hidden_states)
# final layer
hidden_states = self.norm_out(hidden_states)
hidden_states = hidden_states[:, -N:]
hidden_states = self.proj_out(hidden_states)
if USE_PEFT_BACKEND:
# remove `lora_scale` from each PEFT layer
unscale_lora_layers(self, lora_scale)
if not return_dict:
return (hidden_states,)
return Transformer1DModelOutput(sample=hidden_states)
# Copied from diffusers.models.unets.unet_3d_condition.UNet3DConditionModel.enable_forward_chunking
def enable_forward_chunking(
self, chunk_size: Optional[int] = None, dim: int = 0
) -> None:
"""
Sets the attention processor to use [feed forward
chunking](https://huggingface.co/blog/reformer#2-chunked-feed-forward-layers).
Parameters:
chunk_size (`int`, *optional*):
The chunk size of the feed-forward layers. If not specified, will run feed-forward layer individually
over each tensor of dim=`dim`.
dim (`int`, *optional*, defaults to `0`):
The dimension over which the feed-forward computation should be chunked. Choose between dim=0 (batch)
or dim=1 (sequence length).
"""
if dim not in [0, 1]:
raise ValueError(f"Make sure to set `dim` to either 0 or 1, not {dim}")
# By default chunk size is 1
chunk_size = chunk_size or 1
def fn_recursive_feed_forward(
module: torch.nn.Module, chunk_size: int, dim: int
):
if hasattr(module, "set_chunk_feed_forward"):
module.set_chunk_feed_forward(chunk_size=chunk_size, dim=dim)
for child in module.children():
fn_recursive_feed_forward(child, chunk_size, dim)
for module in self.children():
fn_recursive_feed_forward(module, chunk_size, dim)
# Copied from diffusers.models.unets.unet_3d_condition.UNet3DConditionModel.disable_forward_chunking
def disable_forward_chunking(self):
def fn_recursive_feed_forward(
module: torch.nn.Module, chunk_size: int, dim: int
):
if hasattr(module, "set_chunk_feed_forward"):
module.set_chunk_feed_forward(chunk_size=chunk_size, dim=dim)
for child in module.children():
fn_recursive_feed_forward(child, chunk_size, dim)
for module in self.children():
fn_recursive_feed_forward(module, None, 0)

View file

@ -0,0 +1,208 @@
from dataclasses import asdict, dataclass
from omegaconf import OmegaConf
from scipy.spatial import cKDTree # type: ignore
from torch import nn, Tensor
from typing import Dict, List
import math
import numpy as np
import random
import torch
import torch.nn.functional as F
from src.rig_package.info.asset import Asset
from .spec import ModelSpec, ModelInput, VaeInput
from .skin_vae.autoencoders import SkinFSQCVAEModel
try:
from flash_attn_interface import flash_attn_func # type: ignore
except Exception as e:
from flash_attn.flash_attn_interface import flash_attn_func as _flash_attn_func
def flash_attn_func(*args, **kwargs):
res = _flash_attn_func(*args, **kwargs)
return res, None
class Perceiver(nn.Module):
def __init__(self, channels, out_tokens, num_heads=8):
super().__init__()
self.q_vec = nn.Parameter(torch.randn(out_tokens // num_heads, num_heads, channels) * 0.02)
self.num_heads = num_heads
self.head_dim = channels // num_heads
self.k_proj = nn.Linear(channels, channels)
self.v_proj = nn.Linear(channels, channels)
self.out_proj = nn.Linear(channels, channels)
def forward(self, x: Tensor) -> Tensor:
B, N, C = x.shape
k = self.k_proj(x) # [B, N, C]
v = self.v_proj(x) # [B, N, C]
q_repeated = self.q_vec.repeat(B, 1, 1, 1)
q = q_repeated.view(B, -1, self.num_heads, self.head_dim).type(torch.bfloat16)
k = k.view(B, -1, self.num_heads, self.head_dim)
v = v.view(B, -1, self.num_heads, self.head_dim)
hidden_states, _ = flash_attn_func(q, k, v)
hidden_states = hidden_states.view(B, -1, self.num_heads * self.head_dim) # type: ignore
hidden_states = self.out_proj(hidden_states)
return hidden_states
class SkinVAEModel(ModelSpec):
def __init__(self, model_config, transform_config, tokenizer_config=None):
super().__init__(model_config, transform_config, tokenizer_config)
cfg = self.model_config
self.cond_tokens = cfg['sample']['cond_tokens']
self.compress_tokens = cfg['sample']['compress_tokens']
self.sample_tokens = cfg['sample']['sample_tokens']
self.only_dense = cfg['sample'].get('only_dense', False)
self.model_type = cfg.get('type', 'fsqc')
if self.model_type == 'fsqc':
self.model = SkinFSQCVAEModel(**cfg['model'], sample_tokens=self.sample_tokens)
else:
raise NotImplementedError()
if self.sample_tokens != self.compress_tokens:
self.down_perceiver = Perceiver(self.model.latent_channels, self.compress_tokens)
if self.sample_tokens != self.compress_tokens:
self.up_perceiver = Perceiver(self.model.latent_channels, self.sample_tokens)
def compile_model(self):
self.model.compile_model()
@property
def vocab_size(self) -> int:
return self.model.FSQ.codebook_size
@property
def latent_channels(self) -> int:
return self.model.latent_channels
def encode(self, vae_input: VaeInput, num_tokens: int=4, j: int=0, full: bool=False, encode_repeat: int=4, return_cond: bool=True):
raise NotImplementedError()
def decode(self, z: Tensor, sampled_cond: Tensor, cond_tokens: Tensor, full: bool=False, encode_repeat: int=4) -> Tensor:
assert z.shape[0] == sampled_cond.shape[0] == cond_tokens.shape[0]
if full:
l = z.shape[0]
s = []
for i in range(0, l, encode_repeat):
t = min(l,i+encode_repeat)
if self.sample_tokens != self.compress_tokens:
_z = self.up_perceiver(z[i:t])
else:
_z = z[i:t]
logits = self.model._decode(z=_z, cond=cond_tokens[i:t], sampled_points=sampled_cond[i:t])
s.append(logits)
return torch.cat(s, dim=0)
else:
if self.sample_tokens != self.compress_tokens:
z = self.up_perceiver(z)
logits = self.model._decode(z=z, cond=cond_tokens, sampled_points=sampled_cond)
return logits
def get_loss_dict(
self,
skin_pred: Tensor,
skin_gt: Tensor,
) -> Dict[str, Tensor]:
raise NotImplementedError()
def get_input(self, batch: Dict) -> VaeInput:
vertices: Tensor = batch['vertices'].float() # (B, N, 3)
normals: Tensor = batch['normals'].float() # (B, N, 3)
uniform_skin: List[Tensor] = batch['uniform_skin'] # [(N, J)]
dense_skin: List[Tensor] = batch['dense_skin'] # [(J, skin_samples)]
dense_vertices: List[Tensor] = batch['dense_vertices'] # [(J, skin_samples, 3)]
dense_normals: List[Tensor] = batch['dense_normals'] # [(J, skin_samples, 3)]
dense_indices: List[List[int]] = batch['dense_indices'] # [List[J]]
B = vertices.shape[0]
uniform_cond = torch.cat([vertices, normals], dim=-1).float()
dense_cond = []
for i in range(B):
dense_cond.append(torch.cat([dense_vertices[i], dense_normals[i]], dim=-1).float())
uniform_skin = [s.float() for s in uniform_skin]
dense_skin = [s.float() for s in dense_skin]
return VaeInput(
dense_cond=dense_cond,
dense_skin=dense_skin,
dense_indices=dense_indices,
uniform_cond=uniform_cond,
uniform_skin=uniform_skin,
)
@torch.autocast(device_type='cuda', dtype=torch.bfloat16)
def training_step(self, batch: Dict) -> Dict:
raise NotImplementedError()
def process_fn(self, batch: List[ModelInput], is_train: bool = True) -> List[Dict]:
res = []
for b in batch:
asset = b.asset
assert asset is not None
assert asset.sampled_vertex_groups is not None
assert 'skin' in asset.sampled_vertex_groups
assert asset.meta is not None
assert 'dense_indices' in asset.meta
assert 'dense_skin' in asset.meta
assert 'dense_vertices' in asset.meta
assert 'dense_normals' in asset.meta
_d = {
'vertices': asset.sampled_vertices,
'normals': b.asset.sampled_normals,
'non': {
'uniform_skin': asset.sampled_vertex_groups['skin'],
'num_bones': asset.J,
'skin_samples': asset.skin_samples,
'dense_indices': asset.meta['dense_indices'],
'dense_skin': asset.meta['dense_skin'],
'dense_vertices': asset.meta['dense_vertices'],
'dense_normals': asset.meta['dense_normals'],
}
}
res.append(_d)
return res
def forward(self, batch: Dict) -> Dict:
return self.training_step(batch=batch)
@torch.autocast('cuda', dtype=torch.bfloat16)
def predict_step(self, batch: Dict) -> Dict:
vertices: Tensor = batch['vertices'].float() # (B, N, 3)
num_bones: List[int] = batch['num_bones']
B = vertices.shape[0]
N = vertices.shape[1]
vae_input = self.get_input(batch=batch)
num_tokens = 4
z, cond_tokens, indices, _ = self.encode(vae_input=vae_input, num_tokens=num_tokens, full=True, encode_repeat=8)
assert cond_tokens is not None
z = self.model.FSQ.indices_to_codes(indices).reshape(z.shape)
_skin_pred = self.decode(z=z, sampled_cond=vae_input.get_flatten_uniform_cond(), cond_tokens=cond_tokens[vae_input.get_flatten_indices()], full=True, encode_repeat=8)
_skin_pred = _skin_pred.squeeze(-1)
tot = 0
results = []
for i in range(B):
asset: Asset = batch['model_input'][i].asset.copy()
skin_pred = torch.zeros((N, num_bones[i]), dtype=vertices.dtype, device=vertices.device)
for j in range(vae_input.get_len(i=i)):
skin_pred[:, vae_input.true_j(i=i, j=j)] = _skin_pred[tot]
tot += 1
sampled_vertices = vertices[i].detach().float().cpu().numpy()
tree = cKDTree(sampled_vertices)
distances, indices = tree.query(asset.vertices)
sampled_skin = skin_pred.detach().float().cpu().numpy()[indices]
asset.skin = sampled_skin
results.append(asset)
return {
'results': results,
}

300
thirdparty/skintokens/src/model/spec.py vendored Normal file
View file

@ -0,0 +1,300 @@
from abc import ABC, abstractmethod
from copy import deepcopy
from dataclasses import dataclass
from numpy import ndarray
from omegaconf import OmegaConf
from typing import Dict, List, Optional, final
from torch import Tensor
import numpy as np
import lightning.pytorch as pl
import torch
from ..data.transform import Transform
from ..rig_package.info.asset import Asset
from ..tokenizer.spec import DetokenizeOutput
@dataclass
class ModelInput():
asset: Asset
tokens: Optional[ndarray]=None
class ModelSpec(pl.LightningModule, ABC):
model_config: Dict
transform_config: Dict
tokenizer_config: Dict|None
@abstractmethod
def __init__(self, model_config, transform_config, tokenizer_config=None):
super().__init__()
if not isinstance(model_config, dict):
model_cfg = OmegaConf.to_container(model_config, resolve=True)
else:
model_cfg = model_config
if not isinstance(transform_config, dict):
transform_cfg = OmegaConf.to_container(transform_config, resolve=True)
else:
transform_cfg = transform_config
if tokenizer_config is not None and not isinstance(tokenizer_config, dict):
tokenizer_cfg = OmegaConf.to_container(tokenizer_config, resolve=True)
else:
tokenizer_cfg = tokenizer_config
self.model_config = model_cfg # type: ignore
self.transform_config = transform_cfg # type: ignore
self.tokenizer_config = tokenizer_cfg # type: ignore
self.save_hyperparameters(model_cfg)
self.save_hyperparameters(transform_cfg)
self.save_hyperparameters(tokenizer_cfg)
@final
def _process_fn(self, batch: List[ModelInput]) -> List[Dict]:
n_batch = self.process_fn(batch)
if self._trainer is None or not self.trainer.training:
for k in n_batch[0].keys():
if not isinstance(n_batch[0][k], ndarray) and not isinstance(n_batch[0][k], Tensor):
continue
s = n_batch[0][k].shape
for i in range(1, len(n_batch)):
assert n_batch[i][k].shape == s, f"{k} has different shape in batch"
for (i, b) in enumerate(batch):
non = n_batch[i].get('non', {})
non['model_input'] = deepcopy(b)
n_batch[i]['non'] = non
else:
for b in batch:
del b.asset
return n_batch
@abstractmethod
def process_fn(self, batch: List[ModelInput]) -> List[Dict]:
"""
Fetch data from dataloader and turn it into Tensor objects.
"""
raise NotImplementedError()
def compile_model(self):
"""
Compile the model. Do this before training and after loading state dicts.
"""
pass
@classmethod
def load_from_system_checkpoint(cls, checkpoint_path: str, strict: bool=True, **kwargs):
ckpt = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
state_dict = ckpt['state_dict']
model_config = kwargs.get('model_config', None)
transform_config = kwargs.get('transform_config', None)
tokenizer_config = kwargs.get('tokenizer_config', None)
if model_config is None:
model_config = ckpt['hyper_parameters']['model_config']
if transform_config is None:
transform_config = ckpt['hyper_parameters']['transform_config']
if tokenizer_config is None:
tokenizer_config = ckpt['hyper_parameters']['tokenizer_config']
new_state_dict = {}
for k, v in state_dict.items():
k = k.replace("_orig_mod.", "")
if k.startswith("model."):
k = k[len("model.") :]
new_state_dict[k] = v
model = cls(
model_config=model_config,
transform_config=transform_config,
tokenizer_config=tokenizer_config,
)
missing, unexpected = model.load_state_dict(new_state_dict, strict=strict)
if missing or unexpected:
print(f"[Warning] Missing keys: {missing}")
print(f"[Warning] Unexpected keys: {unexpected}")
model.on_load_checkpoint(ckpt)
return model
def get_train_transform(self) -> Transform|None:
cfg = self.transform_config.get('train_transform', None)
if cfg is None:
return None
return Transform.parse(**cfg)
def get_validate_transform(self) -> Transform|None:
cfg = self.transform_config.get('validate_transform', None)
if cfg is None:
return None
return Transform.parse(**cfg)
def get_predict_transform(self) -> Transform|None:
cfg = self.transform_config.get('predict_transform', None)
if cfg is None:
return None
return Transform.parse(**cfg)
def predict_step(self, batch: Dict, no_cls: bool=False, skeleton_tokens=None) -> Dict:
raise NotImplementedError()
@dataclass
class VaeInput():
dense_cond: List[Tensor] # [(J, skin_samples, 6)]
dense_skin: List[Tensor] # [(J, skin_samples)]
dense_indices: List[List[int]] # [List[J]], corresponding indices of gt
uniform_cond: Tensor # (B, N, 6)
uniform_skin: List[Tensor] # [(N, J)]
@property
def B(self):
return self.uniform_cond.shape[0]
@property
def max_J(self):
return max([len(s) for s in self.dense_indices])
def get_len(self, i) -> int:
return len(self.dense_indices[i])
def _clamp_j(self, i: int, j: int) -> int:
return min(j, len(self.dense_indices[i])-1)
def get_dense_cond(self, j: int) -> Tensor:
"""return (B, skin_samples, 6)"""
return torch.stack([self.dense_cond[i][self._clamp_j(i=i, j=j)] for i in range(self.B)])
def get_dense_skin(self, j: int) -> Tensor:
"""return (B, skin_samples)"""
return torch.stack([self.dense_skin[i][self._clamp_j(i=i, j=j)] for i in range(self.B)])
def get_full_cond(self, j: int) -> Tensor:
"""return (B, N+skin_samples, 6)"""
return torch.cat([self.uniform_cond, self.get_dense_cond(j=j)], dim=1)
def get_uniform_skin(self, j: int) -> Tensor:
"""return (B, N)"""
return torch.stack([self.uniform_skin[i][:, self._clamp_j(i=i, j=j)] for i in range(self.B)])
def get_full_skin(self, j: int) -> Tensor:
"""return (B, N+skin_samples)"""
return torch.cat([self.get_uniform_skin(j=j), self.get_dense_skin(j=j)], dim=1)
def get_flatten_uniform_cond(self) -> Tensor:
"""return (sum_J, N, 6)"""
return self.uniform_cond[self.get_flatten_indices()]
def get_flatten_dense_cond(self) -> Tensor:
"""return (sum_J, skin_samples, 6)"""
return torch.cat(self.dense_cond, dim=0)
def get_flatten_dense_skin(self) -> Tensor:
"""return (sum_J, skin_samples)"""
return torch.cat(self.dense_skin, dim=0)
def get_flatten_full_skin(self) -> Tensor:
"""return (sum_J, N+skin_samples)"""
# (sum_J, N)
s = torch.cat(self.uniform_skin, dim=-1).permute(1, 0)
return torch.cat([s, self.get_flatten_dense_skin()], dim=1)
def get_flatten_full_cond(self) -> Tensor:
"""return (sum_J, N+skin_samples, 6)"""
return torch.cat([self.get_flatten_uniform_cond(), self.get_flatten_dense_cond()], dim=1)
def get_flatten_indices(self) -> List[int]:
"""return (sum_J)"""
return [i for i in range(self.B) for _ in range(self.get_len(i=i))]
def true_j(self, i: int, j: int) -> int:
"""return (clamped) corresponding indice in the skeleton"""
return self.dense_indices[i][self._clamp_j(i=i, j=j)]
@dataclass
class TokenRigResult():
cond: Optional[Tensor]=None # [vertices, normals]
cond_latents: Optional[Tensor]=None # (len, dim)
input_ids: Optional[Tensor]=None # (l,)
output_ids: Optional[Tensor]=None # (l,)
skin_pred: Optional[Tensor]=None # (N, J)
detokenize_output: Optional[DetokenizeOutput]=None
asset: Optional[Asset]=None
@dataclass
class BoneVaeInput():
dense_cond: List[Tensor] # [(J, skin_samples, 6)]
dense_skin: List[Tensor] # [(J, skin_samples)]
dense_indices: List[List[int]] # [List[J]], corresponding indices of gt
bones: List[Tensor] # [(J, 6)]
uniform_cond: Tensor # (B, N, 6)
uniform_skin: List[Tensor] # [(N, J)]
@property
def total_samples(self) -> int:
return self.dense_cond[0].shape[1] + self.uniform_cond.shape[1]
@property
def B(self) -> int:
return self.uniform_cond.shape[0]
@property
def max_J(self) -> int:
return max([len(s) for s in self.dense_indices])
def get_len(self, i) -> int:
return len(self.dense_indices[i])
def _clamp_j(self, i: int, j: int) -> int:
return min(j, len(self.dense_indices[i])-1)
def get_dense_cond(self, j: int) -> Tensor:
"""return (B, skin_samples, 6)"""
return torch.stack([self.dense_cond[i][self._clamp_j(i=i, j=j)] for i in range(self.B)])
def get_dense_skin(self, j: int) -> Tensor:
"""return (B, skin_samples)"""
return torch.stack([self.dense_skin[i][self._clamp_j(i=i, j=j)] for i in range(self.B)])
def get_full_cond(self, j: int) -> Tensor:
"""return (B, N+skin_samples, 6)"""
return torch.cat([self.uniform_cond, self.get_dense_cond(j=j)], dim=1)
def get_uniform_skin(self, j: int) -> Tensor:
"""return (B, N)"""
return torch.stack([self.uniform_skin[i][:, self._clamp_j(i=i, j=j)] for i in range(self.B)])
def get_full_skin(self, j: int) -> Tensor:
"""return (B, N+skin_samples)"""
return torch.cat([self.get_uniform_skin(j=j), self.get_dense_skin(j=j)], dim=1)
def get_bones(self, j: int) -> Tensor:
"""return (B, 3)"""
return torch.stack([self.bones[i][self._clamp_j(i=i, j=j)] for i in range(self.B)])
def get_flatten_bones(self) -> Tensor:
"""return (sum_J, 3)"""
return torch.cat([self.bones[i] for i in range(self.B)])
def get_flatten_uniform_cond(self) -> Tensor:
"""return (sum_J, N, 6)"""
return self.uniform_cond[self.get_flatten_indices()]
def get_flatten_dense_cond(self) -> Tensor:
"""return (sum_J, skin_samples, 6)"""
return torch.cat(self.dense_cond, dim=0)
def get_flatten_dense_skin(self) -> Tensor:
"""return (sum_J, skin_samples)"""
return torch.cat(self.dense_skin, dim=0)
def get_flatten_full_skin(self) -> Tensor:
"""return (sum_J, N+skin_samples)"""
# (sum_J, N)
s = torch.cat(self.uniform_skin, dim=-1).permute(1, 0)
return torch.cat([s, self.get_flatten_dense_skin()], dim=1)
def get_flatten_full_cond(self) -> Tensor:
"""return (sum_J, N+skin_samples, 6)"""
return torch.cat([self.get_flatten_uniform_cond(), self.get_flatten_dense_cond()], dim=1)
def get_flatten_indices(self) -> List[int]:
"""return (sum_J)"""
return [i for i in range(self.B) for _ in range(self.get_len(i=i))]
def true_j(self, i: int, j: int) -> int:
"""return (clamped) corresponding indice in the skeleton"""
return self.dense_indices[i][self._clamp_j(i=i, j=j)]

View file

@ -0,0 +1,666 @@
from copy import deepcopy
from pathlib import Path
from torch import nn, Tensor, FloatTensor
from torch.nn.functional import pad
from transformers import AutoModelForCausalLM, AutoConfig, LogitsProcessor, LogitsProcessorList # type: ignore
from typing import Dict, List, Tuple
import math
import numpy as np
import torch
import torch.nn.functional as F
LLM_LOCAL_DIR = Path("models/Qwen3-0.6B")
from .skin_vae_model import SkinVAEModel
from .skin_vae.autoencoders import SkinFSQCVAEModel
from .spec import ModelSpec, ModelInput, VaeInput, TokenRigResult
from .parse_encoder import MAP_MESH_ENCODER, get_mesh_encoder
from ..rig_package.info.asset import Asset
from ..tokenizer.spec import Tokenizer
from ..tokenizer.spec import DetokenizeOutput
from ..tokenizer.parse import get_tokenizer
try:
from flash_attn_interface import flash_attn_func # type: ignore
except Exception as e:
from flash_attn.flash_attn_interface import flash_attn_func as _flash_attn_func
def flash_attn_func(*args, **kwargs):
res = _flash_attn_func(*args, **kwargs)
return res, None
class VocabSwitchingLogitsProcessor(LogitsProcessor):
def __init__(self, tokenizer: Tokenizer, switch_token_id, eos_token_id, tokens_per_skin, init):
# make sure all skin tokens > switch_token_id
self.tokenizer = tokenizer
self.switch_token_id = switch_token_id
self.eos_token_id = eos_token_id
self.tokens_per_skin = tokens_per_skin
self.init = init
def __call__(self, input_ids: Tensor, scores: FloatTensor) -> FloatTensor:
# input_ids shape: (batch_size, seq_len)
for batch_idx, sequence in enumerate(input_ids):
mask = torch.full_like(scores[batch_idx], float('-inf'))
sequence = torch.cat([self.init, sequence])
length = len(sequence)
if self.switch_token_id in sequence:
mask[self.switch_token_id:] = 0
where = torch.where(sequence == self.switch_token_id)[0][:1]
J = self.tokenizer.bones_in_sequence(ids=sequence.detach().cpu().numpy())
if (length-where) == J*self.tokens_per_skin:
mask[:] = float('-inf')
mask[self.eos_token_id] = 0
else:
mask[self.eos_token_id] = float('-inf')
else:
tokens = self.tokenizer.next_posible_token(ids=sequence.detach().cpu().numpy())
mask[tokens] = 0
scores[batch_idx] = scores[batch_idx] + mask
return scores
class TokenRig(ModelSpec):
def __init__(self, model_config, transform_config, tokenizer_config=None):
assert tokenizer_config is not None
super().__init__(model_config=model_config, transform_config=transform_config, tokenizer_config=tokenizer_config)
cfg = self.model_config
self.tokens_per_skin: int = cfg['tokens_per_skin']
self.tokens_skin_cond: int = cfg['tokens_skin_cond']
self.use_rope: bool = cfg.get('use_rope', True)
self.encode_repeat: int = cfg.get('encode_repeat', 4)
self.skin_warmup_start_epoch: int = cfg.get('skin_warmup_start_epoch', 0)
self.skin_warmup_end_epoch: int = cfg.get('skin_warmup_end_epoch', -1)
self.vae = SkinVAEModel.load_from_system_checkpoint(cfg['pretrained_vae']).to(torch.bfloat16)
for param in self.vae.parameters():
param.requires_grad_(False)
self.vae.eval()
self.mesh_encoder = get_mesh_encoder(**cfg['mesh_encoder'])
assert (
isinstance(self.mesh_encoder, MAP_MESH_ENCODER.michelangelo) or
isinstance(self.mesh_encoder, MAP_MESH_ENCODER.michelangelo_encoder)
)
self.mesh_encoder = self.mesh_encoder.to(torch.bfloat16)
self.tokenizer: Tokenizer = get_tokenizer(**tokenizer_config)
# (tokenizer codebook, fsq vae codebook)
self.vocab_size = self.tokenizer.vocab_size + self.vae.vocab_size + 1
self.eos = self.vocab_size - 1
_d = cfg['llm'].copy()
self.hidden_size = _d['hidden_size']
_d['vocab_size'] = self.vocab_size
if LLM_LOCAL_DIR.exists():
_d['pretrained_model_name_or_path'] = str(LLM_LOCAL_DIR)
llm_config = AutoConfig.from_pretrained(**_d)
self.vocab_size = self.tokenizer.vocab_size + self.vae.vocab_size + 1
llm_config.torch_dtype = torch.bfloat16
llm_config.pre_norm = True
self.llm_config = llm_config
self.transformer = AutoModelForCausalLM.from_config(config=llm_config, attn_implementation="flash_attention_2").to(torch.bfloat16)
self.output_proj = nn.Sequential(
nn.Linear(self.mesh_encoder.width, self.hidden_size),
nn.RMSNorm(self.hidden_size),
).to(torch.bfloat16)
init_scale = cfg.get('init_scale', None)
if init_scale is not None:
self.initialize_weights(init_scale)
def compile_model(self):
self.vae.compile_model()
self.transformer = torch.compile(self.transformer, dynamic=False)
self.mesh_encoder = torch.compile(self.mesh_encoder, dynamic=False)
def initialize_weights(self, s: float):
def init_linear(l, stddev):
nn.init.normal_(l.weight, std=stddev)
if l.bias is not None:
nn.init.constant_(l.bias, 0.0)
init_scale = s * math.sqrt(1.0 / self.mesh_encoder.width)
for m in self.mesh_encoder.modules():
if isinstance(m, nn.Linear):
init_linear(m, stddev=init_scale)
init_scale = s * math.sqrt(1.0 / self.hidden_size)
for m in self.output_proj.modules():
if isinstance(m, nn.Linear):
init_linear(m, stddev=init_scale)
def get_skin_warmup_rate(self, steps_per_epoch: int) -> float:
if self.current_epoch < self.skin_warmup_start_epoch:
return 0.
if self.current_epoch > self.skin_warmup_end_epoch:
return 1.
start_steps = self.skin_warmup_start_epoch * steps_per_epoch
end_steps = (self.skin_warmup_end_epoch+1) * steps_per_epoch
rate = (self.global_step-start_steps) / (end_steps-start_steps)
return min(max((1.0-math.cos(math.pi * rate))/2, 0), 1)
@torch.autocast(device_type='cuda', dtype=torch.bfloat16)
def training_step(self, batch: Dict) -> Dict:
raise NotImplementedError()
def make_start_tokens(self, **kwargs) -> List[List[int]]:
skeleton_tokens = kwargs.get('skeleton_tokens', None)
skeleton_mask = kwargs.get('skeleton_mask', None)
num_joints = kwargs.get('num_joints', None)
parents = kwargs.get('parents', None)
cls = kwargs.get('cls', None)
start_tokens_list = []
batch_size = 1
if skeleton_tokens is not None:
batch_size = len(skeleton_tokens)
elif cls is not None:
batch_size = len(cls)
elif num_joints is not None:
batch_size = len(num_joints)
elif parents is not None:
batch_size = len(parents)
else:
assert 0, "must provide one of skeleton_tokens, cls, num_joints, parents"
for i in range(batch_size):
if skeleton_tokens is not None:
_skeleton_tokens = skeleton_tokens[i]
_skeleton_mask = skeleton_mask[i] if skeleton_mask is not None else None
assert _skeleton_tokens[0] == self.tokenizer.bos
if skeleton_mask is not None:
start_tokens = _skeleton_tokens[_skeleton_mask==1]
else:
start_tokens = _skeleton_tokens
else:
start_tokens = [self.tokenizer.bos]
start_tokens += self.tokenizer.make_cls_head(
cls=cls[i] if cls is not None else None,
num_joints=num_joints[i] if num_joints is not None else None,
parents=parents[i] if parents is not None else None,
)
if isinstance(start_tokens, Tensor):
start_tokens = start_tokens.detach().cpu().numpy().tolist()
start_tokens_list.append(start_tokens)
return start_tokens_list
@torch.autocast(device_type='cuda', dtype=torch.bfloat16)
def generate(
self,
vertices: Tensor,
normals: Tensor,
cls: str|None=None,
skeleton_tokens: np.ndarray|Tensor|None=None,
only_ids: bool=False,
return_decode_dict: bool=False,
num_joints: int|None=None,
parents: Tensor|None=None,
**kwargs,
) -> TokenRigResult:
"""
Do not support batch!
"""
assert isinstance(self.vae.model, SkinFSQCVAEModel)
assert vertices.dim() == 2, 'do not support batch'
assert normals.dim() == 2, 'do not support batch'
if isinstance(skeleton_tokens, np.ndarray):
skeleton_tokens = torch.from_numpy(skeleton_tokens).to(self.device)
cond = torch.cat([vertices, normals], dim=-1).unsqueeze(0)
_, cond_latents = self.vae.model._encode(
x=None,
cond=cond,
num_tokens=self.tokens_per_skin,
cond_tokens=self.tokens_skin_cond,
return_z=False,
)
assert cond_latents is not None
# (1, len, dim)
learned_mesh_cond = encode_mesh_cond(self.mesh_encoder, self.output_proj, self.tokens_skin_cond, {'vertices': vertices, 'normals': normals})
device = cond.device
start_tokens = torch.tensor(self.make_start_tokens(
device=device,
cls=None if cls is None else [cls],
skeleton_tokens=None if skeleton_tokens is None else [skeleton_tokens],
num_joints=None if num_joints is None else [num_joints],
parents=None if parents is None else [parents],
)[0], device=device).unsqueeze(0)
assert start_tokens.shape[0] == 1
start_embed = self.transformer.get_input_embeddings()(start_tokens)
inputs_embeds = torch.cat([learned_mesh_cond, start_embed], dim=1)
results = self.transformer.generate(
inputs_embeds=inputs_embeds,
bos_token_id=self.tokenizer.bos,
eos_token_id=self.eos,
pad_token_id=self.tokenizer.pad,
logits_processor=get_logits_processor(
tokenizer=self.tokenizer,
eos=self.eos,
tokens_per_skin=self.tokens_per_skin,
start_tokens=start_tokens[0],
),
**kwargs,
)
res = TokenRigResult()
output_ids = results[0, :]
for token in reversed(start_tokens[0]):
v = token.item()
output_ids = pad(output_ids, (1, 0), value=v)
res.input_ids = start_tokens[0]
res.output_ids = output_ids
if only_ids:
return res
res.cond = cond[0]
res.cond_latents = cond_latents[0]
if return_decode_dict:
return res
d = decode(
cond=cond[0],
cond_latents=cond_latents[0],
inputs_ids=output_ids,
tokenizer=self.tokenizer,
tokens_per_skin=self.tokens_per_skin,
vae=self.vae,
)
res.skin_pred = d['skin_pred']
res.detokenize_output = d['detokenize_output']
return res
def _debug_export(
self,
batch: Dict,
cond: Tensor,
cond_latents: Tensor,
inputs_ids: Tensor,
id: int=0,
path: str='res.fbx',
):
if inputs_ids.dim() == 2:
assert cond_latents.dim() == cond.dim() == 3, f"Expected 3 dimensions, got {cond_latents.dim()}, {cond.dim()}"
cond = cond[id]
cond_latents = cond_latents[id]
inputs_ids = inputs_ids[id]
res = decode(
cond=cond,
cond_latents=cond_latents,
inputs_ids=inputs_ids,
tokenizer=self.tokenizer,
tokens_per_skin=self.tokens_per_skin,
vae=self.vae,
)
detokenize_output: DetokenizeOutput = res['detokenize_output']
origin_asset: Asset = batch['model_input'][id].asset
asset = Asset.from_data(
vertices=origin_asset.vertices,
faces=origin_asset.faces,
sampled_vertices=batch['vertices'][id].detach().cpu().numpy(),
sampled_skin=res['skin_pred'].detach().cpu().numpy(),
parents=np.array(detokenize_output.parents),
joint_names=detokenize_output.joint_names,
joints=detokenize_output.joints,
)
from ..rig_package.parser.bpy import BpyParser
BpyParser.export_asset(asset, filepath=path)
def process_fn(self, batch: List[ModelInput]) -> List[Dict]:
res = []
max_length = 0
for b in batch:
if b.tokens is not None:
max_length = max(max_length, b.tokens.shape[0])
res = []
for b in batch:
if b.tokens is not None:
skeleton_tokens = np.pad(b.tokens, ((0, max_length-b.tokens.shape[0])), 'constant', constant_values=self.tokenizer.pad)
skeleton_mask = np.pad(np.ones_like(b.tokens), ((0, max_length-b.tokens.shape[0])), 'constant', constant_values=0)
else:
skeleton_tokens = None
skeleton_mask = None
_d = {
'vertices': torch.from_numpy(b.asset.sampled_vertices).float(),
'normals': torch.from_numpy(b.asset.sampled_normals).float(),
'non': {
'cls': b.asset.cls,
}
}
if skeleton_mask is not None:
_d.update({
'skeleton_tokens': skeleton_tokens,
'skeleton_mask': skeleton_mask,
})
_d['non'].update({
'parents': b.asset.parents,
'num_bones': b.asset.J,
})
if b.asset.sampled_vertex_groups is not None and 'skin' in b.asset.sampled_vertex_groups:
assert b.asset.meta is not None
_d['non'].update({
'cls': b.asset.cls,
'uniform_skin': torch.from_numpy(b.asset.sampled_vertex_groups['skin']).float(),
'skin_samples': b.asset.skin_samples,
'dense_indices': b.asset.meta['dense_indices'],
'dense_skin': torch.from_numpy(b.asset.meta['dense_skin']).float(),
'dense_vertices': torch.from_numpy(b.asset.meta['dense_vertices']).float(),
'dense_normals': torch.from_numpy(b.asset.meta['dense_normals']).float(),
})
res.append(_d)
return res
def predict_step(
self,
batch: Dict,
no_cls: bool=False,
skeleton_tokens=None,
parents=None,
num_joints=None,
make_asset: bool=False,
**kwargs
) -> Dict:
vertices: Tensor = batch['vertices']
normals : Tensor = batch['normals']
cls = batch['cls']
generate_kwargs = deepcopy(batch['generate_kwargs'])
if vertices.dim() == 2:
vertices = vertices.unsqueeze(0)
normals = normals.unsqueeze(0)
results = []
if skeleton_tokens is None:
skeleton_tokens = [None] * vertices.shape[0]
d = {}
for i in range(vertices.shape[0]):
res = self.generate(
vertices=vertices[i],
normals=normals[i],
skeleton_tokens=skeleton_tokens[i],
cls=None if no_cls else cls[i],
parents=None if parents is None else parents[i],
num_joints=None if num_joints is None else num_joints[i],
**generate_kwargs
)
if make_asset:
assert 'model_input' in batch, "need model_input to make asset (in validate/predict mode)"
assert res.detokenize_output is not None
assert res.skin_pred is not None
asset: Asset = batch['model_input'][i].asset.copy()
res.asset = Asset.from_data(
vertices=asset.vertices,
faces=asset.faces,
sampled_vertices=vertices[i].detach().float().cpu().numpy(),
sampled_skin=res.skin_pred.detach().float().cpu().numpy(),
joints=res.detokenize_output.joints,
parents=np.array(res.detokenize_output.parents),
cls=asset.cls,
path=asset.path,
)
results.append(res)
d['results'] = results
return d
def forward(self, batch: Dict) -> Dict[str, Tensor]:
return self.training_step(batch=batch)
def _check(x: Tensor, s, m=None):
assert isinstance(s, (list, tuple)), "Expected shape must be a list or tuple"
assert x.dim() == len(s), f"Expected {len(s)} dims, got {x.dim()}"
for i, (dim_actual, dim_expected) in enumerate(zip(x.shape, s)):
if dim_expected is not None and dim_expected != -1:
if m is None:
assert dim_actual == dim_expected, f"Shape mismatch at dim {i}: expected {dim_expected}, got {dim_actual}"
else:
assert dim_actual == dim_expected, f"Shape mismatch at dim {i}: expected {dim_expected}, got {dim_actual}. Message: {m}"
def encode_mesh_cond(mesh_encoder, output_proj, tokens_skin_cond, batch: Dict) -> Tensor:
vertices = batch['vertices'] # (B, N, 3)
normals = batch['normals'] # (B, N, 3)
assert isinstance(vertices, Tensor)
assert isinstance(normals, Tensor)
if (len(vertices.shape) == 3):
shape_embed, latents, token_num, pre_pc = mesh_encoder.encode_latents(pc=vertices, feats=normals) # type: ignore
else:
shape_embed, latents, token_num, pre_pc = mesh_encoder.encode_latents(pc=vertices.unsqueeze(0), feats=normals.unsqueeze(0)) # type: ignore
latents = output_proj(latents)
return latents
@torch.no_grad()
def encode(
tokenizer: Tokenizer,
vae: SkinVAEModel,
vae_input: VaeInput,
encode_repeat: int,
tokens_skin_cond: int,
tokens_per_skin: int,
) -> Tuple[Tensor, Tensor, Tensor]:
"""
Returns:
skin_tokens: (B, tokens_per_skin*J)
cond_latents: (B, tokens_skin_cond, vae.latent_channels)
skin_mask: (B, tokens_per_skin*J), 1 -> skin, 0 -> pad
"""
device = vae_input.uniform_cond.device
B = vae_input.B
J = vae_input.max_J
_, cond_latents, codes, _ = vae.encode(vae_input=vae_input, num_tokens=tokens_per_skin, full=True, encode_repeat=encode_repeat)
codes = codes[:, :tokens_per_skin]
indices = vae_input.get_flatten_indices()
skin_tokens = torch.full((B, J * tokens_per_skin), tokenizer.pad, dtype=torch.long, device=device)
skin_mask = torch.zeros_like(skin_tokens, dtype=torch.long)
j_counters = [0 for _ in range(B)]
for idx, batch_id in enumerate(indices):
j = j_counters[batch_id]
s = j * tokens_per_skin
t = s + tokens_per_skin
skin_tokens[batch_id, s:t] = codes[idx] + tokenizer.vocab_size
skin_mask[batch_id, s:t] = 1
j_counters[batch_id] += 1
assert cond_latents is not None
_check(cond_latents, (B, tokens_skin_cond, vae.latent_channels))
_check(skin_tokens, (B, J * tokens_per_skin))
_check(skin_mask, (B, J * tokens_per_skin))
return skin_tokens, cond_latents, skin_mask
def prepare_llm_tokens(
tokenizer: Tokenizer,
eos: int,
skeleton_tokens: Tensor,
skeleton_mask: Tensor,
skin_tokens: Tensor,
skin_mask: Tensor,
cond_latents: Tensor,
) -> Tuple[Tensor, Tensor, Tensor, Tensor]:
"""
Args:
skeleton_tokens: (B, n)
skeleton_mask: (B, n)
skin_tokens: (B, tokens_per_skin*J)
skin_mask: (B, tokens_per_skin*J)
cond_latents: (B, tokens_skin_cond, vae.latent_channels)
Returns:
llm_tokens: (B, seq_len)
attention_mask: (B, seq_len), 1 -> attend, 0 -> pad
"""
B = skeleton_tokens.shape[0]
inputs_ids = torch.ones((B, skeleton_tokens.shape[1] + skin_tokens.shape[1] + 1), dtype=torch.long, device=skeleton_tokens.device) * tokenizer.pad
num_skeleton = skeleton_mask.sum(dim=1)
num_skin = skin_mask.sum(dim=1)
attention_mask = torch.ones((B, inputs_ids.shape[1]), dtype=torch.float32, device=skeleton_tokens.device)
llm_skeleton_mask = torch.ones_like(attention_mask, dtype=torch.bool)
llm_skin_mask = torch.ones_like(attention_mask, dtype=torch.bool)
for i in range(B):
length = num_skeleton[i] + num_skin[i]
inputs_ids[i, :num_skeleton[i]] = skeleton_tokens[i, :num_skeleton[i]]
inputs_ids[i, num_skeleton[i]:num_skeleton[i]+num_skin[i]] = skin_tokens[i, :num_skin[i]]
inputs_ids[i, num_skeleton[i]+num_skin[i]] = eos # add an eos
attention_mask[i, length+1:] = 0.
llm_skeleton_mask[i, num_skeleton[i]:] = 0
llm_skin_mask[i, :num_skeleton[i]] = 0
llm_skin_mask[i, length+1:] = 0
seq_len = inputs_ids.shape[1]
_check(inputs_ids, (B, seq_len))
_check(attention_mask, (B, seq_len))
return inputs_ids, attention_mask, llm_skeleton_mask, llm_skin_mask
def get_logits_processor(tokenizer: Tokenizer, eos: int, tokens_per_skin: int, start_tokens):
processor = VocabSwitchingLogitsProcessor(
tokenizer=tokenizer,
switch_token_id=tokenizer.eos,
eos_token_id=eos,
tokens_per_skin=tokens_per_skin,
init=start_tokens,
)
return LogitsProcessorList([processor])
@torch.no_grad()
def decode(
cond: Tensor,
cond_latents: Tensor,
inputs_ids: Tensor,
tokenizer: Tokenizer,
tokens_per_skin: int,
vae: SkinVAEModel,
encode_repeat: int=1,
) -> Dict:
"""
inputs_ids: (seq_len)
cond: (N, c)
cond_latents: (tokens_skin_cond, dim)
"""
assert cond.dim() == 2, 'do not support batch'
assert cond_latents.dim() == 2, 'do not support batch'
where_eos = torch.where(inputs_ids == tokenizer.eos)
if where_eos[0].shape[0] == 0:
raise ValueError("No EOS token found in inputs_ids")
where_eos = where_eos[0][:1]
skeleton_tokens = inputs_ids[:where_eos+1]
skeleton_tokens = np.array(skeleton_tokens.detach().cpu().numpy())
detokenize_output = tokenizer.detokenize(ids=skeleton_tokens)
J = detokenize_output.joints.shape[0]
skin_tokens = inputs_ids[where_eos+1:where_eos+1+J*tokens_per_skin]
if skin_tokens.shape != (J*(tokens_per_skin),):
return {
'skin_pred': None,
'detokenize_output': detokenize_output,
}
cond = cond.unsqueeze(0)
cond_latents = cond_latents.unsqueeze(0)
skin = []
g = tokens_per_skin * encode_repeat
for s in range(0, J*tokens_per_skin, g):
t = min(s+g, J*tokens_per_skin)
indices = skin_tokens[s:t].unsqueeze(0) - tokenizer.vocab_size
# expect: (b, tokens_per_skin, dim)
b = (t-s)//tokens_per_skin
z = vae.model.FSQ.indices_to_codes(indices).reshape(b, tokens_per_skin, -1)
# (b, n, 1)
logits = vae.decode(z=z, sampled_cond=cond.repeat(b, 1, 1), cond_tokens=cond_latents.repeat(b, 1, 1))
skin_pred = logits.reshape(b, logits.shape[1]).permute(1, 0)
skin.append(skin_pred)
skin = torch.concat(skin, dim=1).float()
return {
'skin_pred': skin,
'detokenize_output': detokenize_output,
}
@torch.no_grad()
def decode_multi(
cond: Tensor,
cond_latents: Tensor,
inputs_ids: List[Tensor],
tokenizer: Tokenizer,
tokens_per_skin: int,
vae: SkinVAEModel,
is_numpy: bool=True,
encode_repeat: int=1,
) -> List[Dict]:
"""
inputs_ids: List[(seq_len)]
cond: (N, c)
cond_latents: (tokens_skin_cond, dim)
"""
assert cond.dim() == 2, 'do not support batch'
assert cond_latents.dim() == 2, 'do not support batch'
B = len(inputs_ids)
res = [{'skin_pred': None, 'detokenize_output': None} for _ in range(B)]
device = cond.device
batch_mapping = []
skin_tokens_list = []
oks = []
oks_J = []
for i in range(B):
where_eos = torch.where(inputs_ids[i] == tokenizer.eos)
if where_eos[0].shape[0] == 0:
print(f"decode_multi: {i} has bad skeleton")
continue
where_eos = where_eos[0][:1]
skeleton_tokens = inputs_ids[i][:where_eos+1]
skeleton_tokens = np.array(skeleton_tokens.detach().cpu().numpy())
try:
detokenize_output = tokenizer.detokenize(ids=skeleton_tokens)
except Exception as e:
print(f"decode_multi: error while decoding skeleton: {str(e)}")
continue
J = detokenize_output.joints.shape[0]
res[i]['detokenize_output'] = detokenize_output # type: ignore
skin_tokens = inputs_ids[i][where_eos+1:where_eos+1+J*tokens_per_skin]
if skin_tokens.shape != (J*(tokens_per_skin),):
print(f"decode_multi: {i} has bad skin")
continue
batch_mapping.append(torch.full((J,), i, device=device, dtype=torch.long))
skin_tokens_list.append(skin_tokens)
oks.append(i)
oks_J.append(J)
if len(batch_mapping) == 0:
return res
batch_mapping = torch.cat(batch_mapping, dim=0)
# (1, sum_J*tokens_per_skin)
skin_tokens = torch.cat(skin_tokens_list, dim=0).unsqueeze(0)
cond = cond.unsqueeze(0)
cond_latents = cond_latents.unsqueeze(0)
skin_list = []
g = tokens_per_skin * encode_repeat
sum_J = batch_mapping.shape[0]
for s in range(0, sum_J*tokens_per_skin, g):
t = min(s+g, sum_J*tokens_per_skin)
# (1, m*tokens_per_skin)
indices = skin_tokens[:, s:t] - tokenizer.vocab_size
# expect: (m, tokens_per_skin, dim)
m = (t-s)//tokens_per_skin
z = vae.model.FSQ.indices_to_codes(indices).reshape(m, tokens_per_skin, -1)
# (m, n, 1)
logits = vae.decode(z=z, sampled_cond=cond.repeat(m, 1, 1), cond_tokens=cond_latents.repeat(m, 1, 1))
skin_pred = logits.reshape(m, logits.shape[1]).permute(1, 0)
skin_list.append(skin_pred)
skin = torch.concat(skin_list, dim=1).float()
for (i, id) in enumerate(oks):
skin_pred = skin[:, batch_mapping==id].reshape(-1, oks_J[i])
res[id]['skin_pred'] = skin_pred.detach().cpu().numpy() if is_numpy else skin_pred
return res

118
thirdparty/skintokens/src/model/utils.py vendored Normal file
View file

@ -0,0 +1,118 @@
import torch
def fps(
x: torch.Tensor,
batch: torch.Tensor,
ratio: float,
random_start: bool = False,
) -> torch.Tensor:
"""
Args:
x: (N, C) points.
batch: (N,) batch indices for each point.
ratio: sampling ratio in (0, 1].
random_start: whether to start from a random point per batch.
Returns:
1D tensor of sampled indices in the flattened input space.
"""
if x.ndim != 2:
raise ValueError(f"Expected x to have shape (N, C), got {tuple(x.shape)}")
if batch.ndim != 1 or batch.shape[0] != x.shape[0]:
raise ValueError("batch must be 1D and aligned with x")
if not (0 < ratio <= 1.0):
raise ValueError(f"ratio must be in (0, 1], got {ratio}")
sampled_indices = []
unique_batches = torch.unique(batch)
for batch_id in unique_batches:
mask = batch == batch_id
points = x[mask]
num_points = points.shape[0]
if num_points == 0:
continue
num_samples = max(1, int(round(num_points * ratio)))
num_samples = min(num_samples, num_points)
if random_start:
farthest = torch.randint(num_points, (1,), device=x.device).item()
else:
farthest = 0
distances = torch.full((num_points,), float("inf"), device=x.device)
selected_local = torch.empty(num_samples, dtype=torch.long, device=x.device)
for i in range(num_samples):
selected_local[i] = farthest
centroid = points[farthest]
dist = torch.sum((points - centroid) ** 2, dim=-1)
distances = torch.minimum(distances, dist)
farthest = torch.argmax(distances).item()
global_indices = torch.nonzero(mask, as_tuple=False).squeeze(-1)[selected_local]
sampled_indices.append(global_indices)
if not sampled_indices:
return torch.empty((0,), dtype=torch.long, device=x.device)
return torch.cat(sampled_indices, dim=0)
def segment_csr(
src: torch.Tensor,
indptr: torch.Tensor,
reduce: str = "sum",
) -> torch.Tensor:
"""
Args:
src: source tensor with shape (N, ...).
indptr: CSR index pointer with shape (S + 1,).
reduce: one of {"sum", "mean", "min", "max"}.
Returns:
Reduced tensor with shape (S, ...).
"""
if src.ndim < 1:
raise ValueError(f"Expected src to have at least 1 dim, got {src.ndim}")
if indptr.ndim != 1:
raise ValueError(f"Expected indptr to be 1D, got shape {tuple(indptr.shape)}")
if indptr.numel() < 1:
raise ValueError("indptr must contain at least one element")
if reduce not in {"sum", "mean", "min", "max"}:
raise ValueError(f"Unsupported reduce mode: {reduce}")
indptr = indptr.to(device=src.device, dtype=torch.long)
segments = indptr.numel() - 1
out_shape = (segments, *src.shape[1:])
if reduce in {"sum", "mean"}:
out = torch.zeros(out_shape, dtype=src.dtype, device=src.device)
elif reduce == "min":
out = torch.full(out_shape, float("inf"), dtype=src.dtype, device=src.device)
else:
out = torch.full(out_shape, float("-inf"), dtype=src.dtype, device=src.device)
for i in range(segments):
start = indptr[i].item()
end = indptr[i + 1].item()
if end <= start:
continue
chunk = src[start:end]
if reduce == "sum":
out[i] = chunk.sum(dim=0)
elif reduce == "mean":
out[i] = chunk.mean(dim=0)
elif reduce == "min":
out[i] = chunk.min(dim=0).values
else:
out[i] = chunk.max(dim=0).values
if reduce == "min":
out = torch.where(torch.isinf(out), torch.zeros_like(out), out)
elif reduce == "max":
out = torch.where(torch.isinf(out), torch.zeros_like(out), out)
return out

View file

View file

View file

@ -0,0 +1,779 @@
from dataclasses import dataclass, field
from numpy import ndarray
from scipy.spatial import cKDTree # type: ignore
from typing import Dict, List, Optional, Tuple
import numpy as np
import os
import trimesh
from ..utils import assert_list, assert_ndarray, linear_blend_skinning, sample_vertex_groups
from .voxel import Voxel
@dataclass
class Asset():
# vertices of merged mesh in edit space, shape (N, 3)
vertices: Optional[ndarray]=None
# faces of merged mesh, shape (F, 3)
faces: Optional[ndarray]=None
# vertex normals of merged mesh in edit space, shape (N, 3), calculated by trimesh
vertex_normals: Optional[ndarray]=None
# face normals of merged mesh in edit space, shape (F, 3), calculated by trimesh
face_normals: Optional[ndarray]=None
# offset of vertices in each part, shape (P,),
# vertices[vertex_bias[i-1]:vertex_bias[i]] are in the same part (vertex_bias[-1]=0)
vertex_bias: Optional[ndarray]=None
# offset of faces in each part, shape (P,),
# faces[face_bias[i-1]:face_bias[i]] are in the same part (face_bias[-1]=0)
face_bias: Optional[ndarray]=None
# name of each mesh part, shape (P,)
mesh_names: Optional[List[str]]=None
# name of each joint, shape (J,)
joint_names: Optional[List[str]]=None
# parent index of each joint, shape (J,), -1 for root
parents: Optional[ndarray]=None
# length of each bone indicating euclidean distance between head and tail(which is proposed in blender), shape (J,)
lengths: Optional[ndarray]=None
# matrix to convert from edit space(or motion space) to world space, shape (4, 4)
matrix_world: Optional[ndarray]=None
# local matrix of each joint, shape (J, 4, 4)
matrix_local: Optional[ndarray]=None
# matrix to convert from edit space to motion space, shape (frames, J, 4, 4)
matrix_basis: Optional[ndarray]=None
# name of the armature
armature_name: Optional[str]=None
# skinning weights, shape (N, J)
skin: Optional[ndarray]=None
###########################################################################
cls: Optional[str]=None
path: Optional[str]=None
vertex_groups: Dict[str, ndarray]=field(default_factory=dict)
sampled_vertices: Optional[ndarray]=None
sampled_normals: Optional[ndarray]=None
sampled_vertex_groups: Optional[Dict[str, ndarray]]=None
skin_samples: Optional[int]=None
meta: Optional[Dict]=None
@property
def dirname(self) -> str:
"""return directory name of the asset"""
if self.path is None:
return ""
return os.path.dirname(self.path)
@property
def N(self) -> int:
"""return number of vertices"""
if self.vertices is None:
return 0
return self.vertices.shape[0]
@property
def F(self) -> int:
"""return number of faces"""
if self.faces is None:
return 0
return self.faces.shape[0]
@property
def J(self) -> int:
"""return number of joints"""
if self.parents is None:
return 0
return self.parents.shape[0]
@property
def P(self) -> int:
"""return number of mesh parts"""
self._build_bias()
if self.vertex_bias is None:
return 0
return self.vertex_bias.shape[0]
@property
def root(self) -> int:
"""return the index of root joint"""
if self.parents is None:
return -1
for i, p in enumerate(self.parents):
if p == -1:
return i
raise ValueError("no root found")
@property
def joints(self) -> ndarray|None:
"""return joints in edit space, shape (J, 3)"""
if self.matrix_local is None:
return None
return self.matrix_local[:, :3, 3]
@property
def skeleton(self) -> ndarray|None:
"""return skeleton where joint is followed by parent, shape (J-1, 6), ignore root"""
if self.joints is None or self.parents is None:
return None
indices = np.linspace(0, self.J-1, num=self.J, dtype=int)[self.parents!=-1]
return np.concatenate([self.joints[indices], self.joints[self.parents[indices]]], axis=1)
@property
def dfs_order(self) -> List[int]:
"""return the dfs order of joints"""
if self.parents is None:
return []
sons = [[] for _ in range(self.J)]
stack = []
for i, p in enumerate(self.parents):
if p == -1:
stack.append(i)
continue
sons[p].append(i)
order = []
while len(stack) > 0:
u = stack.pop()
order.append(u)
for s in reversed(sons[u]):
stack.append(s)
return order
@property
def tails(self) -> ndarray|None:
"""
Return tails in edit space, shape (J, 3). The bone is extrueded along local Y axis, in accordance with Blender.
"""
joints = self.joints
matrix_local = self.matrix_local
if joints is None or self.lengths is None or matrix_local is None:
return None
x = np.array([0.0, 1.0, 0.0])
x = self.lengths * x[:, np.newaxis]
y = np.zeros((self.J, 3))
for i in range(self.J):
y[i] = matrix_local[i, :3, :3] @ x[:, i]
return joints + y
def _build_bias(self):
if self.vertex_bias is None and self.vertices is not None:
self.vertex_bias = np.array([self.vertices.shape[0]])
if self.face_bias is None and self.faces is not None:
self.face_bias = np.array([self.faces.shape[0]])
def get_vertex_slice(self, index: int) -> slice:
"""return slice of vertices of a specific part"""
self._build_bias()
if self.vertex_bias is None:
return slice(0, 0)
if index == 0:
return slice(0, self.vertex_bias[0])
return slice(self.vertex_bias[index-1], self.vertex_bias[index])
def get_face_slice(self, index: int) -> slice:
"""return slice of faces of a specific part"""
self._build_bias()
if self.face_bias is None:
return slice(0, 0)
if index == 0:
return slice(0, self.face_bias[index])
return slice(self.face_bias[index-1], self.face_bias[index])
def names_to_ids(self, arr: List[int|str]) -> List[int]:
for s in arr:
if isinstance(s, str) and (self.joint_names is None or s not in self.joint_names):
raise ValueError(f"do not find {s} in joint_names")
elif not isinstance(s, int) and not isinstance(s, str):
raise ValueError(f"element must be int or str")
if self.joint_names is not None:
_name_to_id = {s: i for (i, s) in enumerate(self.joint_names)}
else:
_name_to_id = {}
return [_name_to_id[s] if isinstance(s, str) else s for s in arr]
def set_order(
self,
new_orders: List[int|str],
merge_skin: bool=True,
do_not_normalize: bool=False
):
"""
Rearrange the order of the joints.
Args:
new_orders: A list of int or bone names to indicate orders.
For example, if the first element is 2, then the rearranged
joint will be the second first joint in the current skeleton.
merge_skin: If True, if some joints are merged, skin will be
added to its nearest ancestor. Otherwise completely removes
skin and finally normalized.
do_not_normalize: Do not normalize skin.
"""
if len(np.unique(new_orders)) != len(new_orders):
raise ValueError("multiple values found in new_orders")
_new_orders = self.names_to_ids(arr=new_orders)
ancestors = []
grandsons = []
beyond_root = []
root_id = 0
if self.parents is not None:
new_positions = [0 for i in range(self.J)]
new_parents = [-1 for i in range(self.J)]
for i, x in enumerate(_new_orders):
new_positions[x] = i
set_new_orders = set(_new_orders)
roots = 0
for i in self.dfs_order:
if i not in set_new_orders:
if self.parents[i] == -1:
new_positions[i] = -1
beyond_root.append(i)
else:
new_positions[i] = new_positions[self.parents[i]]
if new_positions[i] == -1:
beyond_root.append(i)
else:
ancestors.append(new_positions[i])
grandsons.append(i)
else:
if self.parents[i] == -1:
new_parents[i] = -1
else:
new_parents[i] = new_positions[self.parents[i]]
if new_parents[i] == -1:
roots += 1
root_id = new_positions[i]
if roots >= 2:
raise ValueError(f"multiple roots found: {self.path} {self.parents} {new_orders}")
self.parents = np.array(new_parents)[_new_orders]
if self.joint_names is not None:
_joint_names = [self.joint_names[u] for u in _new_orders]
self.joint_names = _joint_names
if self.lengths is not None:
self.lengths = self.lengths[_new_orders]
if self.matrix_local is not None:
self.matrix_local = self.matrix_local[_new_orders]
if self.matrix_basis is not None:
self.matrix_basis = self.matrix_basis[:, _new_orders]
if self.skin is not None:
if merge_skin:
skin = self.skin.copy()
self.skin = skin[:, _new_orders]
for x, y in zip(ancestors, grandsons):
self.skin[:, x] += skin[:, y]
self.skin[:, root_id] += skin[:, beyond_root].sum(axis=1)
else:
self.skin = self.skin[:, _new_orders]
if not do_not_normalize:
self.normalize_skin()
def delete_joints(self, joints_to_remove: List[int|str]):
"""
Delete joints and their corresponding values.
"""
_joints_to_remove = set(self.names_to_ids(arr=joints_to_remove))
new_orders: List[int|str] = [i for i in range(self.J) if i not in _joints_to_remove]
self.set_order(new_orders=new_orders)
def delete_vertices(self, vertices_to_remove: List[int]|ndarray):
"""
Delete vertices and their corresponding values.
"""
if self.vertices is None:
return
if isinstance(vertices_to_remove, list):
vertices_to_remove = np.array(vertices_to_remove)
mask = np.ones(self.N, dtype=bool)
mask[vertices_to_remove] = False
indices = np.where(mask)[0]
# handle vertex bias
if self.vertex_bias is not None:
cumsum_mask = np.cumsum(mask)
self.vertex_bias = cumsum_mask[self.vertex_bias-1]
N = self.N
self.vertices = self.vertices[indices]
if self.vertex_normals is not None:
self.vertex_normals = self.vertex_normals[indices]
if self.skin is not None:
self.skin = self.skin[indices, :]
if self.faces is not None: # keep faces
face_mask = np.all(np.isin(self.faces, indices), axis=1)
self.faces = self.faces[face_mask]
old_to_new = np.zeros(N, dtype=np.int32)
old_to_new[indices] = np.arange(len(indices))
self.faces = old_to_new[self.faces]
if self.face_normals is not None:
self.face_normals = self.face_normals[indices]
# handle face bias
if self.face_bias is not None:
cumsum_face_mask = np.cumsum(face_mask)
self.face_bias = cumsum_face_mask[self.face_bias-1]
self._build_bias()
def normalize_skin(self) -> 'Asset':
"""
Normalize skin so that add up to 1.
"""
if self.skin is None:
return self
self.skin = self.skin / np.maximum(np.sum(self.skin, axis=1, keepdims=True), 1e-8)
return self
def build_normals(self):
"""
Build vertex_normals and face_normals using trimesh.
"""
if self.vertices is None:
raise ValueError("do not have vertices")
if self.faces is None:
raise ValueError("do not have faces")
mesh = trimesh.Trimesh(vertices=self.vertices, faces=self.faces, process=False, maintain_order=True)
self.vertex_normals = mesh.vertex_normals.copy()
self.face_normals = mesh.face_normals.copy()
def normalize_vertices(
self,
range: Optional[Tuple[float, float]]=None,
range_x: Optional[Tuple[float, float]]=None,
range_y: Optional[Tuple[float, float]]=None,
range_z: Optional[Tuple[float, float]]=None,
):
"""
Normalize vertices into cube in edit space. If range_x/y/z is provided,
use range_x/y/z, otherwise use range by default.
"""
if self.vertices is None:
return
if range is None:
if range_x is None:
raise ValueError("range_x is None, but range is missing")
if range_y is None:
raise ValueError("range_y is None, but range is missing")
if range_z is None:
raise ValueError("range_z is None, but range is missing")
_range_x = range_x
_range_y = range_y
_range_z = range_z
else:
_range_x = range if range_x is None else range_x
_range_y = range if range_y is None else range_y
_range_z = range if range_z is None else range_z
v_min = self.vertices.min(axis=0)
v_max = self.vertices.max(axis=0)
scale_range = (v_max - v_min).max()
# normalize into [0, 1]^3
v = (self.vertices - v_min) / scale_range
mid_point = (v.min(axis=0) + v.max(axis=0)) / 2
bias = np.array([0.5, 0.5, 0.5]) - mid_point
v += bias
dx = (_range_x[1] - _range_x[0])
dy = (_range_y[1] - _range_y[0])
dz = (_range_z[1] - _range_z[0])
if self.faces is not None and np.abs(dx-dy) > 1e-3 or np.abs(dy-dz) > 1e-3 or np.abs(dy-dz) > 1e-3:
raise ValueError("do not support non-uniform normalization")
v[:, 0] = v[:, 0] * dx + _range_x[0]
v[:, 1] = v[:, 1] * dy + _range_y[0]
v[:, 2] = v[:, 2] * dz + _range_z[0]
self.vertices = v
if self.matrix_local is not None:
jv = (self.matrix_local[:, :3, 3] - v_min) / scale_range + bias
self.matrix_local[:, 0, 3] = jv[:, 0] * dx + _range_x[0]
self.matrix_local[:, 1, 3] = jv[:, 1] * dy + _range_y[0]
self.matrix_local[:, 2, 3] = jv[:, 2] * dz + _range_z[0]
def get_matrix(
self,
matrix_basis: ndarray,
) -> ndarray:
"""
Get pose matrix in motion space using forward kinetics.
"""
J = self.J
parents = self.parents
if parents is None:
raise ValueError("do not have parents")
if self.matrix_local is None:
raise ValueError("do not have matrix_local")
assert_ndarray(matrix_basis, "matrix_basis", (J, 4, 4))
matrix = np.zeros((J, 4, 4))
for i in self.dfs_order:
pid = parents[i]
if pid==-1:
matrix[i] = self.matrix_local[i] @ matrix_basis[i]
else:
matrix_parent = matrix[pid]
matrix_local_parent = self.matrix_local[pid]
matrix[i] = (
matrix_parent @
(np.linalg.inv(matrix_local_parent) @ self.matrix_local[i]) @
matrix_basis[i]
)
return matrix
def vertices_with_pose(
self,
matrix_basis: ndarray,
inplace: bool=True,
) -> ndarray:
"""
Apply pose to vertices and return the deformed vertices.
Args:
inplace: if True, change vertices and all motion related fileds of the asset.
"""
if self.vertices is None:
raise ValueError("do not have vertices")
if self.matrix_local is None:
raise ValueError("do not have matrix_local")
if self.joints is None:
raise ValueError("do not have joints")
if self.skin is None:
raise ValueError("do not have skin")
matrix = self.get_matrix(matrix_basis=matrix_basis)
vertices = linear_blend_skinning(
vertices=self.vertices,
matrix_local=self.matrix_local,
matrix=matrix,
skin=self.skin,
pad=1,
value=1.0,
)
if inplace:
self.vertices = vertices
if self.faces is not None:
self.build_normals()
self.matrix_local = matrix
return vertices
def transform(self, trans: ndarray):
"""trans: 4x4 affine matrix"""
def _apply(v: ndarray, trans: ndarray) -> ndarray:
return np.matmul(v, trans[:3, :3].transpose()) + trans[:3, 3]
if self.vertices is not None:
self.vertices = _apply(self.vertices, trans)
if self.matrix_local is not None:
self.matrix_local = trans @ self.matrix_local
self.build_normals()
def trim_skeleton(self):
"""remove all leaf bones and coordinate bones"""
if self.skin is None:
return
if self.parents is None:
return
has_skin = self.skin.sum(axis=0) > 1e-6
if not np.any(has_skin):
return
sons = [[] for _ in range(self.J)]
good_sons = [[] for _ in range(self.J)]
sub_tree_has_skin = [False for _ in range(self.J)]
dfs_order = self.dfs_order
for u in dfs_order:
p = self.parents[u]
if p != -1:
sons[p].append(u)
for u in reversed(dfs_order):
p = self.parents[u]
if has_skin[u]:
sub_tree_has_skin[u] = True
else:
for v in sons[u]:
if sub_tree_has_skin[v]:
sub_tree_has_skin[u] = True
break
keep = [False for _ in range(self.J)]
for u in dfs_order:
for v in sons[u]:
if sub_tree_has_skin[v]:
good_sons[u].append(v)
if has_skin[u]:
keep[u] = True
else:
p = self.parents[u]
if len(good_sons[u]) >= 2:
keep[u] = True
elif len(good_sons[u]) == 1 and p != -1:
if len(good_sons[p]) >= 2:
keep[u] = True
elif len(good_sons[p]) == 1 and good_sons[p][0] != u:
keep[u] = True
joints_to_remove: List[int|str] = [i for i in range(self.J) if not keep[i]]
self.delete_joints(joints_to_remove=joints_to_remove)
def check_field(self):
def _check_array(arr, name, shape, dtype=None):
if arr is not None:
assert_ndarray(arr, name=name, shape=shape, dtype=dtype)
def _check_list(arr, name, dtype=None):
if arr is not None:
assert_list(arr, name=name, dtype=dtype)
_check_array(self.vertices, name="vertices", shape=(self.N, 3))
_check_array(self.faces, name="faces", shape=(self.F, 3))
_check_array(self.vertex_normals, name="vertex_normals", shape=(self.N, 3))
_check_array(self.face_normals, name="face_normals", shape=(self.F, 3))
_check_array(self.vertex_bias, name="vertex_bias", shape=(self.P,), dtype=np.integer)
_check_array(self.face_bias, name="face_bias", shape=(self.P,), dtype=np.integer)
_check_list(self.mesh_names, name="mesh_names", dtype=str)
_check_list(self.joint_names, name="joint_names", dtype=str)
_check_array(self.parents, name="parents", shape=(-1,), dtype=np.integer)
_check_array(self.lengths, name="lengths", shape=(-1,))
_check_array(self.matrix_world, name="matrix_world", shape=(4, 4))
_check_array(self.matrix_local, name="matrix_local", shape=(self.J, 4, 4))
_check_array(self.matrix_basis, name="matrix_basis", shape=(self.F, self.J, 4, 4))
if self.armature_name is not None:
if not isinstance(self.armature_name, str):
raise ValueError(f"armature_name should be str")
_check_array(self.skin, name="skin", shape=(self.N, self.J))
if self.vertices is not None and self.vertex_normals is not None:
if self.vertices.shape[0] != self.vertex_normals.shape[0]:
raise ValueError(f"shapes of vertices and vertex_normals do not match: {self.vertices.shape} and {self.vertex_normals.shape}")
if self.faces is not None and self.face_normals is not None:
if self.faces.shape[0] != self.face_normals.shape[0]:
raise ValueError(f"shapes of faces and face_normals do not match: {self.faces.shape} and {self.face_normals.shape}")
if self.vertex_bias is not None:
if self.vertices is None:
raise ValueError("have vertex_bias, but do not have vertices")
if self.vertex_bias[-1] != self.N:
raise ValueError(f"vertex_bias must end with number of vertices {self.N}")
if self.face_bias is not None:
if self.faces is None:
raise ValueError("have face_bias, but do not have faces")
if self.face_bias[-1] != self.F:
raise ValueError(f"vertex_bias must end with number of vertices {self.N}")
if self.matrix_local is not None and self.matrix_basis is not None:
if self.matrix_local.shape[0] != self.matrix_basis.shape[1]:
raise ValueError(f"number of joints do not match in matix_local and matrix_basis: {self.matrix_local.shape[0]} and {self.matrix_basis.shape[1]}")
if self.joint_names is not None and self.matrix_local is not None:
if len(self.joint_names) != self.matrix_local.shape[0]:
raise ValueError(f"number of joints do not match in joint_names and matrix_local: {len(self.joint_names)} and {self.matrix_local.shape[0]}")
if self.skin is not None and self.matrix_local is not None:
if self.skin.shape[1] != self.matrix_local.shape[0]:
raise ValueError(f"number of joints do not match in skin and matrix_local: {self.skin.shape[0]} and {self.matrix_local.shape[0]}")
if self.parents is not None:
if (self.parents==-1).sum() != 1:
raise ValueError(f"no root or multiple roots found, count: {(self.parents==-1).sum()}")
def voxel(self, resolution: int=128, voxel_size: Optional[float]=None) -> Voxel:
"""
Return a voxel created from mesh.
Args:
resolution: Maximum number of cubes along one axis.
voxel_size: Forcibly asign length of the cube with this value.
"""
import open3d as o3d
if self.vertices is None:
raise ValueError("do not have vertices")
if self.faces is None:
raise ValueError("do not have faces")
if voxel_size is None:
max_d = (self.vertices.max(axis=1) - self.vertices.min(axis=1)).max()
v = max_d / resolution
else:
v = voxel_size
mesh_o3d = o3d.geometry.TriangleMesh()
mesh_o3d.vertices = o3d.utility.Vector3dVector(self.vertices.copy())
mesh_o3d.triangles = o3d.utility.Vector3iVector(self.faces)
voxel = o3d.geometry.VoxelGrid.create_from_triangle_mesh(mesh_o3d, voxel_size=v)
coords = np.array([pt.grid_index for pt in voxel.get_voxels()])
return Voxel(
origin=voxel.origin,
voxel_size=v,
coords=coords,
)
def sample_pc(
self,
num_samples: int,
num_vertex_samples: Optional[int]=None,
face_mask: Optional[ndarray]=None,
shuffle: bool=True,
) -> 'Asset':
"""
Return a asset where vertices, normals and skin are sampled.
"""
if self.vertices is None:
raise ValueError("do not have vertices")
if self.faces is None:
raise ValueError("do not have faces")
if self.vertex_normals is None or self.face_normals is None:
self.build_normals()
if face_mask is not None:
assert_ndarray(arr=face_mask, name="face_mask", shape=(self.F,))
sampled_vertices, sampled_normals, sampled_vertex_groups = sample_vertex_groups(
vertices=self.vertices,
faces=self.faces,
num_samples=num_samples,
num_vertex_samples=num_vertex_samples,
vertex_normals=self.vertex_normals,
face_normals=self.face_normals,
vertex_groups=self.skin,
face_mask=face_mask,
shuffle=shuffle,
same=True,
)
asset = self.copy()
asset.vertices = sampled_vertices[:, 0]
asset.vertex_normals = sampled_normals[:, 0] # type: ignore
asset.skin = sampled_vertex_groups
asset.vertex_bias = None
asset.faces = None
asset.face_bias = None
asset.face_normals = None
asset._build_bias()
return asset
def copy(self) -> 'Asset':
def _copy(x):
if isinstance(x, ndarray):
return x.copy()
elif isinstance(x, list):
return x.copy()
elif isinstance(x, str):
return x
else:
return None
return Asset(
vertices=_copy(self.vertices),
faces=_copy(self.faces),
vertex_normals=_copy(self.vertex_normals), # type: ignore
face_normals=_copy(self.face_normals),
vertex_bias=_copy(self.vertex_bias),
face_bias=_copy(self.face_bias),
mesh_names=_copy(self.mesh_names),
joint_names=_copy(self.joint_names),
parents=_copy(self.parents),
lengths=_copy(self.lengths),
matrix_world=_copy(self.matrix_world),
matrix_local=_copy(self.matrix_local),
matrix_basis=_copy(self.matrix_basis),
armature_name=_copy(self.armature_name), # type: ignore
skin=_copy(self.skin),
cls=_copy(self.cls), # type: ignore
path=_copy(self.path), # type: ignore
)
def change_dtype(self, float_dtype=np.float32, int_dtype=np.int32) -> 'Asset':
"""change dtype"""
def convert(arr):
if arr is None:
return None
if np.issubdtype(arr.dtype, np.floating):
return arr.astype(float_dtype)
elif np.issubdtype(arr.dtype, np.integer):
return arr.astype(int_dtype)
else:
return arr
self.vertices = convert(self.vertices)
self.faces = convert(self.faces)
self.vertex_normals = convert(self.vertex_normals)
self.face_normals = convert(self.face_normals)
self.vertex_bias = convert(self.vertex_bias)
self.face_bias = convert(self.face_bias)
self.parents = convert(self.parents)
self.lengths = convert(self.lengths)
self.matrix_world = convert(self.matrix_world)
self.matrix_local = convert(self.matrix_local)
self.matrix_basis = convert(self.matrix_basis)
self.skin = convert(self.skin)
return self
@classmethod
def from_data(
c,
vertices: Optional[ndarray]=None,
faces: Optional[ndarray]=None,
vertex_normals: Optional[ndarray]=None,
face_normals: Optional[ndarray]=None,
vertex_bias: Optional[ndarray]=None,
face_bias: Optional[ndarray]=None,
mesh_names: Optional[List[str]]=None,
joint_names: Optional[List[str]]=None,
parents: Optional[ndarray]=None,
lengths: Optional[ndarray]=None,
matrix_world: Optional[ndarray]=None,
matrix_local: Optional[ndarray]=None,
matrix_basis: Optional[ndarray]=None,
armature_name: Optional[str]=None,
skin: Optional[ndarray]=None,
joints: Optional[ndarray]=None,
sampled_vertices: Optional[ndarray]=None,
sampled_skin: Optional[ndarray]=None,
cls: Optional[str]=None,
path: Optional[str]=None,
) -> 'Asset':
"""
Return an asset with as many fields as possible.
"""
if matrix_local is None and joints is not None:
J = joints.shape[0]
matrix_local = np.zeros((J, 4, 4), dtype=np.float32)
matrix_local[...] = np.eye(4)
matrix_local[:, :3, 3] = joints
if joint_names is None and matrix_local is not None:
joints_names = [f"bone_{i}" for i in range(matrix_local.shape[0])]
if sampled_vertices is not None and vertices is not None and sampled_skin is not None:
tree = cKDTree(sampled_vertices)
k = min(8, sampled_vertices.shape[0])
distances, indices = tree.query(vertices, k=k)
if k == 1:
skin = sampled_skin[indices]
else:
# smooth interpolation with inverse-distance weights
weights = 1.0 / (distances + 1e-8)
weights = weights / np.sum(weights, axis=1, keepdims=True)
skin = np.einsum("nk,nkj->nj", weights, sampled_skin[indices])
asset = Asset(
vertices=vertices,
faces=faces,
vertex_normals=vertex_normals,
face_normals=face_normals,
vertex_bias=vertex_bias,
face_bias=face_bias,
mesh_names=mesh_names,
joint_names=joint_names,
parents=parents,
lengths=lengths,
matrix_world=matrix_world,
matrix_local=matrix_local,
matrix_basis=matrix_basis,
armature_name=armature_name,
skin=skin,
cls=cls,
path=path,
)
asset.check_field()
return asset

View file

@ -0,0 +1,88 @@
from dataclasses import dataclass
from numpy import ndarray
from typing import Optional
import numpy as np
@dataclass
class Voxel():
# coordinates of mesh
coords: ndarray
# origin of the voxel
origin: ndarray
# grid size
voxel_size: float
# a boolen array
_voxel: Optional[ndarray]=None
@property
def voxel(self) -> ndarray:
if self._voxel is None:
max_coords = np.max(self.coords, axis=0)
shape = tuple(max_coords + 1)
voxel = np.zeros(shape, dtype=bool)
voxel[tuple(self.coords.T)] = True
self._voxel = voxel
return self._voxel
@property
def pc(self) -> ndarray:
return self.origin + (self.coords + 0.5) * self.voxel_size
def projection_fill(self, rigid: bool=True):
"""
Fill up holes in the voxel.
"""
grids = np.indices(self.voxel.shape)
x_coord = grids[0, ...]
y_coord = grids[1, ...]
z_coord = grids[2, ...]
INF = 2147483647
x_tmp = x_coord.copy()
x_tmp[~self.voxel] = INF
x_min = x_tmp.min(axis=0)
x_tmp[~self.voxel] = -1
x_max = x_tmp.max(axis=0)
y_tmp = y_coord.copy()
y_tmp[~self.voxel] = INF
y_min = y_tmp.min(axis=1)
y_tmp[~self.voxel] = -1
y_max = y_tmp.max(axis=1)
z_tmp = z_coord.copy()
z_tmp[~self.voxel] = INF
z_min = z_tmp.min(axis=2)
z_tmp[~self.voxel] = -1
z_max = z_tmp.max(axis=2)
in_x = (x_coord >= x_min[None, :, :]) & (x_coord <= x_max[None, :, :])
in_y = (y_coord >= y_min[:, None, :]) & (y_coord <= y_max[:, None, :])
in_z = (z_coord >= z_min[:, :, None]) & (z_coord <= z_max[:, :, None])
count = in_x.astype(int) + in_y.astype(int) + in_z.astype(int)
fill_mask = count >= (3 if rigid else 2)
self._voxel = self.voxel | fill_mask
x, y, z = np.where(self.voxel)
self.coords = np.stack([x, y, z], axis=1)
def inside(self, points: ndarray) -> ndarray:
if points.ndim == 1:
points = points[None, :]
points = np.asarray(points)
idx = np.floor((points - self.origin) / self.voxel_size).astype(int)
invalid = (
(idx < 0).any(axis=1) |
(idx >= np.array(self.voxel.shape)).any(axis=1)
)
result = np.zeros(len(points), dtype=bool)
valid_idx = np.where(~invalid)[0]
valid_voxel_idx = idx[valid_idx]
result[valid_idx] = self.voxel[valid_voxel_idx[:, 0], valid_voxel_idx[:, 1], valid_voxel_idx[:, 2]]
return result

View file

@ -0,0 +1,17 @@
"""Abstract class for parsers."""
from abc import ABC, abstractmethod
from ..info.asset import Asset
class AbstractParser(ABC):
"""Abstract class for parsers."""
@classmethod
@abstractmethod
def load(cls, filepath: str, **kwargs) -> Asset:
pass
@classmethod
def export(cls, asset: Asset, filepath: str, **kwargs):
raise NotImplementedError("do not implement")

View file

@ -0,0 +1,825 @@
from collections import defaultdict
from numpy import ndarray
from typing import Optional, Tuple
import bpy # type: ignore
import logging
import numpy as np
import os
import trimesh
from .abstract import AbstractParser
from ..info.asset import Asset
from mathutils import Vector, Matrix # type: ignore
class BpyParser(AbstractParser):
@classmethod
def load(cls, filepath: str, **kwargs) -> Asset:
clean_bpy()
load(filepath=filepath, **kwargs)
collection = bpy.data.collections.get("glTF_not_exported")
if collection is not None:
for obj in list(collection.objects):
bpy.data.objects.remove(obj, do_unlink=True)
armature = get_armature()
if armature is None:
bones = None
joint_names = None
parents = None
lengths = None
matrix_world = np.eye(4)
matrix_local = None
matrix_basis = None
armature_name = None
else:
bones = armature.pose.bones # list of PoseBone
joint_names = [b.name for b in bones]
parents = []
lengths = []
matrix_world = np.array(armature.matrix_world)
obj = armature.parent
while obj is not None:
matrix_world = np.array(obj.matrix_world) @ matrix_world
obj = obj.parent
matrix_local = []
for pbone in bones:
matrix_local.append(np.array(pbone.bone.matrix_local))
parents.append(joint_names.index(pbone.parent.name) if pbone.parent is not None else -1)
lengths.append(pbone.bone.length)
matrix_local = np.stack(matrix_local, axis=0)
parents = np.array(parents, dtype=np.int32)
lengths = np.array(lengths, dtype=np.float32)
matrix_basis = get_matrix_basis(bones=bones)
armature_name = armature.name
mesh_dict = extract_mesh(bones=bones)
return Asset(
vertices=mesh_dict['vertices'],
faces=mesh_dict['faces'],
vertex_normals=mesh_dict['vertex_normals'],
face_normals=mesh_dict['face_normals'],
vertex_bias=mesh_dict['vertex_bias'],
face_bias=mesh_dict['face_bias'],
mesh_names=mesh_dict['mesh_names'],
joint_names=joint_names,
parents=parents,
lengths=lengths,
matrix_world=matrix_world,
matrix_local=matrix_local,
matrix_basis=matrix_basis,
armature_name=armature_name,
skin=mesh_dict['skin'],
)
@classmethod
def export(cls, asset: Asset, filepath: str, **kwargs):
"""
If export obj, kwargs:
precision: int=6, number of decimal places for vertex coordinates
Otherwise, export fbx/glb/gltf using bpy, kwargs:
extrude_scale: float=0.5, if there is no tails in asset, first calculate the average length between parents and sons, then the length of leaf bone is l*extrude_scale. Otherwise do not affect final results.
connect_tail_to_unique_child: bool=False, if True, the tail of a bone with only one child will be exactly at the head of its child.
extrude_from_parent: bool=False, if True, the orientation of the leaf bone will be the same as its parent.
group_per_vertex: int=-1, number of the largest weights to keep for each vertex. -1 means keep all.
add_root: bool=False, if True, add a root bone at (0, 0, 0).
do_not_normalize: bool=False, if True, do not normalize the skinning weights.
collection_name: str='new_collection', name of the new collection to store objects.
add_leaf_bones: bool=False, if True, add a leaf bone at the end of each bone.
"""
ext = os.path.splitext(filepath)[1].lower()
if ext == '.obj':
cls.export_obj(asset, filepath, **kwargs)
elif ext == 'ply':
cls.export_ply(asset, filepath, **kwargs)
else:
cls.export_asset(asset, filepath, **kwargs)
@classmethod
def export_obj(
cls,
asset: Asset,
filepath: str,
precision: int=6,
use_pc: bool=False,
use_normal: bool=False,
use_skeleton: bool=False,
normal_size: float=0.01,
):
"""
Export the asset as an .obj file. This will ignore skeleton and skinning.
Args:
use_normal: export normals
use_skeleton: export skeleton
"""
asset._build_bias()
if asset.vertices is None or asset.vertex_bias is None:
raise ValueError("do not have vertices or vertex_bias")
if use_normal and asset.vertex_normals is None:
raise ValueError("use_normal is True but do not have vertex_normals")
if not filepath.lower().endswith('.obj'):
filepath += ".obj"
faces = asset.faces
mesh_names = asset.mesh_names
if mesh_names is None:
mesh_names = [f"mesh_{i}" for i in range(asset.P)]
cls._safe_make_dir(filepath)
file = open(filepath, 'w')
lines = []
tot = 0
if use_skeleton:
raise NotImplementedError()
for i, mesh_name in enumerate(mesh_names):
lines.append(f'o {mesh_name}\n')
if use_normal:
s = asset.get_vertex_slice(i)
for v, n in zip(asset.vertices[s], asset.vertex_normals[s]): # type: ignore
vv = v + n * normal_size
lines.append(f'v {v[0]:.{precision}f} {v[2]:.{precision}f} {-v[1]:.{precision}f}\n')
lines.append(f'v {vv[0]:.{precision}f} {vv[2]:.{precision}f} {-vv[1]:.{precision}f}\n')
lines.append(f'v {vv[0]:.{precision}f} {vv[2]:.{precision}f} {-vv[1]+0.000001:.{precision}f}\n')
lines.append(f"f {tot+1} {tot+2} {tot+3}\n")
tot += 3
else:
for v in asset.vertices[asset.get_vertex_slice(i)]:
lines.append(f'v {v[0]:.{precision}f} {v[2]:.{precision}f} {-v[1]:.{precision}f}\n')
if faces is not None and use_pc == False:
for f in faces[asset.get_face_slice(i)]:
lines.append(f"f {f[0]+1} {f[1]+1} {f[2]+1}\n")
file.writelines(lines)
file.close()
@classmethod
def export_ply(
cls,
asset: Asset,
filepath: str,
use_pc: bool=False,
render_skin_id: Optional[int]=None,
):
"""
Export the asset as an .ply file. This will ignore skeleton and skinning.
"""
import open3d as o3d
asset._build_bias()
if asset.vertices is None or asset.vertex_bias is None:
raise ValueError("do not have vertices or vertex_bias")
if not filepath.lower().endswith('.ply'):
filepath += ".ply"
faces = asset.faces
if use_pc:
faces = None
mesh_names = asset.mesh_names
if mesh_names is None:
mesh_names = [f"mesh_{i}" for i in range(asset.P)]
cls._safe_make_dir(filepath)
if render_skin_id is not None:
if asset.skin is None:
raise ValueError("render_skin_id is not None, but skin of asset is None")
colors = np.stack([
asset.skin[:, render_skin_id],
np.zeros(asset.N),
1-asset.skin[:, render_skin_id],
], axis=1)
else:
colors = None
if faces is None:
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(asset.vertices)
if colors is not None:
pcd.colors = o3d.utility.Vector3dVector(colors)
o3d.io.write_point_cloud(filepath, pcd)
else:
mesh = o3d.geometry.TriangleMesh()
mesh.vertices = o3d.utility.Vector3dVector(asset.vertices)
mesh.triangles = o3d.utility.Vector3iVector(faces)
if colors is not None:
mesh.vertex_colors = o3d.utility.Vector3dVector(colors)
o3d.io.write_triangle_mesh(filepath, mesh)
@classmethod
def export_asset(cls, asset: Asset, filepath: str, **kwargs):
use_origin = kwargs.pop('use_origin', False) if 'use_origin' in kwargs else False
if not use_origin:
clean_bpy()
make_asset(asset=asset, **kwargs)
cls._safe_make_dir(filepath)
_, ext = os.path.splitext(filepath)
ext = ext.lower()[1:]
if ext == 'fbx':
if asset.joints is not None and asset.matrix_basis is not None:
logging.warning("Exporting animation, but fbx format is deprecated because the rest pose will not be exported in bpy4.2. Use glb/gltf format instead. See: https://blender.stackexchange.com/questions/273398/blender-export-fbx-lose-the-origin-rest-pose.")
bpy.ops.export_scene.fbx(filepath=filepath, check_existing=False, add_leaf_bones=kwargs.get('add_leaf_bones', False), path_mode='COPY', embed_textures=True, mesh_smooth_type="FACE")
elif ext == 'glb' or ext == 'gltf':
bpy.ops.export_scene.gltf(filepath=filepath)
else:
raise ValueError(f"Unsupported format: {ext}")
@classmethod
def _safe_make_dir(cls, path: str):
if os.path.dirname(path) == '':
return
os.makedirs(os.path.dirname(path), exist_ok=True)
def clean_bpy():
"""Clean all the data in bpy."""
bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True)
data_types = [
bpy.data.actions,
bpy.data.armatures,
bpy.data.cameras,
bpy.data.collections,
bpy.data.curves,
bpy.data.lights,
bpy.data.materials,
bpy.data.meshes,
bpy.data.objects,
bpy.data.worlds,
bpy.data.node_groups,
bpy.data.images,
bpy.data.textures,
]
for data_collection in data_types:
for item in data_collection:
data_collection.remove(item)
def load(filepath: str, **kwargs):
"""Load a 3D file into bpy."""
_, ext = os.path.splitext(filepath)
ext = ext.lower()[1:]
if not os.path.exists(filepath):
raise RuntimeError(f"file does not exist: {filepath}")
if ext == "obj":
bpy.ops.wm.obj_import(filepath=filepath)
elif ext == "fbx":
bpy.ops.import_scene.fbx(
filepath=filepath,
ignore_leaf_bones=kwargs.get('ignore_leaf_bones', False),
use_image_search=kwargs.get('use_image_search', True),
)
elif ext == "glb" or ext == "gltf":
bpy.ops.import_scene.gltf(filepath=filepath, import_pack_images=kwargs.get('import_pack_images', False))
elif ext == "dae":
bpy.ops.wm.collada_import(filepath=filepath)
elif ext == "blend":
with bpy.data.libraries.load(filepath) as (data_from, data_to):
data_to.objects = data_from.objects
for obj in data_to.objects:
if obj is not None:
bpy.context.collection.objects.link(obj)
elif ext == "bvh":
bpy.ops.import_anim.bvh(filepath=filepath)
else:
raise ValueError(f"unsupported type: {ext}")
def get_armature():
"""Get the armature object in the current scene."""
armatures = [obj for obj in bpy.context.scene.objects if obj.type == 'ARMATURE']
if len(armatures) == 0:
return None
return armatures[0]
def extract_mesh(bones=None):
"""
Extract vertices, face_normals, faces and skinning(if possible).
"""
meshes = []
for v in bpy.data.objects:
if v.type == 'MESH':
meshes.append(v)
index = {}
if bones is not None:
for (id, pbone) in enumerate(bones):
index[pbone.name] = id
total_bones = len(bones)
else:
total_bones = None
mesh_names_list = []
vertices_list = []
faces_list = []
skin_list = []
vertex_bias = []
face_bias = []
cur_vertex_bias = 0
cur_face_bias = 0
for obj in meshes:
# directly apply mesh's transformation because armature operates on the transformed mesh
if obj.parent is not None:
m = np.linalg.inv(np.array(obj.parent.matrix_world)) @ np.array(obj.matrix_world)
else:
m = np.array(obj.matrix_world)
matrix_world_rot = m[:3, :3]
matrix_world_bias = m[:3, 3]
rot = matrix_world_rot
total_vertices = len(obj.data.vertices)
vertices = np.zeros((3, total_vertices))
if total_bones is not None:
skin_weight = np.zeros((total_vertices, total_bones))
else:
skin_weight = np.zeros((1, 1))
obj_verts = obj.data.vertices
obj_group_names = [g.name for g in obj.vertex_groups]
faces = []
normals = []
for polygon in obj.data.polygons:
edges = polygon.edge_keys
nodes = []
adj = {}
for edge in edges:
if adj.get(edge[0]) is None:
adj[edge[0]] = []
adj[edge[0]].append(edge[1])
if adj.get(edge[1]) is None:
adj[edge[1]] = []
adj[edge[1]].append(edge[0])
nodes.append(edge[0])
nodes.append(edge[1])
normal = polygon.normal
nodes = list(set(sorted(nodes)))
first = nodes[0]
loop = []
now = first
vis = {}
while True:
loop.append(now)
vis[now] = True
if vis.get(adj[now][0]) is None:
now = adj[now][0]
elif vis.get(adj[now][1]) is None:
now = adj[now][1]
else:
break
for (second, third) in zip(loop[1:], loop[2:]):
faces.append((first, second, third))
normals.append(rot @ normal)
faces = np.array(faces, dtype=np.int32)
normals = np.array(normals, dtype=np.float32)
coords = np.array([v.co for v in obj_verts])
rot_np = np.array(rot)
coords = (rot_np @ coords.T).T + matrix_world_bias
vertices[0:3, :coords.shape[0]] = coords.T
# extract skin
if bones is not None:
vg_lut = {}
for v in obj_verts:
for g in v.groups:
vg_lut[(v.index, g.group)] = g.weight
for bone in bones:
if bone.name not in obj_group_names:
continue
gidx = obj.vertex_groups[bone.name].index
col = index[bone.name]
for v in obj_verts:
w = vg_lut.get((v.index, gidx))
if w is not None:
skin_weight[v.index, col] = w
vertices = vertices.T
# determine the orientation of the face normal
v0 = vertices[faces[:, 0]]
v1 = vertices[faces[:, 1]]
v2 = vertices[faces[:, 2]]
cross = np.cross(v1-v0, v2-v0)
dot = np.einsum("ij,ij->i", cross, normals)
correct_faces = faces.copy()
mask = dot < 0
correct_faces[mask, 1], correct_faces[mask, 2] = faces[mask, 2], faces[mask, 1]
mesh_names_list.append(obj.name)
vertices_list.append(vertices)
faces_list.append(correct_faces+cur_vertex_bias) # add bias to faces
if total_bones is not None:
skin_list.append(skin_weight)
cur_vertex_bias += len(vertices)
cur_face_bias += len(faces)
vertex_bias.append(cur_vertex_bias)
face_bias.append(cur_face_bias)
vertices = np.vstack(vertices_list)
faces = np.vstack(faces_list)
mesh = trimesh.Trimesh(vertices=vertices, faces=faces, process=False, maintain_order=True)
vertex_normals = mesh.vertex_normals
face_normals = mesh.face_normals
return {
'mesh_names': np.array(mesh_names_list),
'vertices': vertices,
'faces': faces,
'face_normals': face_normals,
'vertex_normals': vertex_normals,
'skin': np.vstack(skin_list) if len(skin_list) > 0 else None,
'vertex_bias': np.array(vertex_bias),
'face_bias': np.array(face_bias),
}
def get_matrix_basis(bones=None):
if bones is None:
return None
if bpy.data.actions is not None and len(bpy.data.actions) > 0:
action = bpy.data.actions[0]
frames = int(action.frame_range.y - action.frame_range.x)
else:
return None
J = len(bones)
matrix_basis = np.zeros((frames, J, 4, 4))
matrix_basis[...] = np.eye(4)
for frame in range(frames):
bpy.context.scene.frame_set(frame + 1)
for (id, pbone) in enumerate(bones):
matrix_basis[frame, id] = np.array(pbone.matrix_basis)
return matrix_basis
def make_asset(
asset: Asset,
extrude_scale: float=0.5,
connect_tail_to_unique_child: bool=False,
extrude_from_parent: bool=False,
group_per_vertex: int=-1,
add_root: bool=False,
do_not_normalize: bool=False,
collection_name: str='new_collection',
use_face: bool=True,
):
"""
Args:
extrude_scale: float=0.5, if there is no tails in asset, first calculate the average length between parents and sons, then the length of leaf bone is l*extrude_scale. Otherwise do not affect final results.
connect_tail_to_unique_child: bool=False, if True, the tail of a bone with only one child will be exactly at the head of its child.
extrude_from_parent: bool=False, if True, the orientation of the leaf bone will be the same as its parent.
group_per_vertex: int=-1, number of the largest weights to keep for each vertex. -1 means keep all.
add_root: bool=False, if True, add a root bone at (0, 0, 0).
do_not_normalize: bool=False, if True, do not normalize the skinning weights.
collection_name: str='new_collection', name of the new collection to store objects.
use_face: bool=True, if False, do not export faces.
"""
collection = bpy.data.collections.new(collection_name)
bpy.context.scene.collection.children.link(collection)
# 1. if there are meshes, make meshes
objects = []
mesh_names = []
for v in bpy.data.objects:
if v.type == 'MESH':
objects.append(v)
mesh_names.append(v.name)
if len(objects) == 0:
mesh_names = [f"mesh_{i}" for i in range(asset.P)]
if len(objects)==0 and asset.vertices is not None:
if asset.mesh_names is not None:
mesh_names = asset.mesh_names
for i in range(asset.P):
mesh = bpy.data.meshes.new(f"data_{mesh_names[i]}")
v = asset.vertices[asset.get_vertex_slice(i)]
if not use_face or (asset.faces is None or asset.face_bias is None or asset.vertex_bias is None):
mesh.from_pydata(v, [], [])
else:
if i == 0:
mesh.from_pydata(v, [], asset.faces[asset.get_face_slice(i)])
else:
mesh.from_pydata(v, [], asset.faces[asset.get_face_slice(i)]-asset.vertex_bias[i-1])
mesh.update()
# make object from mesh
object = bpy.data.objects.new(mesh_names[i], mesh)
objects.append(object)
# add object to scene collection
collection.objects.link(object)
# 2. if there is armature, process tails and make armature
if len(bpy.data.armatures) > 0:
armature = bpy.data.armatures[0]
armature_name = armature.name
joint_names = [b.name for b in armature.bones]
else:
armature = None
armature_name = 'Armature'
joint_names = asset.joint_names if asset.joint_names is not None else [f"bone_{i}" for i in range(asset.J)]
if armature is None and asset.joints is not None and asset.parents is not None:
joints = asset.joints
if asset.tails is None:
tails = joints.copy()
connect_tail_to_unique_child = True
extrude_from_parent = True
else:
tails = asset.tails
root_tail = False
root_id = asset.root
length_sum = 0.
sons = defaultdict(list)
for i in range(len(asset.parents)):
p = asset.parents[i]
if p == -1:
continue
sons[p].append(i)
length_sum += np.linalg.norm(joints[i] - joints[p])
if asset.J <= 1:
length = 1.0
else:
length_avg = length_sum / max(len(asset.parents) - 1, 1)
length = length_avg * extrude_scale
for i in range(len(asset.parents)):
p = asset.parents[i]
if p == -1:
continue
sons[p].append(i)
d = np.linalg.norm(joints[i] - joints[p])
if d <= length * 1e-2:
max_d = max(length, 1e-5)
joints[i] += np.random.randn(3) * max_d * 1e-2
if connect_tail_to_unique_child:
for i in range(len(asset.parents)):
if len(sons[i]) == 1:
child = sons[i][0]
tails[i] = joints[child]
if root_id == i:
root_tail = True
if extrude_from_parent:
for i in range(len(asset.parents)):
if len(sons[i]) != 1 and asset.parents[i] != -1:
p = asset.parents[i]
d = joints[i] - joints[p]
if np.linalg.norm(d) < 1e-6:
d = np.array([0., 0., 1.]) # in case son.head == parent.head
else:
d = d / np.linalg.norm(d)
tails[i] = joints[i] + d * length
if root_tail is False:
tails[root_id] = joints[root_id] + np.array([0., 0., length])
bpy.ops.object.armature_add(enter_editmode=True)
armature = bpy.data.armatures.get('Armature')
armature_name = asset.armature_name if asset.armature_name is not None else 'Armature'
edit_bones = armature.edit_bones
if add_root:
bone_root = edit_bones.get('Bone')
root_name = 'Root'
x = 0
while root_name in joint_names:
root_name = f'Root_{x}'
x += 1
bone_root.name = root_name
bone_root.tail = Vector((joints[0, 0], joints[0, 1], joints[0, 2]))
else:
bone_root = edit_bones.get('Bone')
bone_root.name = joint_names[0]
bone_root.head = Vector((joints[0, 0], joints[0, 1], joints[0, 2]))
bone_root.tail = Vector((tails[0, 0], tails[0, 1], tails[0, 2]))
def extrude_bone(
edit_bones,
name: str,
parent_name: str,
head: Tuple[float, float, float],
tail: Tuple[float, float, float],
):
bone = edit_bones.new(name)
bone.head = Vector((head[0], head[1], head[2]))
bone.tail = Vector((tail[0], tail[1], tail[2]))
bone.name = name
parent_bone = edit_bones.get(parent_name)
bone.parent = parent_bone
bone.use_connect = False
assert not np.isnan(head).any(), f"nan found in head of bone {name}"
assert not np.isnan(tail).any(), f"nan found in tail of bone {name}"
for u in asset.dfs_order:
if add_root is False and u==0:
continue
pname = joint_names[u] if asset.parents[u] == -1 else joint_names[asset.parents[u]]
extrude_bone(edit_bones, joint_names[u], pname, joints[u], tails[u])
bpy.ops.object.mode_set(mode='OBJECT')
# 3. if there is skin, set vertex groups
if asset.skin is not None and armature is not None and len(objects) > 0:
# must set to object mode to enable parent_set
bpy.ops.object.mode_set(mode='OBJECT')
N = len(objects)
objects = bpy.data.objects
for o in bpy.context.selected_objects:
o.select_set(False)
for i in range(N):
skin = asset.skin[asset.get_vertex_slice(i)]
ob = objects[mesh_names[i]]
armature_b = bpy.data.objects[armature_name]
ob.select_set(True)
armature_b.select_set(True)
bpy.ops.object.parent_set(type='ARMATURE_NAME')
# sparsify
argsorted = np.argsort(-skin, axis=1)
vertex_group_reweight = skin[np.arange(skin.shape[0])[..., None], argsorted]
group_per_vertex = min(group_per_vertex, skin.shape[1])
if group_per_vertex == -1:
group_per_vertex = vertex_group_reweight.shape[-1]
if not do_not_normalize:
vertex_group_reweight = vertex_group_reweight / vertex_group_reweight[..., :group_per_vertex].sum(axis=1)[...,None]
# clean vertex groups first in case skin exists
for name in joint_names:
ob.vertex_groups[name].remove(range(990))
for v, w in enumerate(skin):
for ii in range(group_per_vertex):
j = argsorted[v, ii]
n = joint_names[j]
ob.vertex_groups[n].add([v], vertex_group_reweight[v, ii], 'REPLACE')
def to_matrix(x: ndarray):
return Matrix((x[0, :], x[1, :], x[2, :], x[3, :]))
if asset.matrix_world is None:
matrix_world = to_matrix(np.eye(4))
else:
matrix_world = to_matrix(asset.matrix_world)
if armature is not None:
bpy.data.objects[armature_name].matrix_world = matrix_world
# 4. if there is animation, set keyframes
if asset.matrix_basis is not None and asset.matrix_local is not None and armature is not None:
matrix_basis = asset.matrix_basis
matrix_local = asset.matrix_local
objects = bpy.data.objects
for o in bpy.context.selected_objects:
o.select_set(False)
armature = bpy.data.objects[armature_name]
armature.select_set(True)
armature.matrix_world = matrix_world
frames = matrix_basis.shape[0]
# change matrix_local
bpy.context.view_layer.objects.active = armature
bpy.ops.object.mode_set(mode='EDIT')
for (id, name) in enumerate(joint_names):
# matrix_local of pose bone
bpy.context.active_object.data.edit_bones[id].matrix = to_matrix(matrix_local[id])
bpy.ops.object.mode_set(mode='OBJECT')
for (id, name) in enumerate(joint_names):
pbone = armature.pose.bones.get(name)
for frame in range(frames):
bpy.context.scene.frame_set(frame + 1)
q = to_matrix(matrix_basis[frame, id])
if pbone.rotation_mode == "QUATERNION":
pbone.rotation_quaternion = q.to_quaternion()
pbone.keyframe_insert(data_path = 'rotation_quaternion')
else:
pbone.rotation_euler = q.to_euler()
pbone.keyframe_insert(data_path = 'rotation_euler')
pbone.location = q.to_translation()
pbone.keyframe_insert(data_path = 'location')
bpy.ops.object.mode_set(mode='OBJECT')
def _umeyama_similarity(src: ndarray, tgt: ndarray) -> ndarray:
assert src.shape == tgt.shape
n = src.shape[0]
src_mean = src.mean(axis=0)
tgt_mean = tgt.mean(axis=0)
src_c = src - src_mean
tgt_c = tgt - tgt_mean
# cross-covariance
C = (src_c.T @ tgt_c) / n
U, S, Vt = np.linalg.svd(C)
R = Vt.T @ U.T
if np.linalg.det(R) < 0:
Vt[-1, :] *= -1
R = Vt.T @ U.T
var_src = (src_c ** 2).sum() / n
scale = S.sum() / var_src
t = tgt_mean - scale * R @ src_mean
T = np.eye(4)
T[:3, :3] = scale * R
T[:3, 3] = t
return T
def _pca_similarity(
src: ndarray,
tgt: ndarray,
max_points: int=4096,
) -> ndarray:
if src.shape[0] > max_points:
src = src[np.random.choice(src.shape[0], max_points, replace=False)]
if tgt.shape[0] > max_points:
tgt = tgt[np.random.choice(tgt.shape[0], max_points, replace=False)]
src_mean = src.mean(axis=0)
tgt_mean = tgt.mean(axis=0)
src_c = src - src_mean
tgt_c = tgt - tgt_mean
U_src, _, _ = np.linalg.svd(src_c.T @ src_c)
U_tgt, _, _ = np.linalg.svd(tgt_c.T @ tgt_c)
R = U_tgt @ U_src.T
if np.linalg.det(R) < 0:
U_tgt[:, -1] *= -1
R = U_tgt @ U_src.T
scale = np.sqrt((tgt_c ** 2).sum() / (src_c ** 2).sum())
t = tgt_mean - scale * R @ src_mean
T = np.eye(4)
T[:3, :3] = scale * R
T[:3, 3] = t
return T
def estimate_similarity_transform(
src: ndarray,
tgt: ndarray,
max_points: int=4096,
) -> ndarray:
"""
src: (N, 3)
tgt: (M, 3)
return: (4, 4) similarity transform matrix
"""
if src.shape[0] == tgt.shape[0]:
return _umeyama_similarity(src, tgt)
return _pca_similarity(src, tgt, max_points)
def transfer_rigging(
source_asset: Asset,
target_path: str,
export_path: str,
**kwargs,
):
assert source_asset.matrix_local is not None
assert source_asset.parents is not None
target_asset = BpyParser.load(filepath=target_path)
bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True)
data_types = [
bpy.data.actions,
bpy.data.armatures,
]
for data_collection in data_types:
for item in data_collection:
data_collection.remove(item)
source_vertices = source_asset.vertices # (n, 3)
target_vertices = target_asset.vertices # (m, 3)
assert source_vertices is not None and target_vertices is not None
target_asset.matrix_local = source_asset.matrix_local.copy()
target_asset.matrix_basis = source_asset.matrix_basis.copy() if source_asset.matrix_basis is not None else None
source_joints = source_asset.joints
assert source_joints is not None
max_points = kwargs.pop('max_points', 4096) if kwargs.get('max_points') is not None else 4096
T = estimate_similarity_transform(src=source_vertices, tgt=target_vertices, max_points=max_points)
source_joints_h = np.concatenate([
source_joints, np.ones((len(source_joints), 1))
], axis=1)
target_joints = (T @ source_joints_h.T).T[:, :3]
target_asset.matrix_local[:, :3, 3] = target_joints
target_asset.parents = source_asset.parents.copy()
target_asset.lengths = source_asset.lengths.copy() if source_asset.lengths is not None else None
target_asset.joint_names = source_asset.joint_names.copy() if source_asset.joint_names is not None else None
if source_asset.skin is not None:
from scipy.spatial import cKDTree
source_skin = source_asset.skin # (n, J)
source_vertices_h = np.concatenate([
source_vertices, np.ones((len(source_vertices), 1))
], axis=1)
source_vertices = (T @ source_vertices_h.T).T[:, :3]
tree = cKDTree(source_vertices)
dists, idx = tree.query(target_vertices, k=1)
target_asset.skin = source_skin[idx]
BpyParser.export(target_asset, export_path, use_origin=True, **kwargs)
clean_bpy()

View file

@ -0,0 +1,997 @@
from __future__ import annotations
import re
from functools import lru_cache
from pathlib import Path
from typing import Iterable, List, Optional
import numpy as np
from omegaconf import OmegaConf
SKELETON_TEMPLATE_KEEP = "original"
SKELETON_TEMPLATE_MIXAMO = "mixamo"
SKELETON_TEMPLATE_UE5 = "ue5"
SKELETON_TEMPLATE_KEYS = [
SKELETON_TEMPLATE_KEEP,
SKELETON_TEMPLATE_MIXAMO,
SKELETON_TEMPLATE_UE5,
]
SKELETON_TEMPLATE_LABELS = {
SKELETON_TEMPLATE_KEEP: "Keep model names",
SKELETON_TEMPLATE_MIXAMO: "Mixamo",
SKELETON_TEMPLATE_UE5: "Unreal Engine 5",
}
SKELETON_TEMPLATE_LABEL_CHOICES = [
SKELETON_TEMPLATE_LABELS[key] for key in SKELETON_TEMPLATE_KEYS
]
_LABEL_TO_TEMPLATE = {
label: key for (key, label) in SKELETON_TEMPLATE_LABELS.items()
}
_TEMPLATE_CONFIGS = {
SKELETON_TEMPLATE_MIXAMO: (
Path(__file__).resolve().parents[2] / "configs" / "skeleton" / "mixamo.yaml"
),
SKELETON_TEMPLATE_UE5: (
Path(__file__).resolve().parents[2] / "configs" / "skeleton" / "ue5.yaml"
),
}
_GENERIC_BONE_NAME = re.compile(r"^(bone|joint)[_ .:-]*\d+$", re.IGNORECASE)
_EXTRA_BONE_PREFIX = {
SKELETON_TEMPLATE_MIXAMO: "mixamorig:Extra",
SKELETON_TEMPLATE_UE5: "extra",
}
_SEMANTIC_TEMPLATE_NAMES = {
SKELETON_TEMPLATE_MIXAMO: {
"hips": "mixamorig:Hips",
"spines": [
"mixamorig:Spine",
"mixamorig:Spine1",
"mixamorig:Spine2",
],
"neck": "mixamorig:Neck",
"head": "mixamorig:Head",
"left_arm": [
"mixamorig:LeftShoulder",
"mixamorig:LeftArm",
"mixamorig:LeftForeArm",
"mixamorig:LeftHand",
],
"right_arm": [
"mixamorig:RightShoulder",
"mixamorig:RightArm",
"mixamorig:RightForeArm",
"mixamorig:RightHand",
],
"left_leg": [
"mixamorig:LeftUpLeg",
"mixamorig:LeftLeg",
"mixamorig:LeftFoot",
"mixamorig:LeftToeBase",
],
"right_leg": [
"mixamorig:RightUpLeg",
"mixamorig:RightLeg",
"mixamorig:RightFoot",
"mixamorig:RightToeBase",
],
"left_fingers": {
"thumb": [
"mixamorig:LeftHandThumb1",
"mixamorig:LeftHandThumb2",
"mixamorig:LeftHandThumb3",
],
"index": [
"mixamorig:LeftHandIndex1",
"mixamorig:LeftHandIndex2",
"mixamorig:LeftHandIndex3",
],
"middle": [
"mixamorig:LeftHandMiddle1",
"mixamorig:LeftHandMiddle2",
"mixamorig:LeftHandMiddle3",
],
"ring": [
"mixamorig:LeftHandRing1",
"mixamorig:LeftHandRing2",
"mixamorig:LeftHandRing3",
],
"pinky": [
"mixamorig:LeftHandPinky1",
"mixamorig:LeftHandPinky2",
"mixamorig:LeftHandPinky3",
],
},
"right_fingers": {
"thumb": [
"mixamorig:RightHandThumb1",
"mixamorig:RightHandThumb2",
"mixamorig:RightHandThumb3",
],
"index": [
"mixamorig:RightHandIndex1",
"mixamorig:RightHandIndex2",
"mixamorig:RightHandIndex3",
],
"middle": [
"mixamorig:RightHandMiddle1",
"mixamorig:RightHandMiddle2",
"mixamorig:RightHandMiddle3",
],
"ring": [
"mixamorig:RightHandRing1",
"mixamorig:RightHandRing2",
"mixamorig:RightHandRing3",
],
"pinky": [
"mixamorig:RightHandPinky1",
"mixamorig:RightHandPinky2",
"mixamorig:RightHandPinky3",
],
},
},
SKELETON_TEMPLATE_UE5: {
"hips": "pelvis",
"spines": [
"spine_01",
"spine_02",
"spine_03",
],
"neck": "neck_01",
"head": "head",
"left_arm": [
"clavicle_l",
"upperarm_l",
"lowerarm_l",
"hand_l",
],
"right_arm": [
"clavicle_r",
"upperarm_r",
"lowerarm_r",
"hand_r",
],
"left_leg": [
"thigh_l",
"calf_l",
"foot_l",
"ball_l",
],
"right_leg": [
"thigh_r",
"calf_r",
"foot_r",
"ball_r",
],
"left_fingers": {
"thumb": ["thumb_01_l", "thumb_02_l", "thumb_03_l"],
"index": ["index_01_l", "index_02_l", "index_03_l"],
"middle": ["middle_01_l", "middle_02_l", "middle_03_l"],
"ring": ["ring_01_l", "ring_02_l", "ring_03_l"],
"pinky": ["pinky_01_l", "pinky_02_l", "pinky_03_l"],
},
"right_fingers": {
"thumb": ["thumb_01_r", "thumb_02_r", "thumb_03_r"],
"index": ["index_01_r", "index_02_r", "index_03_r"],
"middle": ["middle_01_r", "middle_02_r", "middle_03_r"],
"ring": ["ring_01_r", "ring_02_r", "ring_03_r"],
"pinky": ["pinky_01_r", "pinky_02_r", "pinky_03_r"],
},
},
}
def normalize_skeleton_template(template: Optional[str]) -> str:
if template is None:
return SKELETON_TEMPLATE_KEEP
template = _LABEL_TO_TEMPLATE.get(template, template)
if template not in SKELETON_TEMPLATE_KEYS:
raise ValueError(f"Unknown skeleton template: {template}")
return template
@lru_cache(maxsize=None)
def _load_template_names(template: str) -> List[str]:
template = normalize_skeleton_template(template)
if template == SKELETON_TEMPLATE_KEEP:
return []
config = OmegaConf.load(_TEMPLATE_CONFIGS[template])
names: List[str] = []
for part in config.parts_order:
names.extend(str(name) for name in config.parts[part])
return names
def _is_generic_bone_name(name: str) -> bool:
return bool(_GENERIC_BONE_NAME.fullmatch(name))
def _resolve_source_names(
joint_names: Optional[Iterable[str]],
joint_count: int,
) -> List[str]:
names = list(joint_names or [])
if len(names) < joint_count:
names.extend(f"bone_{i}" for i in range(len(names), joint_count))
return names[:joint_count]
def _make_unique_name(name: str, seen: set[str]) -> str:
if name not in seen:
seen.add(name)
return name
suffix = 1
candidate = f"{name}_{suffix}"
while candidate in seen:
suffix += 1
candidate = f"{name}_{suffix}"
seen.add(candidate)
return candidate
def _make_unique_names(names: List[str]) -> List[str]:
seen: set[str] = set()
return [_make_unique_name(name, seen) for name in names]
def _build_children(parents: np.ndarray) -> tuple[int, List[List[int]]]:
root = -1
children = [[] for _ in range(len(parents))]
for idx, parent in enumerate(parents.tolist()):
if parent == -1:
if root != -1:
raise ValueError("Multiple roots found in skeleton.")
root = idx
continue
children[parent].append(idx)
if root == -1:
raise ValueError("Skeleton has no root.")
return root, children
def _post_order(root: int, children: List[List[int]]) -> List[int]:
order: List[int] = []
stack = [(root, False)]
while stack:
node, visited = stack.pop()
if visited:
order.append(node)
continue
stack.append((node, True))
for child in children[node]:
stack.append((child, False))
return order
def _compute_subtree_stats(
joints: np.ndarray,
children: List[List[int]],
root: int,
x_axis: int,
z_axis: int,
) -> dict[str, np.ndarray]:
joint_count = joints.shape[0]
subtree_size = np.ones(joint_count, dtype=np.int32)
subtree_min_z = joints[:, z_axis].copy()
subtree_max_z = joints[:, z_axis].copy()
subtree_min_x = joints[:, x_axis].copy()
subtree_max_x = joints[:, x_axis].copy()
for node in _post_order(root=root, children=children):
for child in children[node]:
subtree_size[node] += subtree_size[child]
subtree_min_z[node] = min(subtree_min_z[node], subtree_min_z[child])
subtree_max_z[node] = max(subtree_max_z[node], subtree_max_z[child])
subtree_min_x[node] = min(subtree_min_x[node], subtree_min_x[child])
subtree_max_x[node] = max(subtree_max_x[node], subtree_max_x[child])
return {
"size": subtree_size,
"min_z": subtree_min_z,
"max_z": subtree_max_z,
"min_x": subtree_min_x,
"max_x": subtree_max_x,
}
def _normalize(v: np.ndarray) -> np.ndarray:
norm = np.linalg.norm(v)
if norm < 1e-8:
return np.zeros_like(v)
return v / norm
def _principal_axis(points: np.ndarray) -> np.ndarray:
if points.shape[0] == 0:
return np.zeros((points.shape[1],), dtype=np.float32)
centered = points - points.mean(axis=0, keepdims=True)
if np.linalg.norm(centered) < 1e-8:
return np.zeros((points.shape[1],), dtype=np.float32)
_, _, vh = np.linalg.svd(centered, full_matrices=False)
return vh[0]
def _side_sign(side: str, left_is_positive_x: bool) -> float:
if left_is_positive_x:
return 1.0 if side == "left" else -1.0
return -1.0 if side == "left" else 1.0
def _build_extra_names(
source_names: List[str],
template: str,
) -> List[str]:
extra_prefix = _EXTRA_BONE_PREFIX[template]
fallback = []
for idx, name in enumerate(source_names):
if name and not _is_generic_bone_name(name):
fallback.append(name)
else:
fallback.append(f"{extra_prefix}_{idx:02d}")
return fallback
def _follow_best_chain(
start: int,
children: List[List[int]],
joints: np.ndarray,
root_x: float,
x_axis: int,
z_axis: int,
subtree_stats: dict[str, np.ndarray],
mode: str,
side: Optional[str] = None,
left_is_positive_x: bool = True,
) -> List[int]:
chain = [start]
current = start
seen = {start}
while True:
child_nodes = [child for child in children[current] if child not in seen]
if not child_nodes:
break
if mode == "arm" and len(child_nodes) >= 3 and len(chain) >= 3:
break
best_child = None
best_score = float("-inf")
for child in child_nodes:
x_offset = joints[child, x_axis] - root_x
z_offset = joints[child, z_axis] - joints[current, z_axis]
side_bonus = 0.0
if side is not None:
side_dir = _side_sign(side, left_is_positive_x=left_is_positive_x)
side_bonus = side_dir * x_offset
if mode == "spine":
score = (
5.0 * (subtree_stats["max_z"][child] - joints[current, z_axis])
+ 2.0 * z_offset
- 3.0 * abs(x_offset)
+ 0.02 * float(subtree_stats["size"][child])
)
elif mode == "arm":
score = (
5.0 * abs(x_offset)
+ 1.5 * side_bonus
+ 1.0 * (subtree_stats["max_z"][child] - joints[current, z_axis])
+ 0.02 * float(subtree_stats["size"][child])
)
else:
score = (
5.0 * (joints[current, z_axis] - subtree_stats["min_z"][child])
+ 1.5 * abs(x_offset)
+ 1.0 * side_bonus
+ 0.02 * float(subtree_stats["size"][child])
)
if score > best_score:
best_score = score
best_child = child
if best_child is None:
break
if mode == "spine" and best_score < 0.05:
break
chain.append(best_child)
seen.add(best_child)
current = best_child
return chain
def _select_side_branch(
candidates: List[int],
joints: np.ndarray,
root_x: float,
x_axis: int,
z_axis: int,
subtree_stats: dict[str, np.ndarray],
side: str,
kind: str,
left_is_positive_x: bool,
) -> Optional[int]:
best_node = None
best_score = float("-inf")
side_dir = _side_sign(side, left_is_positive_x=left_is_positive_x)
for node in candidates:
x_offset = joints[node, x_axis] - root_x
if side_dir * x_offset <= 0:
continue
lateral = max(
abs(subtree_stats["max_x"][node] - root_x),
abs(subtree_stats["min_x"][node] - root_x),
)
if kind == "arm":
score = (
6.0 * lateral
+ 1.5 * (subtree_stats["max_z"][node] - joints[:, z_axis].min())
+ 0.05 * float(subtree_stats["size"][node])
)
else:
score = (
5.0 * (joints[:, z_axis].max() - subtree_stats["min_z"][node])
+ 2.0 * lateral
+ 0.05 * float(subtree_stats["size"][node])
)
if score > best_score:
best_score = score
best_node = node
return best_node
def _select_top_branch_candidates(
candidates: List[int],
joints: np.ndarray,
root_x: float,
x_axis: int,
z_axis: int,
subtree_stats: dict[str, np.ndarray],
kind: str,
limit: int,
) -> List[int]:
scored: List[tuple[float, int]] = []
for node in candidates:
x_offset = joints[node, x_axis] - root_x
lateral = max(
abs(subtree_stats["max_x"][node] - root_x),
abs(subtree_stats["min_x"][node] - root_x),
)
if kind == "arm":
score = (
6.0 * lateral
+ 1.5 * (subtree_stats["max_z"][node] - joints[:, z_axis].min())
+ 0.05 * float(subtree_stats["size"][node])
)
else:
score = (
5.0 * (joints[:, z_axis].max() - subtree_stats["min_z"][node])
+ 2.0 * abs(x_offset)
+ 0.05 * float(subtree_stats["size"][node])
)
scored.append((score, node))
scored.sort(reverse=True)
return [node for _, node in scored[:limit]]
def _infer_left_positive_x(
joints: np.ndarray,
root_idx: int,
central_chain: List[int],
leg_chains: List[List[int]],
z_axis: int,
) -> Optional[bool]:
if len(central_chain) < 2:
return None
up_vector = _normalize(joints[central_chain[-1]] - joints[root_idx])
if np.linalg.norm(up_vector) < 1e-6:
up_vector = np.array([0.0, 0.0, 1.0], dtype=np.float32)
forward_vectors = []
for chain in leg_chains:
if len(chain) >= 2:
direction = joints[chain[-1]] - joints[chain[-2]]
direction = direction - np.dot(direction, up_vector) * up_vector
if np.linalg.norm(direction) > 1e-6:
forward_vectors.append(_normalize(direction))
if not forward_vectors:
return None
forward_vector = _normalize(np.mean(forward_vectors, axis=0))
if np.linalg.norm(forward_vector) < 1e-6:
return None
left_axis = _normalize(np.cross(up_vector, forward_vector))
if np.linalg.norm(left_axis) < 1e-6:
return None
return bool(left_axis[0] >= 0.0)
def _assign_chain_names(
target_names: List[str],
chain: List[int],
semantic_names: List[str],
) -> None:
for node, name in zip(chain, semantic_names):
target_names[node] = name
def _extend_linear_branch(
start: int,
children: List[List[int]],
joints: np.ndarray,
hand_idx: int,
max_length: int = 3,
) -> List[int]:
chain = [start]
current = start
seen = {start}
while len(chain) < max_length:
child_nodes = [child for child in children[current] if child not in seen]
if not child_nodes:
break
if len(child_nodes) == 1:
best_child = child_nodes[0]
else:
best_child = max(
child_nodes,
key=lambda child: float(np.linalg.norm(joints[child] - joints[hand_idx])),
)
chain.append(best_child)
seen.add(best_child)
current = best_child
return chain
def _classify_finger_branches(
hand_idx: int,
children: List[List[int]],
joints: np.ndarray,
) -> List[List[int]]:
branches = [
_extend_linear_branch(start=child, children=children, joints=joints, hand_idx=hand_idx)
for child in children[hand_idx]
]
if len(branches) <= 5:
return branches
branches.sort(
key=lambda branch: (
len(branch),
float(np.linalg.norm(joints[branch[-1]] - joints[hand_idx])),
),
reverse=True,
)
return branches[:5]
def _assign_finger_names(
target_names: List[str],
hand_idx: Optional[int],
side: str,
template: str,
children: List[List[int]],
joints: np.ndarray,
) -> None:
if hand_idx is None:
return
finger_branches = _classify_finger_branches(hand_idx=hand_idx, children=children, joints=joints)
if len(finger_branches) < 2:
return
tip_dirs = np.stack(
[
_normalize(joints[branch[-1]] - joints[hand_idx])
for branch in finger_branches
],
axis=0,
)
thumb_idx = 0
if len(finger_branches) >= 3:
cosine = tip_dirs @ tip_dirs.T
denom = max(len(finger_branches) - 1, 1)
avg_similarity = (cosine.sum(axis=1) - 1.0) / denom
thumb_idx = int(np.argmin(avg_similarity))
thumb_branch = finger_branches[thumb_idx]
other_items = [
(idx, branch)
for idx, branch in enumerate(finger_branches)
if idx != thumb_idx
]
if not other_items:
return
other_branches = [branch for _, branch in other_items]
forward = _normalize(np.mean(
[_normalize(joints[branch[-1]] - joints[hand_idx]) for branch in other_branches],
axis=0,
))
if np.linalg.norm(forward) < 1e-6:
forward = np.array([0.0, 1.0, 0.0], dtype=np.float32)
base_positions = np.stack(
[joints[branch[0]] - joints[hand_idx] for branch in other_branches],
axis=0,
)
projected = base_positions - np.outer(base_positions @ forward, forward)
lateral_axis = _principal_axis(projected)
if np.linalg.norm(lateral_axis) < 1e-6:
lateral_axis = np.array([1.0, 0.0, 0.0], dtype=np.float32)
other_scalars = projected @ lateral_axis
thumb_base = joints[thumb_branch[0]] - joints[hand_idx]
thumb_projected = thumb_base - np.dot(thumb_base, forward) * forward
thumb_scalar = float(np.dot(thumb_projected, lateral_axis))
ordered = list(zip(other_scalars.tolist(), other_branches))
ordered.sort(key=lambda item: item[0])
if thumb_scalar >= float(np.mean(other_scalars)):
ordered.reverse()
semantic = _SEMANTIC_TEMPLATE_NAMES[template][f"{side}_fingers"]
_assign_chain_names(target_names, thumb_branch, semantic["thumb"])
semantic_order = ["index", "middle", "ring", "pinky"]
for key, (_, branch) in zip(semantic_order, ordered):
_assign_chain_names(target_names, branch, semantic[key])
def _build_humanoid_template_names(
source_names: List[str],
joints: np.ndarray,
parents: np.ndarray,
template: str,
left_is_positive_x: bool,
) -> tuple[Optional[List[str]], int]:
if template not in _SEMANTIC_TEMPLATE_NAMES:
return None, -1
x_axis = 0
z_axis = 2
try:
root, children = _build_children(parents=parents)
except ValueError:
return None, -1
if joints.shape[0] < 10:
return None, -1
root_x = float(joints[root, x_axis])
subtree_stats = _compute_subtree_stats(
joints=joints,
children=children,
root=root,
x_axis=x_axis,
z_axis=z_axis,
)
root_children = children[root]
if not root_children:
return None, -1
spine_child = None
spine_score = float("-inf")
for child in root_children:
score = (
6.0 * (subtree_stats["max_z"][child] - joints[root, z_axis])
- 4.0 * abs(joints[child, x_axis] - root_x)
+ 0.05 * float(subtree_stats["size"][child])
)
if score > spine_score:
spine_score = score
spine_child = child
if spine_child is None:
return None, -1
central_chain = [root]
central_chain.extend(
_follow_best_chain(
start=spine_child,
children=children,
joints=joints,
root_x=root_x,
x_axis=x_axis,
z_axis=z_axis,
subtree_stats=subtree_stats,
mode="spine",
left_is_positive_x=left_is_positive_x,
)
)
central_set = set(central_chain)
if len(central_chain) < 4:
return None, -1
central_next = {central_chain[idx]: central_chain[idx + 1] for idx in range(len(central_chain) - 1)}
arm_candidates: List[int] = []
leg_candidates: List[int] = []
for center in central_chain:
for child in children[center]:
if central_next.get(center) == child:
continue
if center == root:
leg_candidates.append(child)
else:
arm_candidates.append(child)
semantic_names = _build_extra_names(source_names=source_names, template=template)
slots = _SEMANTIC_TEMPLATE_NAMES[template]
semantic_names[root] = slots["hips"]
torso_nodes = central_chain[1:]
if len(torso_nodes) >= 2:
semantic_names[torso_nodes[-1]] = slots["head"]
semantic_names[torso_nodes[-2]] = slots["neck"]
spine_nodes = torso_nodes[:-2] if len(torso_nodes) > 2 else torso_nodes[:-1]
_assign_chain_names(semantic_names, spine_nodes, slots["spines"])
preview_leg_roots = _select_top_branch_candidates(
candidates=leg_candidates,
joints=joints,
root_x=root_x,
x_axis=x_axis,
z_axis=z_axis,
subtree_stats=subtree_stats,
kind="leg",
limit=2,
)
preview_leg_chains = [
_follow_best_chain(
start=leg_root,
children=children,
joints=joints,
root_x=root_x,
x_axis=x_axis,
z_axis=z_axis,
subtree_stats=subtree_stats,
mode="leg",
left_is_positive_x=left_is_positive_x,
)
for leg_root in preview_leg_roots
]
inferred_left_positive_x = _infer_left_positive_x(
joints=joints,
root_idx=root,
central_chain=central_chain,
leg_chains=preview_leg_chains,
z_axis=z_axis,
)
resolved_left_positive_x = (
left_is_positive_x if inferred_left_positive_x is None else inferred_left_positive_x
)
left_arm_root = _select_side_branch(
candidates=arm_candidates,
joints=joints,
root_x=root_x,
x_axis=x_axis,
z_axis=z_axis,
subtree_stats=subtree_stats,
side="left",
kind="arm",
left_is_positive_x=resolved_left_positive_x,
)
right_arm_root = _select_side_branch(
candidates=arm_candidates,
joints=joints,
root_x=root_x,
x_axis=x_axis,
z_axis=z_axis,
subtree_stats=subtree_stats,
side="right",
kind="arm",
left_is_positive_x=resolved_left_positive_x,
)
left_leg_root = _select_side_branch(
candidates=leg_candidates,
joints=joints,
root_x=root_x,
x_axis=x_axis,
z_axis=z_axis,
subtree_stats=subtree_stats,
side="left",
kind="leg",
left_is_positive_x=resolved_left_positive_x,
)
right_leg_root = _select_side_branch(
candidates=leg_candidates,
joints=joints,
root_x=root_x,
x_axis=x_axis,
z_axis=z_axis,
subtree_stats=subtree_stats,
side="right",
kind="leg",
left_is_positive_x=resolved_left_positive_x,
)
left_arm_chain = (
_follow_best_chain(
start=left_arm_root,
children=children,
joints=joints,
root_x=root_x,
x_axis=x_axis,
z_axis=z_axis,
subtree_stats=subtree_stats,
mode="arm",
side="left",
left_is_positive_x=resolved_left_positive_x,
)
if left_arm_root is not None
else []
)
right_arm_chain = (
_follow_best_chain(
start=right_arm_root,
children=children,
joints=joints,
root_x=root_x,
x_axis=x_axis,
z_axis=z_axis,
subtree_stats=subtree_stats,
mode="arm",
side="right",
left_is_positive_x=resolved_left_positive_x,
)
if right_arm_root is not None
else []
)
left_leg_chain = (
_follow_best_chain(
start=left_leg_root,
children=children,
joints=joints,
root_x=root_x,
x_axis=x_axis,
z_axis=z_axis,
subtree_stats=subtree_stats,
mode="leg",
side="left",
left_is_positive_x=resolved_left_positive_x,
)
if left_leg_root is not None
else []
)
right_leg_chain = (
_follow_best_chain(
start=right_leg_root,
children=children,
joints=joints,
root_x=root_x,
x_axis=x_axis,
z_axis=z_axis,
subtree_stats=subtree_stats,
mode="leg",
side="right",
left_is_positive_x=resolved_left_positive_x,
)
if right_leg_root is not None
else []
)
_assign_chain_names(semantic_names, left_arm_chain, slots["left_arm"])
_assign_chain_names(semantic_names, right_arm_chain, slots["right_arm"])
_assign_chain_names(semantic_names, left_leg_chain, slots["left_leg"])
_assign_chain_names(semantic_names, right_leg_chain, slots["right_leg"])
left_hand_idx = left_arm_chain[min(3, len(left_arm_chain) - 1)] if left_arm_chain else None
right_hand_idx = right_arm_chain[min(3, len(right_arm_chain) - 1)] if right_arm_chain else None
_assign_finger_names(
target_names=semantic_names,
hand_idx=left_hand_idx,
side="left",
template=template,
children=children,
joints=joints,
)
_assign_finger_names(
target_names=semantic_names,
hand_idx=right_hand_idx,
side="right",
template=template,
children=children,
joints=joints,
)
found_limbs = sum(bool(chain) for chain in [left_arm_chain, right_arm_chain, left_leg_chain, right_leg_chain])
if found_limbs < 3:
return None, found_limbs
score = (
found_limbs * 10
+ min(len(left_arm_chain), 4)
+ min(len(right_arm_chain), 4)
+ min(len(left_leg_chain), 4)
+ min(len(right_leg_chain), 4)
+ min(len(central_chain), 6)
)
return _make_unique_names(semantic_names), score
def _apply_humanoid_template(
source_names: List[str],
joints: np.ndarray,
parents: np.ndarray,
template: str,
) -> Optional[List[str]]:
best_names = None
best_score = -1
for left_is_positive_x in (True, False):
candidate_names, candidate_score = _build_humanoid_template_names(
source_names=source_names,
joints=joints,
parents=parents,
template=template,
left_is_positive_x=left_is_positive_x,
)
if candidate_names is not None and candidate_score > best_score:
best_names = candidate_names
best_score = candidate_score
return best_names
def apply_joint_name_template(
joint_names: Optional[Iterable[str]],
joint_count: int,
template: Optional[str],
) -> List[str]:
template = normalize_skeleton_template(template)
source_names = _resolve_source_names(joint_names=joint_names, joint_count=joint_count)
if template == SKELETON_TEMPLATE_KEEP:
seen: set[str] = set()
return [_make_unique_name(name, seen) for name in source_names]
template_names = _load_template_names(template)
extra_prefix = _EXTRA_BONE_PREFIX[template]
renamed: List[str] = []
seen: set[str] = set()
for idx in range(joint_count):
if idx < len(template_names):
candidate = template_names[idx]
else:
source_name = source_names[idx]
if source_name and not _is_generic_bone_name(source_name):
candidate = source_name
else:
candidate = f"{extra_prefix}_{idx - len(template_names):02d}"
renamed.append(_make_unique_name(candidate, seen))
return renamed
def apply_asset_joint_name_template(
joint_names: Optional[Iterable[str]],
joints: Optional[np.ndarray],
parents: Optional[np.ndarray],
template: Optional[str],
) -> List[str]:
template = normalize_skeleton_template(template)
joint_count = 0 if parents is None else int(len(parents))
if joints is not None:
joint_count = int(joints.shape[0])
source_names = _resolve_source_names(joint_names=joint_names, joint_count=joint_count)
if template == SKELETON_TEMPLATE_KEEP:
return _make_unique_names(source_names)
if joints is not None and parents is not None and joint_count > 0:
humanoid_names = _apply_humanoid_template(
source_names=source_names,
joints=np.asarray(joints, dtype=np.float32),
parents=np.asarray(parents, dtype=np.int32),
template=template,
)
if humanoid_names is not None:
return humanoid_names
return apply_joint_name_template(
joint_names=source_names,
joint_count=joint_count,
template=template,
)

View file

@ -0,0 +1,312 @@
from numpy import ndarray
from typing import Optional, Tuple
import numpy as np
import scipy
def assert_ndarray(arr, name: str="arr", shape: Optional[Tuple[int, ...]]=None, dtype=None):
if not isinstance(arr, np.ndarray):
raise ValueError(f"{name} must be a numpy.ndarray or None, got {type(arr)}")
if shape is not None:
# shape may contain None as wildcard
if len(shape) != arr.ndim:
raise ValueError(f"{name}: expected shape length {len(shape)} but array ndim is {arr.ndim}")
for i, (exp, actual) in enumerate(zip(shape, arr.shape)):
if exp > 0 and exp != actual:
raise ValueError(f"{name} shape mismatch at axis {i}: expected {exp}, got {actual}")
if dtype is not None:
if not np.issubdtype(arr.dtype, dtype):
raise ValueError(f"{name} dtype must be {dtype}, got {arr.dtype}")
def assert_list(arr, name: str="arr", dtype=None):
if not isinstance(arr, list):
raise ValueError(f"found type {type(arr)}, expect a list")
if dtype is not None:
for x in arr:
if not isinstance(x, dtype):
raise ValueError(f"found type {type(x)} in {name}, expect all to be {dtype}")
def linear_blend_skinning(
vertices: ndarray,
matrix_local: ndarray,
matrix: ndarray,
skin: ndarray,
pad: int=1,
value: float=1.0,
) -> ndarray:
"""
Args:
vertices: (N, 4-pad)
matrix_local: (J, 4, 4)
matrix: (J, 4, 4)
skin: (N, J)
pad: 0 or 1
value: value to pad
Returns:
(N, 3) vertices using LBS algorithm: Skinning with dual quaternions, Kavan, 2007
"""
J = matrix_local.shape[0]
N = vertices.shape[0]
assert_ndarray(vertices, name='vertices', shape=(N, 3))
assert_ndarray(matrix_local, name="matrix_local", shape=(J, 4, 4))
assert_ndarray(matrix, name="matrix", shape=(J, 4, 4))
assert_ndarray(skin, name="skin", shape=(N, J))
assert vertices.shape[-1] + pad == 4
# (4, N)
padded = np.pad(vertices, ((0, 0), (0, pad)), 'constant', constant_values=(0, value)).T
# (J, 4, 4)
trans = matrix @ np.linalg.inv(matrix_local)
weighted_per_bone_matrix = []
# (J, N)
mask = (skin > 0).T
for i in range(J):
offset = np.zeros((4, N), dtype=np.float32)
offset[:, mask[i]] = (trans[i] @ padded[:, mask[i]]) * skin.T[i, mask[i]]
weighted_per_bone_matrix.append(offset)
weighted_per_bone_matrix = np.stack(weighted_per_bone_matrix)
g = np.sum(weighted_per_bone_matrix, axis=0)
final = g[:3, :] / (np.sum(skin, axis=1) + 1e-8)
return final.T
def axis_angle_to_matrix(axis_angle: ndarray) -> ndarray:
"""
Turn axis angle representation to matrix representation.
"""
res = np.pad(scipy.spatial.transform.Rotation.from_rotvec(axis_angle).as_matrix(), ((0, 0), (0, 1), (0, 1)), 'constant', constant_values=((0, 0), (0, 0), (0, 0)))
assert res.ndim == 3
res[:, -1, -1] = 1
return res
def sample_surface(
num_samples: int,
vertices: ndarray,
faces: ndarray,
mask: Optional[ndarray]=None,
) -> Tuple[ndarray, ndarray, ndarray]:
'''
Randomly pick samples proportional to face area.
See sample_surface: https://github.com/mikedh/trimesh/blob/main/trimesh/sample.py
Args:
mask: (num_faces,), only sample points on the faces where value is True.
Return:
vertex_samples: sampled vertices
original_face_index: on which face is sampled
random_lengths: sampled vectors on face
'''
original_face_indices = np.arange(len(faces))
# sample according to mask
if mask is not None:
assert_ndarray(arr=mask, name="mask", shape=(faces.shape[0],))
original_face_indices = original_face_indices[mask]
faces = faces[mask]
# get face area
offset_0 = vertices[faces[:, 1]] - vertices[faces[:, 0]]
offset_1 = vertices[faces[:, 2]] - vertices[faces[:, 0]]
# TODO: change to correct uniform sampling...
face_weight = np.linalg.norm(np.cross(offset_0, offset_1, axis=-1), axis=-1)
weight_cum = np.cumsum(face_weight, axis=0)
face_pick = np.random.rand(num_samples) * weight_cum[-1]
face_index = np.searchsorted(weight_cum, face_pick)
# face_weight = np.cross(offset_0, offset_1, axis=-1)
# face_weight = (face_weight * face_weight).sum(axis=1)
# weight_cum = np.cumsum(face_weight, axis=0)
# face_pick = np.random.rand(num_samples) * weight_cum[-1]
# face_index = np.searchsorted(weight_cum, face_pick)
# map face_index back to original indices
original_face_index = original_face_indices[face_index]
# pull triangles into the form of an origin + 2 vectors
tri_origins = vertices[faces[:, 0]]
tri_vectors = vertices[faces[:, 1:]]
tri_vectors -= np.tile(tri_origins, (1, 2)).reshape((-1, 2, 3))
# pull the vectors for the faces we are going to sample from
tri_origins = tri_origins[face_index]
tri_vectors = tri_vectors[face_index]
# randomly generate two 0-1 scalar components to multiply edge vectors b
random_lengths = np.random.rand(len(tri_vectors), 2, 1)
random_test = random_lengths.sum(axis=1).reshape(-1) > 1.0
random_lengths[random_test] -= 1.0
random_lengths = np.abs(random_lengths)
sample_vector = (tri_vectors * random_lengths).sum(axis=1)
vertex_samples = sample_vector + tri_origins
return vertex_samples, original_face_index, random_lengths
def sample_barycentric(
vertex_group: ndarray,
faces: ndarray,
face_index: ndarray,
random_lengths: ndarray,
) -> ndarray:
v_origins = vertex_group[faces[face_index, 0]]
v_vectors = vertex_group[faces[face_index, 1:]]
v_vectors -= v_origins[:, np.newaxis, :]
sample_vector = (v_vectors * random_lengths).sum(axis=1)
v_samples = sample_vector + v_origins
return v_samples
def sample_vertex_groups(
vertices: ndarray,
faces: ndarray,
num_samples: int,
num_vertex_samples: Optional[int]=None,
vertex_normals: Optional[ndarray]=None,
face_normals: Optional[ndarray]=None,
vertex_groups: Optional[ndarray]=None,
face_mask: Optional[ndarray]=None,
shuffle: bool=True,
same: bool=False,
) -> Tuple[ndarray, ndarray|None, ndarray|None]:
"""
Choose num_samples samples on the mesh and get their positions and normals.
If vertex_group is provided, get its weights using barycentric sampling.
Return:
sampled_vertices, sampled_normals, sampled_vertex_groups
Args:
vertices: (N, 3)
faces: (F, 3)
num_samples: how many samples
num_vertex_samples:
At most num_vertex_samples unique vertices to be included,
these points will be concatenated in the last (if shuffle is False).
vertex_normals: (N, 3), sampled_normals will be None if not provided
face_normals: (N, 3), sampled_normals will be None if not provided
vertex_groups: (N, m), sampled_vertex_groups will be None if not provided
face_mask:
(F,) or (F, m), if shape is (F,), use the same mask across all
vertex groups. Only sample on faces where value is True.
shuffle: shuffle samples in the end
same:
Sample on the same locations, only useful when using mutiple
vertex groups and mask is None or shape of (F,).
"""
if num_vertex_samples is None:
num_vertex_samples = 0
if num_vertex_samples > num_samples:
raise ValueError(f"num_vertex_samples cannot be larger than num_samples, found: {num_vertex_samples} > {num_samples}")
def get_mask_perm(mask: Optional[ndarray]):
if mask is None:
vertex_mask = np.arange(vertices.shape[0])
else:
vertex_mask = np.unique(mask)
perm = np.random.permutation(vertex_mask.shape[0])
return vertex_mask[perm[:num_vertex_samples]]
if vertex_groups is not None:
if vertex_groups.ndim == 1:
assert_ndarray(arr=vertex_groups, name="vertex_groups", shape=(vertices.shape[0],))
vertex_groups = vertex_groups[:, None]
else:
assert_ndarray(arr=vertex_groups, name="vertex_groups", shape=(vertices.shape[0], -1))
vertex_groups = vertex_groups
if vertex_groups is not None:
if face_mask is not None:
if face_mask.ndim == 1:
assert_ndarray(arr=face_mask, name="mask", shape=(faces.shape[0],))
else:
assert_ndarray(arr=face_mask, name="mask", shape=(faces.shape[0], vertex_groups.shape[1]))
list_sampled_vertices = []
list_sampled_normals = []
list_sampled_vertex_groups = []
perm = None
_mask = None
same = same and (face_mask is None or (face_mask is not None and face_mask.ndim != 2))
for i in range(vertex_groups.shape[1]):
if face_mask is not None:
if face_mask.ndim == 1:
perm = get_mask_perm(faces[face_mask])
_mask = face_mask
else:
perm = get_mask_perm(faces[face_mask[:, i]])
_mask = face_mask[:, i]
else:
perm = get_mask_perm(None)
_mask = None
_num_samples = num_samples - len(perm)
face_vertices, face_index, random_lengths = sample_surface(
num_samples=_num_samples,
vertices=vertices,
faces=faces,
mask=_mask,
)
list_sampled_vertices.append(np.concatenate([vertices[perm], face_vertices], axis=0))
if vertex_normals is not None and face_normals is not None:
list_sampled_normals.append(np.concatenate([vertex_normals[perm], face_normals[face_index]], axis=0))
if same:
g = sample_barycentric(
vertex_group=vertex_groups,
faces=faces,
face_index=face_index,
random_lengths=random_lengths,
)
list_sampled_vertex_groups.append(np.concatenate([vertex_groups[perm], g], axis=0))
break
g = sample_barycentric(
vertex_group=vertex_groups[:, i:i+1],
faces=faces,
face_index=face_index,
random_lengths=random_lengths,
)[:, 0]
list_sampled_vertex_groups.append(np.concatenate([vertex_groups[:, i][perm], g], axis=0))
sampled_vertices = np.stack(list_sampled_vertices, axis=1)
if len(list_sampled_normals) > 0:
sampled_normals = np.stack(list_sampled_normals, axis=1)
else:
sampled_normals = None
if same:
sampled_vertex_groups = list_sampled_vertex_groups[0]
else:
sampled_vertex_groups = np.stack(list_sampled_vertex_groups, axis=1)
else: # otherwise only sample vertices and normals
if face_mask is not None:
assert_ndarray(arr=face_mask, name="mask", shape=(faces.shape[0],))
perm = get_mask_perm(faces[face_mask])
else:
perm = get_mask_perm(None)
num_samples -= len(perm)
n_vertex = vertices[perm]
face_vertices, face_index, random_lengths = sample_surface(
num_samples=num_samples,
vertices=vertices,
faces=faces,
mask=face_mask,
)
sampled_vertices = np.concatenate([n_vertex, face_vertices], axis=0)
if vertex_normals is not None and face_normals is not None:
sampled_normals = np.concatenate([vertex_normals[perm], face_normals[face_index]], axis=0)
else:
sampled_normals = None
sampled_vertex_groups = None
return sampled_vertices, sampled_normals, sampled_vertex_groups

View file

View file

@ -0,0 +1,92 @@
from bottle import request, response
import bottle
import os
import queue
import threading
import traceback
from .spec import bytes_to_object, object_to_bytes, BPY_PORT
from ..rig_package.parser.bpy import BpyParser, transfer_rigging
def _resolve_payload(data):
if isinstance(data, dict) and "payload_path" in data:
payload_path = data["payload_path"]
try:
with open(payload_path, "rb") as f:
return bytes_to_object(f.read())
finally:
try:
os.remove(payload_path)
except OSError:
pass
return data
def run():
path_queue = queue.Queue()
result_queue = queue.Queue()
app = bottle.Bottle()
@app.route('/load', method='GET') # type: ignore
def load():
data = request.body.read() # type: ignore
path_queue.put(('load', data))
res = result_queue.get()
payload = object_to_bytes(res)
response.content_type = 'application/octet-stream' # type: ignore
return payload
@app.route('/ping', method='GET') # type: ignore
def ping():
return 'pong'
@app.route('/export', method='post') # type: ignore
def export():
data = request.body.read() # type: ignore
path_queue.put(('export', data))
res = result_queue.get()
payload = object_to_bytes(res)
response.content_type = 'application/octet-stream' # type: ignore
return payload
@app.route('/transfer', method='post') # type: ignore
def transfer():
data = request.body.read() # type: ignore
path_queue.put(('transfer', data))
res = result_queue.get()
payload = object_to_bytes(res)
response.content_type = 'application/octet-stream' # type: ignore
return payload
def run_server(): bottle.run(app, host='0.0.0.0', port=BPY_PORT, server='tornado')
threading.Thread(target=run_server, daemon=False).start()
while True:
d = path_queue.get()
op = d[0]
try:
data = _resolve_payload(bytes_to_object(d[1]))
if op == 'load':
print("[SERVER] received load path:", data)
asset = BpyParser.load(data)
result_queue.put(asset)
elif op == 'export':
print("[SERVER] received export path:", data['filepath'])
BpyParser.export(**data)
result_queue.put('ok')
elif op == 'transfer':
print("[SERVER] received transfer path:", data['target_path'])
transfer_rigging(**data)
result_queue.put('ok')
else:
result_queue.put(f"unsupported op: {str(op)}")
except Exception as e:
tb = traceback.format_exc()
print(tb)
result_queue.put({
"error": f"{type(e).__name__}: {e}",
"traceback": tb,
})

View file

@ -0,0 +1,85 @@
from dataclasses import dataclass
from torch import Tensor
from typing import Dict, Optional, List, Tuple
import io
import os
import torch
from ..rig_package.info.asset import Asset
from ..model.tokenrig import TokenRig
PORT = 59875
SERVER = f"http://localhost:{PORT}"
TMP_CKPT_DIR = "./tmp_ckpt"
BPY_PORT = 59876
BPY_SERVER = f"http://localhost:{BPY_PORT}"
@dataclass
class TensorPacket:
"""make sure stays on cpu"""
validate: bool=False
know_skeleton: bool=False
learned_mesh_cond: Optional[Tensor]=None
cond_latents: Optional[Tensor]=None
mesh_cond: Optional[Tensor]=None
vertices: Optional[Tensor]=None
assets: Optional[List[Asset]]=None
output_ids: Optional[Tensor]=None
start_embed_list: Optional[List[Tensor]]=None
start_tokens_list: Optional[List[List[int]]]=None
def to_device(self, device):
if self.learned_mesh_cond is not None:
self.learned_mesh_cond = self.learned_mesh_cond.to(device)
if self.cond_latents is not None:
self.cond_latents = self.cond_latents.to(device)
if self.mesh_cond is not None:
self.mesh_cond = self.mesh_cond.to(device)
if self.vertices is not None:
self.vertices = self.vertices.to(device)
if self.output_ids is not None:
self.output_ids = self.output_ids.to(device)
if self.start_embed_list is not None:
self.start_embed_list = [x.to(device) for x in self.start_embed_list]
@property
def B(self):
assert self.learned_mesh_cond is not None
return self.learned_mesh_cond.shape[0]
def to_bytes(self):
return object_to_bytes(self)
@classmethod
def from_bytes(cls, bytes) -> 'TensorPacket':
return bytes_to_object(bytes)
def object_to_bytes(t):
buffer = io.BytesIO()
torch.save(t, buffer)
return buffer.getvalue()
def bytes_to_object(b, map_location=None):
return torch.load(io.BytesIO(b), weights_only=False, map_location=map_location)
def get_model(
ckpt_path: str,
hf_path: Optional[str]=None,
device='cuda',
) -> TokenRig:
model = TokenRig.load_from_system_checkpoint(checkpoint_path=ckpt_path)
if hf_path is not None:
from transformers import AutoModel
a = AutoModel.from_pretrained(
hf_path,
local_files_only=True,
_attn_implementation="flash_attention_2",
torch_dtype=torch.bfloat16,
)
model.transformer.model.load_state_dict(a.state_dict())
model = model.to(device)
return model

View file

View file

@ -0,0 +1,13 @@
from copy import deepcopy
from .spec import Tokenizer
from .tokenizer_part import TokenizerPart
def get_tokenizer(**kwargs) -> Tokenizer:
__target__ = kwargs.get('__target__')
assert __target__ is not None, "do not find `__target__` in tokenizer config"
del kwargs['__target__']
MAP = {
'tokenizer_part': TokenizerPart,
}
return MAP[__target__].parse(**deepcopy(kwargs))

View file

@ -0,0 +1,267 @@
from abc import ABC, abstractmethod
from collections import defaultdict
from typing import Dict
import numpy as np
from numpy import ndarray
from typing import Union, List, Tuple, Optional
from dataclasses import dataclass
@dataclass
class TokenizeInput():
# (J, 3)
joints: ndarray
# (J)
parents: List[Union[None, int]]
# string of class in tokenizer
cls: Optional[str]=None
joint_names: Optional[List[str]]=None
@property
def J(self) -> int:
return self.joints.shape[0]
@property
def branch(self) -> ndarray:
if not hasattr(self, '_branch'):
branch = []
last = None
for i in range(self.J):
if i == 0:
branch.append(False)
else:
pid = self.parents[i]
branch.append(pid!=last)
last = i
self._branch = np.array(branch, dtype=bool)
return self._branch
@property
def bones(self):
_p = self.parents.copy()
_p[0] = 0
return np.concatenate([self.joints[_p], self.joints], axis=1)
@property
def num_bones(self):
return self.bones.shape[0]
@dataclass
class DetokenizeOutput():
# original tokens
tokens: ndarray
# (J, 6), (parent position, position)
bones: ndarray
# (J), parent of each bone
parents: List[int]
# string of class in tokenizer
cls: Optional[str]=None
# names of joints
joint_names: Optional[List[str]]=None
continuous_range: Optional[Tuple[float, float]]=None
@property
def joints(self):
return self.bones[:, 3:]
@property
def p_joints(self):
return self.bones[:, :3]
@property
def num_bones(self):
return self.bones.shape[0]
@property
def J(self):
return self.bones.shape[0]
def _get_parents(self) -> List[int]:
parents = []
for (i, bone) in enumerate(self.bones):
p_joint = bone[:3]
dis = 999999
pid = -1
for j in reversed(range(i)):
n_dis = ((self.bones[j][3:] - p_joint)**2).sum()
if n_dis < dis:
pid = j
dis = n_dis
parents.append(pid)
return parents
class Tokenizer(ABC):
"""
Abstract class for tokenizer
"""
@classmethod
@abstractmethod
def parse(cls, **kwags) -> 'Tokenizer':
pass
@abstractmethod
def tokenize(self, input: TokenizeInput) -> ndarray:
pass
@abstractmethod
def detokenize(self, ids: ndarray, **kwargs) -> DetokenizeOutput:
pass
@property
@abstractmethod
def vocab_size(self) -> int:
"""The vocabulary size"""
raise NotImplementedError()
@property
def pad(self):
raise NotImplementedError("{} has no attribute 'pad'".format(type(self).__name__))
@property
def bos(self):
raise NotImplementedError("{} has no attribute 'bos'".format(type(self).__name__))
@property
def eos(self):
raise NotImplementedError("{} has no attribute 'eos'".format(type(self).__name__))
def cls_name_to_token(self, cls: str) -> int:
raise NotImplementedError()
def next_posible_token(self, ids: ndarray) -> List[int]:
raise NotImplementedError()
def bones_in_sequence(self, ids: ndarray) -> int:
raise NotImplementedError()
def make_cls_head(self, **kwargs) -> List[int]:
raise NotImplementedError()
def make_skeleton(
joints: ndarray,
p_joints: ndarray,
tails_dict: Dict[int, ndarray],
convert_leaf_bones_to_tails: bool,
extrude_tail_for_leaf: bool,
extrude_tail_for_branch: bool,
extrude_scale: float=0.5,
strict: bool=False,
) -> Tuple[ndarray, ndarray, List[int], List[int]]:
'''
Args:
joints: heads of bones
p_joints: parent position of joints
tails_dict: tail position of the i-th joint
convert_leaf_bones_to_tails: remove leaf bones and make them tails of their parents
extrude_tail_for_leaf: add a tail for leaf bone
extrude_tail_for_branch: add a tail for joint with multiple children
extrude_scale: length scale of tail offset
strict: if true, raise error when there are joints in the same location
Returns:
bones, tails, available_bones_id, parents
'''
assert (convert_leaf_bones_to_tails & extrude_tail_for_leaf)==False, 'cannot extrude tail for leaf when convert_leaf_bones_to_tails is True'
assert joints.shape[0] == p_joints.shape[0]
# build parents
bones = [] # (parent_position, position)
parents = []
for (i, joint) in enumerate(joints):
if len(bones) == 0:
bones.append(np.concatenate([joint, joint])) # root
parents.append(-1)
continue
p_joint = p_joints[i]
dis = 999999
pid = None
for j in reversed(range(i)):
n_dis = ((bones[j][3:] - p_joint)**2).sum()
if n_dis < dis:
pid = j
dis = n_dis
bones.append(np.concatenate([joints[pid], joint]))
parents.append(pid)
bones = np.stack(bones)
children = defaultdict(list)
for (i, pid) in enumerate(parents):
if pid == -1:
continue
children[pid].append(i)
available_bones_id = []
if convert_leaf_bones_to_tails:
for (i, pid) in enumerate(parents):
if len(children[i]) != 0:
available_bones_id.append(i)
continue
tails_dict[pid] = bones[i, 3:]
else:
available_bones_id = [i for i in range(bones.shape[0])]
# tail for leaf
for (i, pid) in enumerate(parents):
if len(children[i]) != 0:
continue
if extrude_tail_for_leaf:
d = bones[i, 3:] - bones[pid, 3:]
length = np.linalg.norm(d)
if strict:
assert length > 1e-9, 'two joints in the same point found'
elif length <= 1e-9:
d = np.array([0., 0., 1.])
tails_dict[i] = bones[i, 3:] + d * extrude_scale
else:
tails_dict[i] = bones[i, 3:]
# tail for branch
for (i, pid) in enumerate(parents):
if len(children[i]) <= 1:
continue
if extrude_tail_for_branch:
if pid == -1: # root
av_len = 0
for child in children[i]:
av_len += np.linalg.norm(bones[i, 3:] - bones[child, 3:])
av_len /= len(children[i])
d = bones[i, 3:] + np.array([0., 0., extrude_scale * av_len])
else:
d = bones[i, 3:] - bones[pid, 3:]
length = np.linalg.norm(d)
if strict:
assert length > 1e-9, 'two joints in the same point found'
elif length <= 1e-9:
d = np.array([0., 0., 1.])
tails_dict[i] = bones[i, 3:] + d * extrude_scale
else:
tails_dict[i] = bones[i, 3:]
# assign new tail
for (i, pid) in enumerate(parents):
if len(children[i]) != 1:
continue
child = children[i][0]
tails_dict[i] = bones[child, 3:]
tails = []
for i in range(bones.shape[0]):
tails.append(tails_dict[i])
tails = np.stack(tails)
return bones, tails, available_bones_id, parents

View file

@ -0,0 +1,410 @@
from dataclasses import dataclass, field
from numpy import ndarray
from typing import Dict, Tuple, Union, List, Optional
import numpy as np
from .spec import Tokenizer, TokenizeInput, DetokenizeOutput
from .spec import make_skeleton
from ..data.order import Order
@dataclass
class TokenizerPart(Tokenizer):
# cls token id
cls_token_id: Dict[str, int]
# parts token id
parts_token_id: Dict[str, int]
part_token_to_name: Dict[int, str]
cls_token_to_name: Dict[int, str]
parts_token_id_name: List[str]
# normalization range
continuous_range: Tuple[float, float]
# coordinate discrete
num_discrete: int
token_id_branch: int
token_id_bos: int
token_id_eos: int
token_id_pad: int
token_id_spring: int
token_id_cls_none: int
_vocab_size: int
order: Optional[Order]=None
@classmethod
def parse(
cls,
**kwargs,
):
num_discrete = kwargs.pop('num_discrete')
continuous_range = kwargs.pop('continuous_range')
cls_token_id = kwargs.pop('cls_token_id')
parts_token_id = kwargs.pop('parts_token_id')
order = kwargs.get('order')
if order is not None:
assert isinstance(order, Order)
_offset = num_discrete
token_id_branch = _offset + 0
token_id_bos = _offset + 1
token_id_eos = _offset + 2
token_id_pad = _offset + 3
_offset += 4
token_id_spring = _offset + 0
_offset += 1
assert None not in parts_token_id
for i in parts_token_id:
parts_token_id[i] += _offset
_offset += len(parts_token_id)
token_id_cls_none = _offset + 0
_offset += 1
for i in cls_token_id:
cls_token_id[i] += _offset
_offset += len(cls_token_id)
_vocab_size = _offset
parts_token_id_name = [x for x in parts_token_id]
part_token_to_name = {v: k for k, v in parts_token_id.items()}
assert len(part_token_to_name) == len(parts_token_id), 'names with same token found in parts_token_id'
part_token_to_name[token_id_spring] = None
cls_token_to_name = {v: k for k, v in cls_token_id.items()}
assert len(cls_token_to_name) == len(cls_token_id), 'names with same token found in cls_token_id'
return TokenizerPart(
num_discrete=num_discrete,
continuous_range=continuous_range,
cls_token_id=cls_token_id,
parts_token_id=parts_token_id,
order=order,
token_id_branch=token_id_branch,
token_id_bos=token_id_bos,
token_id_eos=token_id_eos,
token_id_pad=token_id_pad,
token_id_spring=token_id_spring,
token_id_cls_none=token_id_cls_none,
parts_token_id_name=parts_token_id_name,
part_token_to_name=part_token_to_name,
cls_token_to_name=cls_token_to_name,
_vocab_size=_vocab_size,
)
def make_cls_head(self, **kwargs) -> List[int]:
cls = kwargs.get('cls', None)
if cls is not None:
return [self.cls_name_to_token(cls=cls)]
return [self.token_id_cls_none]
def cls_name_to_token(self, cls: str) -> int:
if cls not in self.cls_token_id:
return self.token_id_cls_none
return self.cls_token_id[cls]
def part_name_to_token(self, part: str) -> int:
assert part in self.parts_token_id, f"do not find part name `{part}` in tokenizer"
return self.parts_token_id[part]
def next_posible_token(self, ids: ndarray) -> List[int]:
if ids.shape[0] == 0 or ids.ndim == 0:
return [self.token_id_bos]
assert ids.ndim == 1, "expect an array"
state = 'expect_bos'
for id in ids:
if state == 'expect_bos':
assert id == self.token_id_bos, 'ids do not start with bos'
state = 'expect_cls_or_part_or_joint'
elif state == 'expect_cls_or_part_or_joint':
if id < self.num_discrete:
state = 'expect_joint_2'
elif id == self.token_id_cls_none or id in self.cls_token_id.values():
state = 'expect_part_or_joint'
else: # a part
state = 'expect_joint'
elif state == 'expect_part_or_joint':
if id < self.num_discrete:
state = 'expect_joint_2'
else:
state = 'expect_part_or_joint'
elif state == 'expect_joint_2':
state = 'expect_joint_3'
elif state == 'expect_joint_3':
state = 'expect_branch_or_part_or_joint'
elif state == 'expect_branch_or_part_or_joint':
if id == self.token_id_branch:
state = 'expect_joint'
elif id < self.num_discrete:
state = 'expect_joint_2'
else: # find a part
state = 'expect_joint'
elif state == 'expect_joint':
state = 'expect_joint_2'
else:
assert 0, state
s = []
def add_cls():
s.append(self.token_id_cls_none)
for v in self.cls_token_id.values():
s.append(v)
def add_part():
s.append(self.token_id_spring)
for v in self.parts_token_id.values():
s.append(v)
def add_joint():
for i in range(self.num_discrete):
s.append(i)
def add_branch():
s.append(self.token_id_branch)
def add_eos():
s.append(self.token_id_eos)
def add_bos():
s.append(self.token_id_bos)
if state == 'expect_bos':
add_bos()
elif state == 'expect_cls_or_part_or_joint':
add_cls()
add_part()
add_joint()
elif state == 'expect_cls':
add_cls()
elif state == 'expect_part_or_joint':
add_part()
add_joint()
add_eos()
elif state == 'expect_joint_2':
add_joint()
elif state == 'expect_joint_3':
add_joint()
elif state == 'expect_branch_or_part_or_joint':
add_joint()
add_part()
add_branch()
add_eos()
elif state == 'expect_joint':
add_joint()
else:
assert 0, state
return s
def bones_in_sequence(self, ids: ndarray):
assert ids.ndim == 1, "expect an array"
s = 0
is_branch = False
state = 'expect_bos'
for id in ids:
if state == 'expect_bos':
assert id == self.token_id_bos, 'ids do not start with bos'
state = 'expect_cls_or_part_or_joint'
elif state == 'expect_cls_or_part_or_joint':
if id < self.num_discrete:
state = 'expect_joint_2'
elif id == self.token_id_cls_none or id in self.cls_token_id.values():
state = 'expect_part_or_joint'
else: # a part
state = 'expect_joint'
elif state == 'expect_part_or_joint':
if id < self.num_discrete:
state = 'expect_joint_2'
else:
state = 'expect_part_or_joint'
elif state == 'expect_joint_2':
state = 'expect_joint_3'
elif state == 'expect_joint_3':
if not is_branch:
s += 1
is_branch = False
state = 'expect_branch_or_part_or_joint'
elif state == 'expect_branch_or_part_or_joint':
if id == self.token_id_branch:
state = 'expect_joint'
is_branch = True
elif id < self.num_discrete:
state = 'expect_joint_2'
else: # find a part
state = 'expect_joint'
elif state == 'expect_joint':
state = 'expect_joint_2'
else:
assert 0, state
if id == self.token_id_eos:
break
return s
def tokenize(self, input: TokenizeInput) -> ndarray:
num_bones = input.num_bones
bones = discretize(t=input.bones, continuous_range=self.continuous_range, num_discrete=self.num_discrete)
branch = input.branch
tokens = [self.token_id_bos]
if input.cls is None or input.cls not in self.cls_token_id:
tokens.append(self.token_id_cls_none)
else:
tokens.append(self.cls_token_id[input.cls])
if self.order is not None and input.cls is not None and input.joint_names is not None:
_, parts_bias = self.order.arrange_names(cls=input.cls, names=input.joint_names, parents=input.parents)
else:
parts_bias = []
for i in range(num_bones):
# add parts token id
if i in parts_bias:
part = parts_bias[i]
if part is None:
tokens.append(self.token_id_spring)
else:
assert part in self.parts_token_id, f"do not find part name {part} in tokenizer {self.__class__}"
tokens.append(self.parts_token_id[part])
if branch[i]:
tokens.append(self.token_id_branch)
tokens.append(bones[i, 0])
tokens.append(bones[i, 1])
tokens.append(bones[i, 2])
tokens.append(bones[i, 3])
tokens.append(bones[i, 4])
tokens.append(bones[i, 5])
else:
tokens.append(bones[i, 3])
tokens.append(bones[i, 4])
tokens.append(bones[i, 5])
tokens.append(self.token_id_eos)
return np.array(tokens, dtype=np.int64)
def detokenize(self, ids: ndarray, **kwargs) -> DetokenizeOutput:
assert isinstance(ids, ndarray), 'expect ids to be ndarray'
if ids[0] != self.token_id_bos:
raise ValueError(f"first token is not bos")
trailing_pad = 0
while trailing_pad < ids.shape[0] and ids[-trailing_pad-1] == self.token_id_pad:
trailing_pad += 1
if ids[-1-trailing_pad] != self.token_id_eos:
raise ValueError(f"last token is not eos")
ids = ids[1:-1-trailing_pad]
joints = []
p_joints = []
tails_dict = {}
parts = []
i = 0
is_branch = False
last_joint = None
num_bones = 0
cls = None
while i < len(ids):
if ids[i] < self.num_discrete:
if is_branch:
p_joint = undiscretize(t=ids[i:i+3], continuous_range=self.continuous_range, num_discrete=self.num_discrete)
current_joint = undiscretize(t=ids[i+3:i+6], continuous_range=self.continuous_range, num_discrete=self.num_discrete)
joints.append(current_joint)
p_joints.append(p_joint)
i += 6
else:
current_joint = undiscretize(t=ids[i:i+3], continuous_range=self.continuous_range, num_discrete=self.num_discrete)
joints.append(current_joint)
if len(p_joints) == 0: # root
p_joints.append(current_joint)
p_joint = current_joint
else:
assert last_joint is not None
p_joints.append(last_joint)
p_joint = last_joint
i += 3
if last_joint is not None:
tails_dict[num_bones-1] = current_joint
last_joint = current_joint
num_bones += 1
is_branch = False
elif ids[i]==self.token_id_branch:
is_branch = True
last_joint = None
i += 1
elif ids[i]==self.token_id_spring or ids[i] in self.parts_token_id.values():
parts.append(self.part_token_to_name[ids[i]])
i += 1
elif ids[i] in self.cls_token_id.values():
cls = ids[i]
i += 1
elif ids[i] == self.token_id_cls_none:
cls = None
i += 1
else:
raise ValueError(f"unexpected token found: {ids[i]}")
joints = np.stack(joints)
p_joints = np.stack(p_joints)
# leaf is ignored in this tokenizer so need to extrude tails for leaf and branch
bones, tails, available_bones_id, parents = make_skeleton(
joints=joints,
p_joints=p_joints,
tails_dict=tails_dict,
convert_leaf_bones_to_tails=False,
extrude_tail_for_leaf=True,
extrude_tail_for_branch=True,
)
bones = bones[available_bones_id]
tails = tails[available_bones_id]
if cls in self.cls_token_to_name:
cls = self.cls_token_to_name[cls]
else:
cls = None
if self.order is not None:
joint_names = self.order.make_names(cls=cls, parts=parts, num_bones=num_bones)
else:
joint_names = [f"bone_{i}" for i in range(num_bones)]
return DetokenizeOutput(
tokens=ids,
bones=bones,
parents=parents,
cls=cls,
joint_names=joint_names,
continuous_range=self.continuous_range,
)
def get_require_parts(self) -> List[str]:
return self.parts_token_id_name
@property
def vocab_size(self):
return self._vocab_size
@property
def pad(self):
return self.token_id_pad
@property
def bos(self):
return self.token_id_bos
@property
def eos(self):
return self.token_id_eos
def discretize(
t: ndarray,
continuous_range: Tuple[float, float],
num_discrete: int,
) -> ndarray:
lo, hi = continuous_range
assert hi >= lo
t = (t - lo) / (hi - lo)
t *= num_discrete
return np.clip(t.round(), 0, num_discrete - 1).astype(np.int64)
def undiscretize(
t: ndarray,
continuous_range: Tuple[float, float],
num_discrete: int,
) -> ndarray:
lo, hi = continuous_range
assert hi >= lo
t = t.astype(np.float32) + 0.5
t /= num_discrete
return t * (hi - lo) + lo