Spaces:
Build error
Build error
Commit ·
bf912fe
0
Parent(s):
Upload demo
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +8 -0
- .gitignore +9 -0
- LICENSE +21 -0
- README.md +10 -0
- TRELLIS/.gitignore +405 -0
- TRELLIS/.gitmodules +3 -0
- TRELLIS/extensions/vox2seq/benchmark.py +45 -0
- TRELLIS/extensions/vox2seq/setup.py +34 -0
- TRELLIS/extensions/vox2seq/src/api.cu +92 -0
- TRELLIS/extensions/vox2seq/src/api.h +76 -0
- TRELLIS/extensions/vox2seq/src/ext.cpp +10 -0
- TRELLIS/extensions/vox2seq/src/hilbert.cu +133 -0
- TRELLIS/extensions/vox2seq/src/hilbert.h +35 -0
- TRELLIS/extensions/vox2seq/src/z_order.cu +66 -0
- TRELLIS/extensions/vox2seq/src/z_order.h +35 -0
- TRELLIS/extensions/vox2seq/test.py +25 -0
- TRELLIS/extensions/vox2seq/vox2seq/__init__.py +50 -0
- TRELLIS/extensions/vox2seq/vox2seq/pytorch/__init__.py +48 -0
- TRELLIS/extensions/vox2seq/vox2seq/pytorch/default.py +59 -0
- TRELLIS/extensions/vox2seq/vox2seq/pytorch/hilbert.py +303 -0
- TRELLIS/extensions/vox2seq/vox2seq/pytorch/z_order.py +126 -0
- TRELLIS/network/__init__.py +104 -0
- TRELLIS/network/hash_grid.py +131 -0
- TRELLIS/network/loss.py +38 -0
- TRELLIS/network/mlp.py +34 -0
- TRELLIS/network/tcnn.py +91 -0
- TRELLIS/setup.sh +250 -0
- TRELLIS/trellis/__init__.py +6 -0
- TRELLIS/trellis/models/__init__.py +70 -0
- TRELLIS/trellis/models/sparse_structure_flow.py +200 -0
- TRELLIS/trellis/models/sparse_structure_vae.py +306 -0
- TRELLIS/trellis/models/structured_latent_flow.py +262 -0
- TRELLIS/trellis/models/structured_latent_vae/__init__.py +4 -0
- TRELLIS/trellis/models/structured_latent_vae/base.py +117 -0
- TRELLIS/trellis/models/structured_latent_vae/decoder_gs.py +124 -0
- TRELLIS/trellis/models/structured_latent_vae/decoder_mesh.py +189 -0
- TRELLIS/trellis/models/structured_latent_vae/decoder_rf.py +104 -0
- TRELLIS/trellis/models/structured_latent_vae/encoder.py +72 -0
- TRELLIS/trellis/modules/attention/__init__.py +36 -0
- TRELLIS/trellis/modules/attention/full_attn.py +140 -0
- TRELLIS/trellis/modules/attention/modules.py +146 -0
- TRELLIS/trellis/modules/norm.py +25 -0
- TRELLIS/trellis/modules/sparse/__init__.py +102 -0
- TRELLIS/trellis/modules/sparse/attention/__init__.py +4 -0
- TRELLIS/trellis/modules/sparse/attention/full_attn.py +215 -0
- TRELLIS/trellis/modules/sparse/attention/modules.py +139 -0
- TRELLIS/trellis/modules/sparse/attention/serialized_attn.py +193 -0
- TRELLIS/trellis/modules/sparse/attention/windowed_attn.py +135 -0
- TRELLIS/trellis/modules/sparse/basic.py +459 -0
- TRELLIS/trellis/modules/sparse/conv/__init__.py +21 -0
.gitattributes
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.exr filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.png filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.jpg filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.jpeg filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.gif filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.webp filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.glb filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.whl filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.pyc
|
| 2 |
+
*.zip
|
| 3 |
+
*.pth
|
| 4 |
+
*.ckpt
|
| 5 |
+
|
| 6 |
+
tmp/
|
| 7 |
+
debug/
|
| 8 |
+
outputs/
|
| 9 |
+
evaluations/
|
LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2025 CzzzzH
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
README.md
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: FreeArt3D
|
| 3 |
+
emoji: 🧩
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: purple
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: "5.34.2"
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
---
|
TRELLIS/.gitignore
ADDED
|
@@ -0,0 +1,405 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## Ignore Visual Studio temporary files, build results, and
|
| 2 |
+
## files generated by popular Visual Studio add-ons.
|
| 3 |
+
##
|
| 4 |
+
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
|
| 5 |
+
|
| 6 |
+
# Extra
|
| 7 |
+
checkpoints/
|
| 8 |
+
dataset/
|
| 9 |
+
debug/
|
| 10 |
+
outputs/
|
| 11 |
+
old_code/
|
| 12 |
+
|
| 13 |
+
# User-specific files
|
| 14 |
+
*.rsuser
|
| 15 |
+
*.suo
|
| 16 |
+
*.user
|
| 17 |
+
*.userosscache
|
| 18 |
+
*.sln.docstates
|
| 19 |
+
|
| 20 |
+
# User-specific files (MonoDevelop/Xamarin Studio)
|
| 21 |
+
*.userprefs
|
| 22 |
+
|
| 23 |
+
# Mono auto generated files
|
| 24 |
+
mono_crash.*
|
| 25 |
+
|
| 26 |
+
# Build results
|
| 27 |
+
[Dd]ebug/
|
| 28 |
+
[Dd]ebugPublic/
|
| 29 |
+
[Rr]elease/
|
| 30 |
+
[Rr]eleases/
|
| 31 |
+
x64/
|
| 32 |
+
x86/
|
| 33 |
+
[Ww][Ii][Nn]32/
|
| 34 |
+
[Aa][Rr][Mm]/
|
| 35 |
+
[Aa][Rr][Mm]64/
|
| 36 |
+
bld/
|
| 37 |
+
[Bb]in/
|
| 38 |
+
[Oo]bj/
|
| 39 |
+
[Ll]og/
|
| 40 |
+
[Ll]ogs/
|
| 41 |
+
|
| 42 |
+
# Visual Studio 2015/2017 cache/options directory
|
| 43 |
+
.vs/
|
| 44 |
+
# Uncomment if you have tasks that create the project's static files in wwwroot
|
| 45 |
+
#wwwroot/
|
| 46 |
+
|
| 47 |
+
# Visual Studio 2017 auto generated files
|
| 48 |
+
Generated\ Files/
|
| 49 |
+
|
| 50 |
+
# MSTest test Results
|
| 51 |
+
[Tt]est[Rr]esult*/
|
| 52 |
+
[Bb]uild[Ll]og.*
|
| 53 |
+
|
| 54 |
+
# NUnit
|
| 55 |
+
*.VisualState.xml
|
| 56 |
+
TestResult.xml
|
| 57 |
+
nunit-*.xml
|
| 58 |
+
|
| 59 |
+
# Build Results of an ATL Project
|
| 60 |
+
[Dd]ebugPS/
|
| 61 |
+
[Rr]eleasePS/
|
| 62 |
+
dlldata.c
|
| 63 |
+
|
| 64 |
+
# Benchmark Results
|
| 65 |
+
BenchmarkDotNet.Artifacts/
|
| 66 |
+
|
| 67 |
+
# .NET Core
|
| 68 |
+
project.lock.json
|
| 69 |
+
project.fragment.lock.json
|
| 70 |
+
artifacts/
|
| 71 |
+
|
| 72 |
+
# ASP.NET Scaffolding
|
| 73 |
+
ScaffoldingReadMe.txt
|
| 74 |
+
|
| 75 |
+
# StyleCop
|
| 76 |
+
StyleCopReport.xml
|
| 77 |
+
|
| 78 |
+
# Files built by Visual Studio
|
| 79 |
+
*_i.c
|
| 80 |
+
*_p.c
|
| 81 |
+
*_h.h
|
| 82 |
+
*.ilk
|
| 83 |
+
*.meta
|
| 84 |
+
*.obj
|
| 85 |
+
*.iobj
|
| 86 |
+
*.pch
|
| 87 |
+
*.pdb
|
| 88 |
+
*.ipdb
|
| 89 |
+
*.pgc
|
| 90 |
+
*.pgd
|
| 91 |
+
*.rsp
|
| 92 |
+
*.sbr
|
| 93 |
+
*.tlb
|
| 94 |
+
*.tli
|
| 95 |
+
*.tlh
|
| 96 |
+
*.tmp
|
| 97 |
+
*.tmp_proj
|
| 98 |
+
*_wpftmp.csproj
|
| 99 |
+
*.log
|
| 100 |
+
*.tlog
|
| 101 |
+
*.vspscc
|
| 102 |
+
*.vssscc
|
| 103 |
+
.builds
|
| 104 |
+
*.pidb
|
| 105 |
+
*.svclog
|
| 106 |
+
*.scc
|
| 107 |
+
|
| 108 |
+
# Chutzpah Test files
|
| 109 |
+
_Chutzpah*
|
| 110 |
+
|
| 111 |
+
# Visual C++ cache files
|
| 112 |
+
ipch/
|
| 113 |
+
*.aps
|
| 114 |
+
*.ncb
|
| 115 |
+
*.opendb
|
| 116 |
+
*.opensdf
|
| 117 |
+
*.sdf
|
| 118 |
+
*.cachefile
|
| 119 |
+
*.VC.db
|
| 120 |
+
*.VC.VC.opendb
|
| 121 |
+
|
| 122 |
+
# Visual Studio profiler
|
| 123 |
+
*.psess
|
| 124 |
+
*.vsp
|
| 125 |
+
*.vspx
|
| 126 |
+
*.sap
|
| 127 |
+
|
| 128 |
+
# Visual Studio Trace Files
|
| 129 |
+
*.e2e
|
| 130 |
+
|
| 131 |
+
# TFS 2012 Local Workspace
|
| 132 |
+
$tf/
|
| 133 |
+
|
| 134 |
+
# Guidance Automation Toolkit
|
| 135 |
+
*.gpState
|
| 136 |
+
|
| 137 |
+
# ReSharper is a .NET coding add-in
|
| 138 |
+
_ReSharper*/
|
| 139 |
+
*.[Rr]e[Ss]harper
|
| 140 |
+
*.DotSettings.user
|
| 141 |
+
|
| 142 |
+
# TeamCity is a build add-in
|
| 143 |
+
_TeamCity*
|
| 144 |
+
|
| 145 |
+
# DotCover is a Code Coverage Tool
|
| 146 |
+
*.dotCover
|
| 147 |
+
|
| 148 |
+
# AxoCover is a Code Coverage Tool
|
| 149 |
+
.axoCover/*
|
| 150 |
+
!.axoCover/settings.json
|
| 151 |
+
|
| 152 |
+
# Coverlet is a free, cross platform Code Coverage Tool
|
| 153 |
+
coverage*.json
|
| 154 |
+
coverage*.xml
|
| 155 |
+
coverage*.info
|
| 156 |
+
|
| 157 |
+
# Visual Studio code coverage results
|
| 158 |
+
*.coverage
|
| 159 |
+
*.coveragexml
|
| 160 |
+
|
| 161 |
+
# NCrunch
|
| 162 |
+
_NCrunch_*
|
| 163 |
+
.*crunch*.local.xml
|
| 164 |
+
nCrunchTemp_*
|
| 165 |
+
|
| 166 |
+
# MightyMoose
|
| 167 |
+
*.mm.*
|
| 168 |
+
AutoTest.Net/
|
| 169 |
+
|
| 170 |
+
# Web workbench (sass)
|
| 171 |
+
.sass-cache/
|
| 172 |
+
|
| 173 |
+
# Installshield output folder
|
| 174 |
+
[Ee]xpress/
|
| 175 |
+
|
| 176 |
+
# DocProject is a documentation generator add-in
|
| 177 |
+
DocProject/buildhelp/
|
| 178 |
+
DocProject/Help/*.HxT
|
| 179 |
+
DocProject/Help/*.HxC
|
| 180 |
+
DocProject/Help/*.hhc
|
| 181 |
+
DocProject/Help/*.hhk
|
| 182 |
+
DocProject/Help/*.hhp
|
| 183 |
+
DocProject/Help/Html2
|
| 184 |
+
DocProject/Help/html
|
| 185 |
+
|
| 186 |
+
# Click-Once directory
|
| 187 |
+
publish/
|
| 188 |
+
|
| 189 |
+
# Publish Web Output
|
| 190 |
+
*.[Pp]ublish.xml
|
| 191 |
+
*.azurePubxml
|
| 192 |
+
# Note: Comment the next line if you want to checkin your web deploy settings,
|
| 193 |
+
# but database connection strings (with potential passwords) will be unencrypted
|
| 194 |
+
*.pubxml
|
| 195 |
+
*.publishproj
|
| 196 |
+
|
| 197 |
+
# Microsoft Azure Web App publish settings. Comment the next line if you want to
|
| 198 |
+
# checkin your Azure Web App publish settings, but sensitive information contained
|
| 199 |
+
# in these scripts will be unencrypted
|
| 200 |
+
PublishScripts/
|
| 201 |
+
|
| 202 |
+
# NuGet Packages
|
| 203 |
+
*.nupkg
|
| 204 |
+
# NuGet Symbol Packages
|
| 205 |
+
*.snupkg
|
| 206 |
+
# The packages folder can be ignored because of Package Restore
|
| 207 |
+
**/[Pp]ackages/*
|
| 208 |
+
# except build/, which is used as an MSBuild target.
|
| 209 |
+
!**/[Pp]ackages/build/
|
| 210 |
+
# Uncomment if necessary however generally it will be regenerated when needed
|
| 211 |
+
#!**/[Pp]ackages/repositories.config
|
| 212 |
+
# NuGet v3's project.json files produces more ignorable files
|
| 213 |
+
*.nuget.props
|
| 214 |
+
*.nuget.targets
|
| 215 |
+
|
| 216 |
+
# Microsoft Azure Build Output
|
| 217 |
+
csx/
|
| 218 |
+
*.build.csdef
|
| 219 |
+
|
| 220 |
+
# Microsoft Azure Emulator
|
| 221 |
+
ecf/
|
| 222 |
+
rcf/
|
| 223 |
+
|
| 224 |
+
# Windows Store app package directories and files
|
| 225 |
+
AppPackages/
|
| 226 |
+
BundleArtifacts/
|
| 227 |
+
Package.StoreAssociation.xml
|
| 228 |
+
_pkginfo.txt
|
| 229 |
+
*.appx
|
| 230 |
+
*.appxbundle
|
| 231 |
+
*.appxupload
|
| 232 |
+
|
| 233 |
+
# Visual Studio cache files
|
| 234 |
+
# files ending in .cache can be ignored
|
| 235 |
+
*.[Cc]ache
|
| 236 |
+
# but keep track of directories ending in .cache
|
| 237 |
+
!?*.[Cc]ache/
|
| 238 |
+
|
| 239 |
+
# Others
|
| 240 |
+
ClientBin/
|
| 241 |
+
~$*
|
| 242 |
+
*~
|
| 243 |
+
*.dbmdl
|
| 244 |
+
*.dbproj.schemaview
|
| 245 |
+
*.jfm
|
| 246 |
+
*.pfx
|
| 247 |
+
*.publishsettings
|
| 248 |
+
orleans.codegen.cs
|
| 249 |
+
|
| 250 |
+
# Including strong name files can present a security risk
|
| 251 |
+
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
|
| 252 |
+
#*.snk
|
| 253 |
+
|
| 254 |
+
# Since there are multiple workflows, uncomment next line to ignore bower_components
|
| 255 |
+
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
|
| 256 |
+
#bower_components/
|
| 257 |
+
|
| 258 |
+
# RIA/Silverlight projects
|
| 259 |
+
Generated_Code/
|
| 260 |
+
|
| 261 |
+
# Backup & report files from converting an old project file
|
| 262 |
+
# to a newer Visual Studio version. Backup files are not needed,
|
| 263 |
+
# because we have git ;-)
|
| 264 |
+
_UpgradeReport_Files/
|
| 265 |
+
Backup*/
|
| 266 |
+
UpgradeLog*.XML
|
| 267 |
+
UpgradeLog*.htm
|
| 268 |
+
ServiceFabricBackup/
|
| 269 |
+
*.rptproj.bak
|
| 270 |
+
|
| 271 |
+
# SQL Server files
|
| 272 |
+
*.mdf
|
| 273 |
+
*.ldf
|
| 274 |
+
*.ndf
|
| 275 |
+
|
| 276 |
+
# Business Intelligence projects
|
| 277 |
+
*.rdl.data
|
| 278 |
+
*.bim.layout
|
| 279 |
+
*.bim_*.settings
|
| 280 |
+
*.rptproj.rsuser
|
| 281 |
+
*- [Bb]ackup.rdl
|
| 282 |
+
*- [Bb]ackup ([0-9]).rdl
|
| 283 |
+
*- [Bb]ackup ([0-9][0-9]).rdl
|
| 284 |
+
|
| 285 |
+
# Microsoft Fakes
|
| 286 |
+
FakesAssemblies/
|
| 287 |
+
|
| 288 |
+
# GhostDoc plugin setting file
|
| 289 |
+
*.GhostDoc.xml
|
| 290 |
+
|
| 291 |
+
# Node.js Tools for Visual Studio
|
| 292 |
+
.ntvs_analysis.dat
|
| 293 |
+
node_modules/
|
| 294 |
+
|
| 295 |
+
# Visual Studio 6 build log
|
| 296 |
+
*.plg
|
| 297 |
+
|
| 298 |
+
# Visual Studio 6 workspace options file
|
| 299 |
+
*.opt
|
| 300 |
+
|
| 301 |
+
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
|
| 302 |
+
*.vbw
|
| 303 |
+
|
| 304 |
+
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
|
| 305 |
+
*.vbp
|
| 306 |
+
|
| 307 |
+
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
|
| 308 |
+
*.dsw
|
| 309 |
+
*.dsp
|
| 310 |
+
|
| 311 |
+
# Visual Studio 6 technical files
|
| 312 |
+
*.ncb
|
| 313 |
+
*.aps
|
| 314 |
+
|
| 315 |
+
# Visual Studio LightSwitch build output
|
| 316 |
+
**/*.HTMLClient/GeneratedArtifacts
|
| 317 |
+
**/*.DesktopClient/GeneratedArtifacts
|
| 318 |
+
**/*.DesktopClient/ModelManifest.xml
|
| 319 |
+
**/*.Server/GeneratedArtifacts
|
| 320 |
+
**/*.Server/ModelManifest.xml
|
| 321 |
+
_Pvt_Extensions
|
| 322 |
+
|
| 323 |
+
# Paket dependency manager
|
| 324 |
+
.paket/paket.exe
|
| 325 |
+
paket-files/
|
| 326 |
+
|
| 327 |
+
# FAKE - F# Make
|
| 328 |
+
.fake/
|
| 329 |
+
|
| 330 |
+
# CodeRush personal settings
|
| 331 |
+
.cr/personal
|
| 332 |
+
|
| 333 |
+
# Python Tools for Visual Studio (PTVS)
|
| 334 |
+
__pycache__/
|
| 335 |
+
*.pyc
|
| 336 |
+
|
| 337 |
+
# Cake - Uncomment if you are using it
|
| 338 |
+
# tools/**
|
| 339 |
+
# !tools/packages.config
|
| 340 |
+
|
| 341 |
+
# Tabs Studio
|
| 342 |
+
*.tss
|
| 343 |
+
|
| 344 |
+
# Telerik's JustMock configuration file
|
| 345 |
+
*.jmconfig
|
| 346 |
+
|
| 347 |
+
# BizTalk build output
|
| 348 |
+
*.btp.cs
|
| 349 |
+
*.btm.cs
|
| 350 |
+
*.odx.cs
|
| 351 |
+
*.xsd.cs
|
| 352 |
+
|
| 353 |
+
# OpenCover UI analysis results
|
| 354 |
+
OpenCover/
|
| 355 |
+
|
| 356 |
+
# Azure Stream Analytics local run output
|
| 357 |
+
ASALocalRun/
|
| 358 |
+
|
| 359 |
+
# MSBuild Binary and Structured Log
|
| 360 |
+
*.binlog
|
| 361 |
+
|
| 362 |
+
# NVidia Nsight GPU debugger configuration file
|
| 363 |
+
*.nvuser
|
| 364 |
+
|
| 365 |
+
# MFractors (Xamarin productivity tool) working folder
|
| 366 |
+
.mfractor/
|
| 367 |
+
|
| 368 |
+
# Local History for Visual Studio
|
| 369 |
+
.localhistory/
|
| 370 |
+
|
| 371 |
+
# Visual Studio History (VSHistory) files
|
| 372 |
+
.vshistory/
|
| 373 |
+
|
| 374 |
+
# BeatPulse healthcheck temp database
|
| 375 |
+
healthchecksdb
|
| 376 |
+
|
| 377 |
+
# Backup folder for Package Reference Convert tool in Visual Studio 2017
|
| 378 |
+
MigrationBackup/
|
| 379 |
+
|
| 380 |
+
# Ionide (cross platform F# VS Code tools) working folder
|
| 381 |
+
.ionide/
|
| 382 |
+
|
| 383 |
+
# Fody - auto-generated XML schema
|
| 384 |
+
FodyWeavers.xsd
|
| 385 |
+
|
| 386 |
+
# VS Code files for those working on multiple tools
|
| 387 |
+
.vscode/*
|
| 388 |
+
!.vscode/settings.json
|
| 389 |
+
!.vscode/tasks.json
|
| 390 |
+
!.vscode/launch.json
|
| 391 |
+
!.vscode/extensions.json
|
| 392 |
+
*.code-workspace
|
| 393 |
+
|
| 394 |
+
# Local History for Visual Studio Code
|
| 395 |
+
.history/
|
| 396 |
+
|
| 397 |
+
# Windows Installer files from build outputs
|
| 398 |
+
*.cab
|
| 399 |
+
*.msi
|
| 400 |
+
*.msix
|
| 401 |
+
*.msm
|
| 402 |
+
*.msp
|
| 403 |
+
|
| 404 |
+
# JetBrains Rider
|
| 405 |
+
*.sln.iml
|
TRELLIS/.gitmodules
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[submodule "trellis/representations/mesh/flexicubes"]
|
| 2 |
+
path = trellis/representations/mesh/flexicubes
|
| 3 |
+
url = https://github.com/MaxtirError/FlexiCubes.git
|
TRELLIS/extensions/vox2seq/benchmark.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
import torch
|
| 3 |
+
import vox2seq
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
if __name__ == "__main__":
|
| 7 |
+
stats = {
|
| 8 |
+
'z_order_cuda': [],
|
| 9 |
+
'z_order_pytorch': [],
|
| 10 |
+
'hilbert_cuda': [],
|
| 11 |
+
'hilbert_pytorch': [],
|
| 12 |
+
}
|
| 13 |
+
RES = [16, 32, 64, 128, 256]
|
| 14 |
+
for res in RES:
|
| 15 |
+
coords = torch.meshgrid(torch.arange(res), torch.arange(res), torch.arange(res))
|
| 16 |
+
coords = torch.stack(coords, dim=-1).reshape(-1, 3).int().cuda()
|
| 17 |
+
|
| 18 |
+
start = time.time()
|
| 19 |
+
for _ in range(100):
|
| 20 |
+
code_z_cuda = vox2seq.encode(coords, mode='z_order').cuda()
|
| 21 |
+
torch.cuda.synchronize()
|
| 22 |
+
stats['z_order_cuda'].append((time.time() - start) / 100)
|
| 23 |
+
|
| 24 |
+
start = time.time()
|
| 25 |
+
for _ in range(100):
|
| 26 |
+
code_z_pytorch = vox2seq.pytorch.encode(coords, mode='z_order').cuda()
|
| 27 |
+
torch.cuda.synchronize()
|
| 28 |
+
stats['z_order_pytorch'].append((time.time() - start) / 100)
|
| 29 |
+
|
| 30 |
+
start = time.time()
|
| 31 |
+
for _ in range(100):
|
| 32 |
+
code_h_cuda = vox2seq.encode(coords, mode='hilbert').cuda()
|
| 33 |
+
torch.cuda.synchronize()
|
| 34 |
+
stats['hilbert_cuda'].append((time.time() - start) / 100)
|
| 35 |
+
|
| 36 |
+
start = time.time()
|
| 37 |
+
for _ in range(100):
|
| 38 |
+
code_h_pytorch = vox2seq.pytorch.encode(coords, mode='hilbert').cuda()
|
| 39 |
+
torch.cuda.synchronize()
|
| 40 |
+
stats['hilbert_pytorch'].append((time.time() - start) / 100)
|
| 41 |
+
|
| 42 |
+
print(f"{'Resolution':<12}{'Z-Order (CUDA)':<24}{'Z-Order (PyTorch)':<24}{'Hilbert (CUDA)':<24}{'Hilbert (PyTorch)':<24}")
|
| 43 |
+
for res, z_order_cuda, z_order_pytorch, hilbert_cuda, hilbert_pytorch in zip(RES, stats['z_order_cuda'], stats['z_order_pytorch'], stats['hilbert_cuda'], stats['hilbert_pytorch']):
|
| 44 |
+
print(f"{res:<12}{z_order_cuda:<24.6f}{z_order_pytorch:<24.6f}{hilbert_cuda:<24.6f}{hilbert_pytorch:<24.6f}")
|
| 45 |
+
|
TRELLIS/extensions/vox2seq/setup.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# Copyright (C) 2023, Inria
|
| 3 |
+
# GRAPHDECO research group, https://team.inria.fr/graphdeco
|
| 4 |
+
# All rights reserved.
|
| 5 |
+
#
|
| 6 |
+
# This software is free for non-commercial, research and evaluation use
|
| 7 |
+
# under the terms of the LICENSE.md file.
|
| 8 |
+
#
|
| 9 |
+
# For inquiries contact george.drettakis@inria.fr
|
| 10 |
+
#
|
| 11 |
+
|
| 12 |
+
from setuptools import setup
|
| 13 |
+
from torch.utils.cpp_extension import CUDAExtension, BuildExtension
|
| 14 |
+
import os
|
| 15 |
+
os.path.dirname(os.path.abspath(__file__))
|
| 16 |
+
|
| 17 |
+
setup(
|
| 18 |
+
name="vox2seq",
|
| 19 |
+
packages=['vox2seq', 'vox2seq.pytorch'],
|
| 20 |
+
ext_modules=[
|
| 21 |
+
CUDAExtension(
|
| 22 |
+
name="vox2seq._C",
|
| 23 |
+
sources=[
|
| 24 |
+
"src/api.cu",
|
| 25 |
+
"src/z_order.cu",
|
| 26 |
+
"src/hilbert.cu",
|
| 27 |
+
"src/ext.cpp",
|
| 28 |
+
],
|
| 29 |
+
)
|
| 30 |
+
],
|
| 31 |
+
cmdclass={
|
| 32 |
+
'build_ext': BuildExtension
|
| 33 |
+
}
|
| 34 |
+
)
|
TRELLIS/extensions/vox2seq/src/api.cu
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include <torch/extension.h>
|
| 2 |
+
#include "api.h"
|
| 3 |
+
#include "z_order.h"
|
| 4 |
+
#include "hilbert.h"
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
torch::Tensor
|
| 8 |
+
z_order_encode(
|
| 9 |
+
const torch::Tensor& x,
|
| 10 |
+
const torch::Tensor& y,
|
| 11 |
+
const torch::Tensor& z
|
| 12 |
+
) {
|
| 13 |
+
// Allocate output tensor
|
| 14 |
+
torch::Tensor codes = torch::empty_like(x);
|
| 15 |
+
|
| 16 |
+
// Call CUDA kernel
|
| 17 |
+
z_order_encode_cuda<<<(x.size(0) + BLOCK_SIZE - 1) / BLOCK_SIZE, BLOCK_SIZE>>>(
|
| 18 |
+
x.size(0),
|
| 19 |
+
reinterpret_cast<uint32_t*>(x.contiguous().data_ptr<int>()),
|
| 20 |
+
reinterpret_cast<uint32_t*>(y.contiguous().data_ptr<int>()),
|
| 21 |
+
reinterpret_cast<uint32_t*>(z.contiguous().data_ptr<int>()),
|
| 22 |
+
reinterpret_cast<uint32_t*>(codes.data_ptr<int>())
|
| 23 |
+
);
|
| 24 |
+
|
| 25 |
+
return codes;
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
std::tuple<torch::Tensor, torch::Tensor, torch::Tensor>
|
| 30 |
+
z_order_decode(
|
| 31 |
+
const torch::Tensor& codes
|
| 32 |
+
) {
|
| 33 |
+
// Allocate output tensors
|
| 34 |
+
torch::Tensor x = torch::empty_like(codes);
|
| 35 |
+
torch::Tensor y = torch::empty_like(codes);
|
| 36 |
+
torch::Tensor z = torch::empty_like(codes);
|
| 37 |
+
|
| 38 |
+
// Call CUDA kernel
|
| 39 |
+
z_order_decode_cuda<<<(codes.size(0) + BLOCK_SIZE - 1) / BLOCK_SIZE, BLOCK_SIZE>>>(
|
| 40 |
+
codes.size(0),
|
| 41 |
+
reinterpret_cast<uint32_t*>(codes.contiguous().data_ptr<int>()),
|
| 42 |
+
reinterpret_cast<uint32_t*>(x.data_ptr<int>()),
|
| 43 |
+
reinterpret_cast<uint32_t*>(y.data_ptr<int>()),
|
| 44 |
+
reinterpret_cast<uint32_t*>(z.data_ptr<int>())
|
| 45 |
+
);
|
| 46 |
+
|
| 47 |
+
return std::make_tuple(x, y, z);
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
torch::Tensor
|
| 52 |
+
hilbert_encode(
|
| 53 |
+
const torch::Tensor& x,
|
| 54 |
+
const torch::Tensor& y,
|
| 55 |
+
const torch::Tensor& z
|
| 56 |
+
) {
|
| 57 |
+
// Allocate output tensor
|
| 58 |
+
torch::Tensor codes = torch::empty_like(x);
|
| 59 |
+
|
| 60 |
+
// Call CUDA kernel
|
| 61 |
+
hilbert_encode_cuda<<<(x.size(0) + BLOCK_SIZE - 1) / BLOCK_SIZE, BLOCK_SIZE>>>(
|
| 62 |
+
x.size(0),
|
| 63 |
+
reinterpret_cast<uint32_t*>(x.contiguous().data_ptr<int>()),
|
| 64 |
+
reinterpret_cast<uint32_t*>(y.contiguous().data_ptr<int>()),
|
| 65 |
+
reinterpret_cast<uint32_t*>(z.contiguous().data_ptr<int>()),
|
| 66 |
+
reinterpret_cast<uint32_t*>(codes.data_ptr<int>())
|
| 67 |
+
);
|
| 68 |
+
|
| 69 |
+
return codes;
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
std::tuple<torch::Tensor, torch::Tensor, torch::Tensor>
|
| 74 |
+
hilbert_decode(
|
| 75 |
+
const torch::Tensor& codes
|
| 76 |
+
) {
|
| 77 |
+
// Allocate output tensors
|
| 78 |
+
torch::Tensor x = torch::empty_like(codes);
|
| 79 |
+
torch::Tensor y = torch::empty_like(codes);
|
| 80 |
+
torch::Tensor z = torch::empty_like(codes);
|
| 81 |
+
|
| 82 |
+
// Call CUDA kernel
|
| 83 |
+
hilbert_decode_cuda<<<(codes.size(0) + BLOCK_SIZE - 1) / BLOCK_SIZE, BLOCK_SIZE>>>(
|
| 84 |
+
codes.size(0),
|
| 85 |
+
reinterpret_cast<uint32_t*>(codes.contiguous().data_ptr<int>()),
|
| 86 |
+
reinterpret_cast<uint32_t*>(x.data_ptr<int>()),
|
| 87 |
+
reinterpret_cast<uint32_t*>(y.data_ptr<int>()),
|
| 88 |
+
reinterpret_cast<uint32_t*>(z.data_ptr<int>())
|
| 89 |
+
);
|
| 90 |
+
|
| 91 |
+
return std::make_tuple(x, y, z);
|
| 92 |
+
}
|
TRELLIS/extensions/vox2seq/src/api.h
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*
|
| 2 |
+
* Serialize a voxel grid
|
| 3 |
+
*
|
| 4 |
+
* Copyright (C) 2024, Jianfeng XIANG <belljig@outlook.com>
|
| 5 |
+
* All rights reserved.
|
| 6 |
+
*
|
| 7 |
+
* Licensed under The MIT License [see LICENSE for details]
|
| 8 |
+
*
|
| 9 |
+
* Written by Jianfeng XIANG
|
| 10 |
+
*/
|
| 11 |
+
|
| 12 |
+
#pragma once
|
| 13 |
+
#include <torch/extension.h>
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
#define BLOCK_SIZE 256
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
/**
|
| 20 |
+
* Z-order encode 3D points
|
| 21 |
+
*
|
| 22 |
+
* @param x [N] tensor containing the x coordinates
|
| 23 |
+
* @param y [N] tensor containing the y coordinates
|
| 24 |
+
* @param z [N] tensor containing the z coordinates
|
| 25 |
+
*
|
| 26 |
+
* @return [N] tensor containing the z-order encoded values
|
| 27 |
+
*/
|
| 28 |
+
torch::Tensor
|
| 29 |
+
z_order_encode(
|
| 30 |
+
const torch::Tensor& x,
|
| 31 |
+
const torch::Tensor& y,
|
| 32 |
+
const torch::Tensor& z
|
| 33 |
+
);
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
/**
|
| 37 |
+
* Z-order decode 3D points
|
| 38 |
+
*
|
| 39 |
+
* @param codes [N] tensor containing the z-order encoded values
|
| 40 |
+
*
|
| 41 |
+
* @return 3 tensors [N] containing the x, y, z coordinates
|
| 42 |
+
*/
|
| 43 |
+
std::tuple<torch::Tensor, torch::Tensor, torch::Tensor>
|
| 44 |
+
z_order_decode(
|
| 45 |
+
const torch::Tensor& codes
|
| 46 |
+
);
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
/**
|
| 50 |
+
* Hilbert encode 3D points
|
| 51 |
+
*
|
| 52 |
+
* @param x [N] tensor containing the x coordinates
|
| 53 |
+
* @param y [N] tensor containing the y coordinates
|
| 54 |
+
* @param z [N] tensor containing the z coordinates
|
| 55 |
+
*
|
| 56 |
+
* @return [N] tensor containing the Hilbert encoded values
|
| 57 |
+
*/
|
| 58 |
+
torch::Tensor
|
| 59 |
+
hilbert_encode(
|
| 60 |
+
const torch::Tensor& x,
|
| 61 |
+
const torch::Tensor& y,
|
| 62 |
+
const torch::Tensor& z
|
| 63 |
+
);
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
/**
|
| 67 |
+
* Hilbert decode 3D points
|
| 68 |
+
*
|
| 69 |
+
* @param codes [N] tensor containing the Hilbert encoded values
|
| 70 |
+
*
|
| 71 |
+
* @return 3 tensors [N] containing the x, y, z coordinates
|
| 72 |
+
*/
|
| 73 |
+
std::tuple<torch::Tensor, torch::Tensor, torch::Tensor>
|
| 74 |
+
hilbert_decode(
|
| 75 |
+
const torch::Tensor& codes
|
| 76 |
+
);
|
TRELLIS/extensions/vox2seq/src/ext.cpp
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include <torch/extension.h>
|
| 2 |
+
#include "api.h"
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
|
| 6 |
+
m.def("z_order_encode", &z_order_encode);
|
| 7 |
+
m.def("z_order_decode", &z_order_decode);
|
| 8 |
+
m.def("hilbert_encode", &hilbert_encode);
|
| 9 |
+
m.def("hilbert_decode", &hilbert_decode);
|
| 10 |
+
}
|
TRELLIS/extensions/vox2seq/src/hilbert.cu
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include <cuda.h>
|
| 2 |
+
#include <cuda_runtime.h>
|
| 3 |
+
#include <device_launch_parameters.h>
|
| 4 |
+
|
| 5 |
+
#include <cooperative_groups.h>
|
| 6 |
+
#include <cooperative_groups/memcpy_async.h>
|
| 7 |
+
namespace cg = cooperative_groups;
|
| 8 |
+
|
| 9 |
+
#include "hilbert.h"
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
// Expands a 10-bit integer into 30 bits by inserting 2 zeros after each bit.
|
| 13 |
+
static __device__ uint32_t expandBits(uint32_t v)
|
| 14 |
+
{
|
| 15 |
+
v = (v * 0x00010001u) & 0xFF0000FFu;
|
| 16 |
+
v = (v * 0x00000101u) & 0x0F00F00Fu;
|
| 17 |
+
v = (v * 0x00000011u) & 0xC30C30C3u;
|
| 18 |
+
v = (v * 0x00000005u) & 0x49249249u;
|
| 19 |
+
return v;
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
// Removes 2 zeros after each bit in a 30-bit integer.
|
| 24 |
+
static __device__ uint32_t extractBits(uint32_t v)
|
| 25 |
+
{
|
| 26 |
+
v = v & 0x49249249;
|
| 27 |
+
v = (v ^ (v >> 2)) & 0x030C30C3u;
|
| 28 |
+
v = (v ^ (v >> 4)) & 0x0300F00Fu;
|
| 29 |
+
v = (v ^ (v >> 8)) & 0x030000FFu;
|
| 30 |
+
v = (v ^ (v >> 16)) & 0x000003FFu;
|
| 31 |
+
return v;
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
__global__ void hilbert_encode_cuda(
|
| 36 |
+
size_t N,
|
| 37 |
+
const uint32_t* x,
|
| 38 |
+
const uint32_t* y,
|
| 39 |
+
const uint32_t* z,
|
| 40 |
+
uint32_t* codes
|
| 41 |
+
) {
|
| 42 |
+
size_t thread_id = cg::this_grid().thread_rank();
|
| 43 |
+
if (thread_id >= N) return;
|
| 44 |
+
|
| 45 |
+
uint32_t point[3] = {x[thread_id], y[thread_id], z[thread_id]};
|
| 46 |
+
|
| 47 |
+
uint32_t m = 1 << 9, q, p, t;
|
| 48 |
+
|
| 49 |
+
// Inverse undo excess work
|
| 50 |
+
q = m;
|
| 51 |
+
while (q > 1) {
|
| 52 |
+
p = q - 1;
|
| 53 |
+
for (int i = 0; i < 3; i++) {
|
| 54 |
+
if (point[i] & q) {
|
| 55 |
+
point[0] ^= p; // invert
|
| 56 |
+
} else {
|
| 57 |
+
t = (point[0] ^ point[i]) & p;
|
| 58 |
+
point[0] ^= t;
|
| 59 |
+
point[i] ^= t;
|
| 60 |
+
}
|
| 61 |
+
}
|
| 62 |
+
q >>= 1;
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
// Gray encode
|
| 66 |
+
for (int i = 1; i < 3; i++) {
|
| 67 |
+
point[i] ^= point[i - 1];
|
| 68 |
+
}
|
| 69 |
+
t = 0;
|
| 70 |
+
q = m;
|
| 71 |
+
while (q > 1) {
|
| 72 |
+
if (point[2] & q) {
|
| 73 |
+
t ^= q - 1;
|
| 74 |
+
}
|
| 75 |
+
q >>= 1;
|
| 76 |
+
}
|
| 77 |
+
for (int i = 0; i < 3; i++) {
|
| 78 |
+
point[i] ^= t;
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
// Convert to 3D Hilbert code
|
| 82 |
+
uint32_t xx = expandBits(point[0]);
|
| 83 |
+
uint32_t yy = expandBits(point[1]);
|
| 84 |
+
uint32_t zz = expandBits(point[2]);
|
| 85 |
+
|
| 86 |
+
codes[thread_id] = xx * 4 + yy * 2 + zz;
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
__global__ void hilbert_decode_cuda(
|
| 91 |
+
size_t N,
|
| 92 |
+
const uint32_t* codes,
|
| 93 |
+
uint32_t* x,
|
| 94 |
+
uint32_t* y,
|
| 95 |
+
uint32_t* z
|
| 96 |
+
) {
|
| 97 |
+
size_t thread_id = cg::this_grid().thread_rank();
|
| 98 |
+
if (thread_id >= N) return;
|
| 99 |
+
|
| 100 |
+
uint32_t point[3];
|
| 101 |
+
point[0] = extractBits(codes[thread_id] >> 2);
|
| 102 |
+
point[1] = extractBits(codes[thread_id] >> 1);
|
| 103 |
+
point[2] = extractBits(codes[thread_id]);
|
| 104 |
+
|
| 105 |
+
uint32_t m = 2 << 9, q, p, t;
|
| 106 |
+
|
| 107 |
+
// Gray decode by H ^ (H/2)
|
| 108 |
+
t = point[2] >> 1;
|
| 109 |
+
for (int i = 2; i > 0; i--) {
|
| 110 |
+
point[i] ^= point[i - 1];
|
| 111 |
+
}
|
| 112 |
+
point[0] ^= t;
|
| 113 |
+
|
| 114 |
+
// Undo excess work
|
| 115 |
+
q = 2;
|
| 116 |
+
while (q != m) {
|
| 117 |
+
p = q - 1;
|
| 118 |
+
for (int i = 2; i >= 0; i--) {
|
| 119 |
+
if (point[i] & q) {
|
| 120 |
+
point[0] ^= p;
|
| 121 |
+
} else {
|
| 122 |
+
t = (point[0] ^ point[i]) & p;
|
| 123 |
+
point[0] ^= t;
|
| 124 |
+
point[i] ^= t;
|
| 125 |
+
}
|
| 126 |
+
}
|
| 127 |
+
q <<= 1;
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
x[thread_id] = point[0];
|
| 131 |
+
y[thread_id] = point[1];
|
| 132 |
+
z[thread_id] = point[2];
|
| 133 |
+
}
|
TRELLIS/extensions/vox2seq/src/hilbert.h
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
/**
|
| 4 |
+
* Hilbert encode 3D points
|
| 5 |
+
*
|
| 6 |
+
* @param x [N] tensor containing the x coordinates
|
| 7 |
+
* @param y [N] tensor containing the y coordinates
|
| 8 |
+
* @param z [N] tensor containing the z coordinates
|
| 9 |
+
*
|
| 10 |
+
* @return [N] tensor containing the z-order encoded values
|
| 11 |
+
*/
|
| 12 |
+
__global__ void hilbert_encode_cuda(
|
| 13 |
+
size_t N,
|
| 14 |
+
const uint32_t* x,
|
| 15 |
+
const uint32_t* y,
|
| 16 |
+
const uint32_t* z,
|
| 17 |
+
uint32_t* codes
|
| 18 |
+
);
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
/**
|
| 22 |
+
* Hilbert decode 3D points
|
| 23 |
+
*
|
| 24 |
+
* @param codes [N] tensor containing the z-order encoded values
|
| 25 |
+
* @param x [N] tensor containing the x coordinates
|
| 26 |
+
* @param y [N] tensor containing the y coordinates
|
| 27 |
+
* @param z [N] tensor containing the z coordinates
|
| 28 |
+
*/
|
| 29 |
+
__global__ void hilbert_decode_cuda(
|
| 30 |
+
size_t N,
|
| 31 |
+
const uint32_t* codes,
|
| 32 |
+
uint32_t* x,
|
| 33 |
+
uint32_t* y,
|
| 34 |
+
uint32_t* z
|
| 35 |
+
);
|
TRELLIS/extensions/vox2seq/src/z_order.cu
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include <cuda.h>
|
| 2 |
+
#include <cuda_runtime.h>
|
| 3 |
+
#include <device_launch_parameters.h>
|
| 4 |
+
|
| 5 |
+
#include <cooperative_groups.h>
|
| 6 |
+
#include <cooperative_groups/memcpy_async.h>
|
| 7 |
+
namespace cg = cooperative_groups;
|
| 8 |
+
|
| 9 |
+
#include "z_order.h"
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
// Expands a 10-bit integer into 30 bits by inserting 2 zeros after each bit.
|
| 13 |
+
static __device__ uint32_t expandBits(uint32_t v)
|
| 14 |
+
{
|
| 15 |
+
v = (v * 0x00010001u) & 0xFF0000FFu;
|
| 16 |
+
v = (v * 0x00000101u) & 0x0F00F00Fu;
|
| 17 |
+
v = (v * 0x00000011u) & 0xC30C30C3u;
|
| 18 |
+
v = (v * 0x00000005u) & 0x49249249u;
|
| 19 |
+
return v;
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
// Removes 2 zeros after each bit in a 30-bit integer.
|
| 24 |
+
static __device__ uint32_t extractBits(uint32_t v)
|
| 25 |
+
{
|
| 26 |
+
v = v & 0x49249249;
|
| 27 |
+
v = (v ^ (v >> 2)) & 0x030C30C3u;
|
| 28 |
+
v = (v ^ (v >> 4)) & 0x0300F00Fu;
|
| 29 |
+
v = (v ^ (v >> 8)) & 0x030000FFu;
|
| 30 |
+
v = (v ^ (v >> 16)) & 0x000003FFu;
|
| 31 |
+
return v;
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
__global__ void z_order_encode_cuda(
|
| 36 |
+
size_t N,
|
| 37 |
+
const uint32_t* x,
|
| 38 |
+
const uint32_t* y,
|
| 39 |
+
const uint32_t* z,
|
| 40 |
+
uint32_t* codes
|
| 41 |
+
) {
|
| 42 |
+
size_t thread_id = cg::this_grid().thread_rank();
|
| 43 |
+
if (thread_id >= N) return;
|
| 44 |
+
|
| 45 |
+
uint32_t xx = expandBits(x[thread_id]);
|
| 46 |
+
uint32_t yy = expandBits(y[thread_id]);
|
| 47 |
+
uint32_t zz = expandBits(z[thread_id]);
|
| 48 |
+
|
| 49 |
+
codes[thread_id] = xx * 4 + yy * 2 + zz;
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
__global__ void z_order_decode_cuda(
|
| 54 |
+
size_t N,
|
| 55 |
+
const uint32_t* codes,
|
| 56 |
+
uint32_t* x,
|
| 57 |
+
uint32_t* y,
|
| 58 |
+
uint32_t* z
|
| 59 |
+
) {
|
| 60 |
+
size_t thread_id = cg::this_grid().thread_rank();
|
| 61 |
+
if (thread_id >= N) return;
|
| 62 |
+
|
| 63 |
+
x[thread_id] = extractBits(codes[thread_id] >> 2);
|
| 64 |
+
y[thread_id] = extractBits(codes[thread_id] >> 1);
|
| 65 |
+
z[thread_id] = extractBits(codes[thread_id]);
|
| 66 |
+
}
|
TRELLIS/extensions/vox2seq/src/z_order.h
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
/**
|
| 4 |
+
* Z-order encode 3D points
|
| 5 |
+
*
|
| 6 |
+
* @param x [N] tensor containing the x coordinates
|
| 7 |
+
* @param y [N] tensor containing the y coordinates
|
| 8 |
+
* @param z [N] tensor containing the z coordinates
|
| 9 |
+
*
|
| 10 |
+
* @return [N] tensor containing the z-order encoded values
|
| 11 |
+
*/
|
| 12 |
+
__global__ void z_order_encode_cuda(
|
| 13 |
+
size_t N,
|
| 14 |
+
const uint32_t* x,
|
| 15 |
+
const uint32_t* y,
|
| 16 |
+
const uint32_t* z,
|
| 17 |
+
uint32_t* codes
|
| 18 |
+
);
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
/**
|
| 22 |
+
* Z-order decode 3D points
|
| 23 |
+
*
|
| 24 |
+
* @param codes [N] tensor containing the z-order encoded values
|
| 25 |
+
* @param x [N] tensor containing the x coordinates
|
| 26 |
+
* @param y [N] tensor containing the y coordinates
|
| 27 |
+
* @param z [N] tensor containing the z coordinates
|
| 28 |
+
*/
|
| 29 |
+
__global__ void z_order_decode_cuda(
|
| 30 |
+
size_t N,
|
| 31 |
+
const uint32_t* codes,
|
| 32 |
+
uint32_t* x,
|
| 33 |
+
uint32_t* y,
|
| 34 |
+
uint32_t* z
|
| 35 |
+
);
|
TRELLIS/extensions/vox2seq/test.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import vox2seq
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
if __name__ == "__main__":
|
| 6 |
+
RES = 256
|
| 7 |
+
coords = torch.meshgrid(torch.arange(RES), torch.arange(RES), torch.arange(RES))
|
| 8 |
+
coords = torch.stack(coords, dim=-1).reshape(-1, 3).int().cuda()
|
| 9 |
+
code_z_cuda = vox2seq.encode(coords, mode='z_order')
|
| 10 |
+
code_z_pytorch = vox2seq.pytorch.encode(coords, mode='z_order')
|
| 11 |
+
code_h_cuda = vox2seq.encode(coords, mode='hilbert')
|
| 12 |
+
code_h_pytorch = vox2seq.pytorch.encode(coords, mode='hilbert')
|
| 13 |
+
assert torch.equal(code_z_cuda, code_z_pytorch)
|
| 14 |
+
assert torch.equal(code_h_cuda, code_h_pytorch)
|
| 15 |
+
|
| 16 |
+
code = torch.arange(RES**3).int().cuda()
|
| 17 |
+
coords_z_cuda = vox2seq.decode(code, mode='z_order')
|
| 18 |
+
coords_z_pytorch = vox2seq.pytorch.decode(code, mode='z_order')
|
| 19 |
+
coords_h_cuda = vox2seq.decode(code, mode='hilbert')
|
| 20 |
+
coords_h_pytorch = vox2seq.pytorch.decode(code, mode='hilbert')
|
| 21 |
+
assert torch.equal(coords_z_cuda, coords_z_pytorch)
|
| 22 |
+
assert torch.equal(coords_h_cuda, coords_h_pytorch)
|
| 23 |
+
|
| 24 |
+
print("All tests passed.")
|
| 25 |
+
|
TRELLIS/extensions/vox2seq/vox2seq/__init__.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from typing import *
|
| 3 |
+
import torch
|
| 4 |
+
from . import _C
|
| 5 |
+
from . import pytorch
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@torch.no_grad()
|
| 9 |
+
def encode(coords: torch.Tensor, permute: List[int] = [0, 1, 2], mode: Literal['z_order', 'hilbert'] = 'z_order') -> torch.Tensor:
|
| 10 |
+
"""
|
| 11 |
+
Encodes 3D coordinates into a 30-bit code.
|
| 12 |
+
|
| 13 |
+
Args:
|
| 14 |
+
coords: a tensor of shape [N, 3] containing the 3D coordinates.
|
| 15 |
+
permute: the permutation of the coordinates.
|
| 16 |
+
mode: the encoding mode to use.
|
| 17 |
+
"""
|
| 18 |
+
assert coords.shape[-1] == 3 and coords.ndim == 2, "Input coordinates must be of shape [N, 3]"
|
| 19 |
+
x = coords[:, permute[0]].int()
|
| 20 |
+
y = coords[:, permute[1]].int()
|
| 21 |
+
z = coords[:, permute[2]].int()
|
| 22 |
+
if mode == 'z_order':
|
| 23 |
+
return _C.z_order_encode(x, y, z)
|
| 24 |
+
elif mode == 'hilbert':
|
| 25 |
+
return _C.hilbert_encode(x, y, z)
|
| 26 |
+
else:
|
| 27 |
+
raise ValueError(f"Unknown encoding mode: {mode}")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@torch.no_grad()
|
| 31 |
+
def decode(code: torch.Tensor, permute: List[int] = [0, 1, 2], mode: Literal['z_order', 'hilbert'] = 'z_order') -> torch.Tensor:
|
| 32 |
+
"""
|
| 33 |
+
Decodes a 30-bit code into 3D coordinates.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
code: a tensor of shape [N] containing the 30-bit code.
|
| 37 |
+
permute: the permutation of the coordinates.
|
| 38 |
+
mode: the decoding mode to use.
|
| 39 |
+
"""
|
| 40 |
+
assert code.ndim == 1, "Input code must be of shape [N]"
|
| 41 |
+
if mode == 'z_order':
|
| 42 |
+
coords = _C.z_order_decode(code)
|
| 43 |
+
elif mode == 'hilbert':
|
| 44 |
+
coords = _C.hilbert_decode(code)
|
| 45 |
+
else:
|
| 46 |
+
raise ValueError(f"Unknown decoding mode: {mode}")
|
| 47 |
+
x = coords[permute.index(0)]
|
| 48 |
+
y = coords[permute.index(1)]
|
| 49 |
+
z = coords[permute.index(2)]
|
| 50 |
+
return torch.stack([x, y, z], dim=-1)
|
TRELLIS/extensions/vox2seq/vox2seq/pytorch/__init__.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from typing import *
|
| 3 |
+
|
| 4 |
+
from .default import (
|
| 5 |
+
encode,
|
| 6 |
+
decode,
|
| 7 |
+
z_order_encode,
|
| 8 |
+
z_order_decode,
|
| 9 |
+
hilbert_encode,
|
| 10 |
+
hilbert_decode,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@torch.no_grad()
|
| 15 |
+
def encode(coords: torch.Tensor, permute: List[int] = [0, 1, 2], mode: Literal['z_order', 'hilbert'] = 'z_order') -> torch.Tensor:
|
| 16 |
+
"""
|
| 17 |
+
Encodes 3D coordinates into a 30-bit code.
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
coords: a tensor of shape [N, 3] containing the 3D coordinates.
|
| 21 |
+
permute: the permutation of the coordinates.
|
| 22 |
+
mode: the encoding mode to use.
|
| 23 |
+
"""
|
| 24 |
+
if mode == 'z_order':
|
| 25 |
+
return z_order_encode(coords[:, permute], depth=10).int()
|
| 26 |
+
elif mode == 'hilbert':
|
| 27 |
+
return hilbert_encode(coords[:, permute], depth=10).int()
|
| 28 |
+
else:
|
| 29 |
+
raise ValueError(f"Unknown encoding mode: {mode}")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@torch.no_grad()
|
| 33 |
+
def decode(code: torch.Tensor, permute: List[int] = [0, 1, 2], mode: Literal['z_order', 'hilbert'] = 'z_order') -> torch.Tensor:
|
| 34 |
+
"""
|
| 35 |
+
Decodes a 30-bit code into 3D coordinates.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
code: a tensor of shape [N] containing the 30-bit code.
|
| 39 |
+
permute: the permutation of the coordinates.
|
| 40 |
+
mode: the decoding mode to use.
|
| 41 |
+
"""
|
| 42 |
+
if mode == 'z_order':
|
| 43 |
+
return z_order_decode(code, depth=10)[:, permute].float()
|
| 44 |
+
elif mode == 'hilbert':
|
| 45 |
+
return hilbert_decode(code, depth=10)[:, permute].float()
|
| 46 |
+
else:
|
| 47 |
+
raise ValueError(f"Unknown decoding mode: {mode}")
|
| 48 |
+
|
TRELLIS/extensions/vox2seq/vox2seq/pytorch/default.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from .z_order import xyz2key as z_order_encode_
|
| 3 |
+
from .z_order import key2xyz as z_order_decode_
|
| 4 |
+
from .hilbert import encode as hilbert_encode_
|
| 5 |
+
from .hilbert import decode as hilbert_decode_
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@torch.inference_mode()
|
| 9 |
+
def encode(grid_coord, batch=None, depth=16, order="z"):
|
| 10 |
+
assert order in {"z", "z-trans", "hilbert", "hilbert-trans"}
|
| 11 |
+
if order == "z":
|
| 12 |
+
code = z_order_encode(grid_coord, depth=depth)
|
| 13 |
+
elif order == "z-trans":
|
| 14 |
+
code = z_order_encode(grid_coord[:, [1, 0, 2]], depth=depth)
|
| 15 |
+
elif order == "hilbert":
|
| 16 |
+
code = hilbert_encode(grid_coord, depth=depth)
|
| 17 |
+
elif order == "hilbert-trans":
|
| 18 |
+
code = hilbert_encode(grid_coord[:, [1, 0, 2]], depth=depth)
|
| 19 |
+
else:
|
| 20 |
+
raise NotImplementedError
|
| 21 |
+
if batch is not None:
|
| 22 |
+
batch = batch.long()
|
| 23 |
+
code = batch << depth * 3 | code
|
| 24 |
+
return code
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@torch.inference_mode()
|
| 28 |
+
def decode(code, depth=16, order="z"):
|
| 29 |
+
assert order in {"z", "hilbert"}
|
| 30 |
+
batch = code >> depth * 3
|
| 31 |
+
code = code & ((1 << depth * 3) - 1)
|
| 32 |
+
if order == "z":
|
| 33 |
+
grid_coord = z_order_decode(code, depth=depth)
|
| 34 |
+
elif order == "hilbert":
|
| 35 |
+
grid_coord = hilbert_decode(code, depth=depth)
|
| 36 |
+
else:
|
| 37 |
+
raise NotImplementedError
|
| 38 |
+
return grid_coord, batch
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def z_order_encode(grid_coord: torch.Tensor, depth: int = 16):
|
| 42 |
+
x, y, z = grid_coord[:, 0].long(), grid_coord[:, 1].long(), grid_coord[:, 2].long()
|
| 43 |
+
# we block the support to batch, maintain batched code in Point class
|
| 44 |
+
code = z_order_encode_(x, y, z, b=None, depth=depth)
|
| 45 |
+
return code
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def z_order_decode(code: torch.Tensor, depth):
|
| 49 |
+
x, y, z, _ = z_order_decode_(code, depth=depth)
|
| 50 |
+
grid_coord = torch.stack([x, y, z], dim=-1) # (N, 3)
|
| 51 |
+
return grid_coord
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def hilbert_encode(grid_coord: torch.Tensor, depth: int = 16):
|
| 55 |
+
return hilbert_encode_(grid_coord, num_dims=3, num_bits=depth)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def hilbert_decode(code: torch.Tensor, depth: int = 16):
|
| 59 |
+
return hilbert_decode_(code, num_dims=3, num_bits=depth)
|
TRELLIS/extensions/vox2seq/vox2seq/pytorch/hilbert.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Hilbert Order
|
| 3 |
+
Modified from https://github.com/PrincetonLIPS/numpy-hilbert-curve
|
| 4 |
+
|
| 5 |
+
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com), Kaixin Xu
|
| 6 |
+
Please cite our work if the code is helpful to you.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def right_shift(binary, k=1, axis=-1):
|
| 13 |
+
"""Right shift an array of binary values.
|
| 14 |
+
|
| 15 |
+
Parameters:
|
| 16 |
+
-----------
|
| 17 |
+
binary: An ndarray of binary values.
|
| 18 |
+
|
| 19 |
+
k: The number of bits to shift. Default 1.
|
| 20 |
+
|
| 21 |
+
axis: The axis along which to shift. Default -1.
|
| 22 |
+
|
| 23 |
+
Returns:
|
| 24 |
+
--------
|
| 25 |
+
Returns an ndarray with zero prepended and the ends truncated, along
|
| 26 |
+
whatever axis was specified."""
|
| 27 |
+
|
| 28 |
+
# If we're shifting the whole thing, just return zeros.
|
| 29 |
+
if binary.shape[axis] <= k:
|
| 30 |
+
return torch.zeros_like(binary)
|
| 31 |
+
|
| 32 |
+
# Determine the padding pattern.
|
| 33 |
+
# padding = [(0,0)] * len(binary.shape)
|
| 34 |
+
# padding[axis] = (k,0)
|
| 35 |
+
|
| 36 |
+
# Determine the slicing pattern to eliminate just the last one.
|
| 37 |
+
slicing = [slice(None)] * len(binary.shape)
|
| 38 |
+
slicing[axis] = slice(None, -k)
|
| 39 |
+
shifted = torch.nn.functional.pad(
|
| 40 |
+
binary[tuple(slicing)], (k, 0), mode="constant", value=0
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
return shifted
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def binary2gray(binary, axis=-1):
|
| 47 |
+
"""Convert an array of binary values into Gray codes.
|
| 48 |
+
|
| 49 |
+
This uses the classic X ^ (X >> 1) trick to compute the Gray code.
|
| 50 |
+
|
| 51 |
+
Parameters:
|
| 52 |
+
-----------
|
| 53 |
+
binary: An ndarray of binary values.
|
| 54 |
+
|
| 55 |
+
axis: The axis along which to compute the gray code. Default=-1.
|
| 56 |
+
|
| 57 |
+
Returns:
|
| 58 |
+
--------
|
| 59 |
+
Returns an ndarray of Gray codes.
|
| 60 |
+
"""
|
| 61 |
+
shifted = right_shift(binary, axis=axis)
|
| 62 |
+
|
| 63 |
+
# Do the X ^ (X >> 1) trick.
|
| 64 |
+
gray = torch.logical_xor(binary, shifted)
|
| 65 |
+
|
| 66 |
+
return gray
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def gray2binary(gray, axis=-1):
|
| 70 |
+
"""Convert an array of Gray codes back into binary values.
|
| 71 |
+
|
| 72 |
+
Parameters:
|
| 73 |
+
-----------
|
| 74 |
+
gray: An ndarray of gray codes.
|
| 75 |
+
|
| 76 |
+
axis: The axis along which to perform Gray decoding. Default=-1.
|
| 77 |
+
|
| 78 |
+
Returns:
|
| 79 |
+
--------
|
| 80 |
+
Returns an ndarray of binary values.
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
# Loop the log2(bits) number of times necessary, with shift and xor.
|
| 84 |
+
shift = 2 ** (torch.Tensor([gray.shape[axis]]).log2().ceil().int() - 1)
|
| 85 |
+
while shift > 0:
|
| 86 |
+
gray = torch.logical_xor(gray, right_shift(gray, shift))
|
| 87 |
+
shift = torch.div(shift, 2, rounding_mode="floor")
|
| 88 |
+
return gray
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def encode(locs, num_dims, num_bits):
|
| 92 |
+
"""Decode an array of locations in a hypercube into a Hilbert integer.
|
| 93 |
+
|
| 94 |
+
This is a vectorized-ish version of the Hilbert curve implementation by John
|
| 95 |
+
Skilling as described in:
|
| 96 |
+
|
| 97 |
+
Skilling, J. (2004, April). Programming the Hilbert curve. In AIP Conference
|
| 98 |
+
Proceedings (Vol. 707, No. 1, pp. 381-387). American Institute of Physics.
|
| 99 |
+
|
| 100 |
+
Params:
|
| 101 |
+
-------
|
| 102 |
+
locs - An ndarray of locations in a hypercube of num_dims dimensions, in
|
| 103 |
+
which each dimension runs from 0 to 2**num_bits-1. The shape can
|
| 104 |
+
be arbitrary, as long as the last dimension of the same has size
|
| 105 |
+
num_dims.
|
| 106 |
+
|
| 107 |
+
num_dims - The dimensionality of the hypercube. Integer.
|
| 108 |
+
|
| 109 |
+
num_bits - The number of bits for each dimension. Integer.
|
| 110 |
+
|
| 111 |
+
Returns:
|
| 112 |
+
--------
|
| 113 |
+
The output is an ndarray of uint64 integers with the same shape as the
|
| 114 |
+
input, excluding the last dimension, which needs to be num_dims.
|
| 115 |
+
"""
|
| 116 |
+
|
| 117 |
+
# Keep around the original shape for later.
|
| 118 |
+
orig_shape = locs.shape
|
| 119 |
+
bitpack_mask = 1 << torch.arange(0, 8).to(locs.device)
|
| 120 |
+
bitpack_mask_rev = bitpack_mask.flip(-1)
|
| 121 |
+
|
| 122 |
+
if orig_shape[-1] != num_dims:
|
| 123 |
+
raise ValueError(
|
| 124 |
+
"""
|
| 125 |
+
The shape of locs was surprising in that the last dimension was of size
|
| 126 |
+
%d, but num_dims=%d. These need to be equal.
|
| 127 |
+
"""
|
| 128 |
+
% (orig_shape[-1], num_dims)
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
if num_dims * num_bits > 63:
|
| 132 |
+
raise ValueError(
|
| 133 |
+
"""
|
| 134 |
+
num_dims=%d and num_bits=%d for %d bits total, which can't be encoded
|
| 135 |
+
into a int64. Are you sure you need that many points on your Hilbert
|
| 136 |
+
curve?
|
| 137 |
+
"""
|
| 138 |
+
% (num_dims, num_bits, num_dims * num_bits)
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
# Treat the location integers as 64-bit unsigned and then split them up into
|
| 142 |
+
# a sequence of uint8s. Preserve the association by dimension.
|
| 143 |
+
locs_uint8 = locs.long().view(torch.uint8).reshape((-1, num_dims, 8)).flip(-1)
|
| 144 |
+
|
| 145 |
+
# Now turn these into bits and truncate to num_bits.
|
| 146 |
+
gray = (
|
| 147 |
+
locs_uint8.unsqueeze(-1)
|
| 148 |
+
.bitwise_and(bitpack_mask_rev)
|
| 149 |
+
.ne(0)
|
| 150 |
+
.byte()
|
| 151 |
+
.flatten(-2, -1)[..., -num_bits:]
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
# Run the decoding process the other way.
|
| 155 |
+
# Iterate forwards through the bits.
|
| 156 |
+
for bit in range(0, num_bits):
|
| 157 |
+
# Iterate forwards through the dimensions.
|
| 158 |
+
for dim in range(0, num_dims):
|
| 159 |
+
# Identify which ones have this bit active.
|
| 160 |
+
mask = gray[:, dim, bit]
|
| 161 |
+
|
| 162 |
+
# Where this bit is on, invert the 0 dimension for lower bits.
|
| 163 |
+
gray[:, 0, bit + 1 :] = torch.logical_xor(
|
| 164 |
+
gray[:, 0, bit + 1 :], mask[:, None]
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
# Where the bit is off, exchange the lower bits with the 0 dimension.
|
| 168 |
+
to_flip = torch.logical_and(
|
| 169 |
+
torch.logical_not(mask[:, None]).repeat(1, gray.shape[2] - bit - 1),
|
| 170 |
+
torch.logical_xor(gray[:, 0, bit + 1 :], gray[:, dim, bit + 1 :]),
|
| 171 |
+
)
|
| 172 |
+
gray[:, dim, bit + 1 :] = torch.logical_xor(
|
| 173 |
+
gray[:, dim, bit + 1 :], to_flip
|
| 174 |
+
)
|
| 175 |
+
gray[:, 0, bit + 1 :] = torch.logical_xor(gray[:, 0, bit + 1 :], to_flip)
|
| 176 |
+
|
| 177 |
+
# Now flatten out.
|
| 178 |
+
gray = gray.swapaxes(1, 2).reshape((-1, num_bits * num_dims))
|
| 179 |
+
|
| 180 |
+
# Convert Gray back to binary.
|
| 181 |
+
hh_bin = gray2binary(gray)
|
| 182 |
+
|
| 183 |
+
# Pad back out to 64 bits.
|
| 184 |
+
extra_dims = 64 - num_bits * num_dims
|
| 185 |
+
padded = torch.nn.functional.pad(hh_bin, (extra_dims, 0), "constant", 0)
|
| 186 |
+
|
| 187 |
+
# Convert binary values into uint8s.
|
| 188 |
+
hh_uint8 = (
|
| 189 |
+
(padded.flip(-1).reshape((-1, 8, 8)) * bitpack_mask)
|
| 190 |
+
.sum(2)
|
| 191 |
+
.squeeze()
|
| 192 |
+
.type(torch.uint8)
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
# Convert uint8s into uint64s.
|
| 196 |
+
hh_uint64 = hh_uint8.view(torch.int64).squeeze()
|
| 197 |
+
|
| 198 |
+
return hh_uint64
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def decode(hilberts, num_dims, num_bits):
|
| 202 |
+
"""Decode an array of Hilbert integers into locations in a hypercube.
|
| 203 |
+
|
| 204 |
+
This is a vectorized-ish version of the Hilbert curve implementation by John
|
| 205 |
+
Skilling as described in:
|
| 206 |
+
|
| 207 |
+
Skilling, J. (2004, April). Programming the Hilbert curve. In AIP Conference
|
| 208 |
+
Proceedings (Vol. 707, No. 1, pp. 381-387). American Institute of Physics.
|
| 209 |
+
|
| 210 |
+
Params:
|
| 211 |
+
-------
|
| 212 |
+
hilberts - An ndarray of Hilbert integers. Must be an integer dtype and
|
| 213 |
+
cannot have fewer bits than num_dims * num_bits.
|
| 214 |
+
|
| 215 |
+
num_dims - The dimensionality of the hypercube. Integer.
|
| 216 |
+
|
| 217 |
+
num_bits - The number of bits for each dimension. Integer.
|
| 218 |
+
|
| 219 |
+
Returns:
|
| 220 |
+
--------
|
| 221 |
+
The output is an ndarray of unsigned integers with the same shape as hilberts
|
| 222 |
+
but with an additional dimension of size num_dims.
|
| 223 |
+
"""
|
| 224 |
+
|
| 225 |
+
if num_dims * num_bits > 64:
|
| 226 |
+
raise ValueError(
|
| 227 |
+
"""
|
| 228 |
+
num_dims=%d and num_bits=%d for %d bits total, which can't be encoded
|
| 229 |
+
into a uint64. Are you sure you need that many points on your Hilbert
|
| 230 |
+
curve?
|
| 231 |
+
"""
|
| 232 |
+
% (num_dims, num_bits)
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
# Handle the case where we got handed a naked integer.
|
| 236 |
+
hilberts = torch.atleast_1d(hilberts)
|
| 237 |
+
|
| 238 |
+
# Keep around the shape for later.
|
| 239 |
+
orig_shape = hilberts.shape
|
| 240 |
+
bitpack_mask = 2 ** torch.arange(0, 8).to(hilberts.device)
|
| 241 |
+
bitpack_mask_rev = bitpack_mask.flip(-1)
|
| 242 |
+
|
| 243 |
+
# Treat each of the hilberts as a s equence of eight uint8.
|
| 244 |
+
# This treats all of the inputs as uint64 and makes things uniform.
|
| 245 |
+
hh_uint8 = (
|
| 246 |
+
hilberts.ravel().type(torch.int64).view(torch.uint8).reshape((-1, 8)).flip(-1)
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
# Turn these lists of uints into lists of bits and then truncate to the size
|
| 250 |
+
# we actually need for using Skilling's procedure.
|
| 251 |
+
hh_bits = (
|
| 252 |
+
hh_uint8.unsqueeze(-1)
|
| 253 |
+
.bitwise_and(bitpack_mask_rev)
|
| 254 |
+
.ne(0)
|
| 255 |
+
.byte()
|
| 256 |
+
.flatten(-2, -1)[:, -num_dims * num_bits :]
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
# Take the sequence of bits and Gray-code it.
|
| 260 |
+
gray = binary2gray(hh_bits)
|
| 261 |
+
|
| 262 |
+
# There has got to be a better way to do this.
|
| 263 |
+
# I could index them differently, but the eventual packbits likes it this way.
|
| 264 |
+
gray = gray.reshape((-1, num_bits, num_dims)).swapaxes(1, 2)
|
| 265 |
+
|
| 266 |
+
# Iterate backwards through the bits.
|
| 267 |
+
for bit in range(num_bits - 1, -1, -1):
|
| 268 |
+
# Iterate backwards through the dimensions.
|
| 269 |
+
for dim in range(num_dims - 1, -1, -1):
|
| 270 |
+
# Identify which ones have this bit active.
|
| 271 |
+
mask = gray[:, dim, bit]
|
| 272 |
+
|
| 273 |
+
# Where this bit is on, invert the 0 dimension for lower bits.
|
| 274 |
+
gray[:, 0, bit + 1 :] = torch.logical_xor(
|
| 275 |
+
gray[:, 0, bit + 1 :], mask[:, None]
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
# Where the bit is off, exchange the lower bits with the 0 dimension.
|
| 279 |
+
to_flip = torch.logical_and(
|
| 280 |
+
torch.logical_not(mask[:, None]),
|
| 281 |
+
torch.logical_xor(gray[:, 0, bit + 1 :], gray[:, dim, bit + 1 :]),
|
| 282 |
+
)
|
| 283 |
+
gray[:, dim, bit + 1 :] = torch.logical_xor(
|
| 284 |
+
gray[:, dim, bit + 1 :], to_flip
|
| 285 |
+
)
|
| 286 |
+
gray[:, 0, bit + 1 :] = torch.logical_xor(gray[:, 0, bit + 1 :], to_flip)
|
| 287 |
+
|
| 288 |
+
# Pad back out to 64 bits.
|
| 289 |
+
extra_dims = 64 - num_bits
|
| 290 |
+
padded = torch.nn.functional.pad(gray, (extra_dims, 0), "constant", 0)
|
| 291 |
+
|
| 292 |
+
# Now chop these up into blocks of 8.
|
| 293 |
+
locs_chopped = padded.flip(-1).reshape((-1, num_dims, 8, 8))
|
| 294 |
+
|
| 295 |
+
# Take those blocks and turn them unto uint8s.
|
| 296 |
+
# from IPython import embed; embed()
|
| 297 |
+
locs_uint8 = (locs_chopped * bitpack_mask).sum(3).squeeze().type(torch.uint8)
|
| 298 |
+
|
| 299 |
+
# Finally, treat these as uint64s.
|
| 300 |
+
flat_locs = locs_uint8.view(torch.int64)
|
| 301 |
+
|
| 302 |
+
# Return them in the expected shape.
|
| 303 |
+
return flat_locs.reshape((*orig_shape, num_dims))
|
TRELLIS/extensions/vox2seq/vox2seq/pytorch/z_order.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --------------------------------------------------------
|
| 2 |
+
# Octree-based Sparse Convolutional Neural Networks
|
| 3 |
+
# Copyright (c) 2022 Peng-Shuai Wang <wangps@hotmail.com>
|
| 4 |
+
# Licensed under The MIT License [see LICENSE for details]
|
| 5 |
+
# Written by Peng-Shuai Wang
|
| 6 |
+
# --------------------------------------------------------
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from typing import Optional, Union
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class KeyLUT:
|
| 13 |
+
def __init__(self):
|
| 14 |
+
r256 = torch.arange(256, dtype=torch.int64)
|
| 15 |
+
r512 = torch.arange(512, dtype=torch.int64)
|
| 16 |
+
zero = torch.zeros(256, dtype=torch.int64)
|
| 17 |
+
device = torch.device("cpu")
|
| 18 |
+
|
| 19 |
+
self._encode = {
|
| 20 |
+
device: (
|
| 21 |
+
self.xyz2key(r256, zero, zero, 8),
|
| 22 |
+
self.xyz2key(zero, r256, zero, 8),
|
| 23 |
+
self.xyz2key(zero, zero, r256, 8),
|
| 24 |
+
)
|
| 25 |
+
}
|
| 26 |
+
self._decode = {device: self.key2xyz(r512, 9)}
|
| 27 |
+
|
| 28 |
+
def encode_lut(self, device=torch.device("cpu")):
|
| 29 |
+
if device not in self._encode:
|
| 30 |
+
cpu = torch.device("cpu")
|
| 31 |
+
self._encode[device] = tuple(e.to(device) for e in self._encode[cpu])
|
| 32 |
+
return self._encode[device]
|
| 33 |
+
|
| 34 |
+
def decode_lut(self, device=torch.device("cpu")):
|
| 35 |
+
if device not in self._decode:
|
| 36 |
+
cpu = torch.device("cpu")
|
| 37 |
+
self._decode[device] = tuple(e.to(device) for e in self._decode[cpu])
|
| 38 |
+
return self._decode[device]
|
| 39 |
+
|
| 40 |
+
def xyz2key(self, x, y, z, depth):
|
| 41 |
+
key = torch.zeros_like(x)
|
| 42 |
+
for i in range(depth):
|
| 43 |
+
mask = 1 << i
|
| 44 |
+
key = (
|
| 45 |
+
key
|
| 46 |
+
| ((x & mask) << (2 * i + 2))
|
| 47 |
+
| ((y & mask) << (2 * i + 1))
|
| 48 |
+
| ((z & mask) << (2 * i + 0))
|
| 49 |
+
)
|
| 50 |
+
return key
|
| 51 |
+
|
| 52 |
+
def key2xyz(self, key, depth):
|
| 53 |
+
x = torch.zeros_like(key)
|
| 54 |
+
y = torch.zeros_like(key)
|
| 55 |
+
z = torch.zeros_like(key)
|
| 56 |
+
for i in range(depth):
|
| 57 |
+
x = x | ((key & (1 << (3 * i + 2))) >> (2 * i + 2))
|
| 58 |
+
y = y | ((key & (1 << (3 * i + 1))) >> (2 * i + 1))
|
| 59 |
+
z = z | ((key & (1 << (3 * i + 0))) >> (2 * i + 0))
|
| 60 |
+
return x, y, z
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
_key_lut = KeyLUT()
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def xyz2key(
|
| 67 |
+
x: torch.Tensor,
|
| 68 |
+
y: torch.Tensor,
|
| 69 |
+
z: torch.Tensor,
|
| 70 |
+
b: Optional[Union[torch.Tensor, int]] = None,
|
| 71 |
+
depth: int = 16,
|
| 72 |
+
):
|
| 73 |
+
r"""Encodes :attr:`x`, :attr:`y`, :attr:`z` coordinates to the shuffled keys
|
| 74 |
+
based on pre-computed look up tables. The speed of this function is much
|
| 75 |
+
faster than the method based on for-loop.
|
| 76 |
+
|
| 77 |
+
Args:
|
| 78 |
+
x (torch.Tensor): The x coordinate.
|
| 79 |
+
y (torch.Tensor): The y coordinate.
|
| 80 |
+
z (torch.Tensor): The z coordinate.
|
| 81 |
+
b (torch.Tensor or int): The batch index of the coordinates, and should be
|
| 82 |
+
smaller than 32768. If :attr:`b` is :obj:`torch.Tensor`, the size of
|
| 83 |
+
:attr:`b` must be the same as :attr:`x`, :attr:`y`, and :attr:`z`.
|
| 84 |
+
depth (int): The depth of the shuffled key, and must be smaller than 17 (< 17).
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
EX, EY, EZ = _key_lut.encode_lut(x.device)
|
| 88 |
+
x, y, z = x.long(), y.long(), z.long()
|
| 89 |
+
|
| 90 |
+
mask = 255 if depth > 8 else (1 << depth) - 1
|
| 91 |
+
key = EX[x & mask] | EY[y & mask] | EZ[z & mask]
|
| 92 |
+
if depth > 8:
|
| 93 |
+
mask = (1 << (depth - 8)) - 1
|
| 94 |
+
key16 = EX[(x >> 8) & mask] | EY[(y >> 8) & mask] | EZ[(z >> 8) & mask]
|
| 95 |
+
key = key16 << 24 | key
|
| 96 |
+
|
| 97 |
+
if b is not None:
|
| 98 |
+
b = b.long()
|
| 99 |
+
key = b << 48 | key
|
| 100 |
+
|
| 101 |
+
return key
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def key2xyz(key: torch.Tensor, depth: int = 16):
|
| 105 |
+
r"""Decodes the shuffled key to :attr:`x`, :attr:`y`, :attr:`z` coordinates
|
| 106 |
+
and the batch index based on pre-computed look up tables.
|
| 107 |
+
|
| 108 |
+
Args:
|
| 109 |
+
key (torch.Tensor): The shuffled key.
|
| 110 |
+
depth (int): The depth of the shuffled key, and must be smaller than 17 (< 17).
|
| 111 |
+
"""
|
| 112 |
+
|
| 113 |
+
DX, DY, DZ = _key_lut.decode_lut(key.device)
|
| 114 |
+
x, y, z = torch.zeros_like(key), torch.zeros_like(key), torch.zeros_like(key)
|
| 115 |
+
|
| 116 |
+
b = key >> 48
|
| 117 |
+
key = key & ((1 << 48) - 1)
|
| 118 |
+
|
| 119 |
+
n = (depth + 2) // 3
|
| 120 |
+
for i in range(n):
|
| 121 |
+
k = key >> (i * 9) & 511
|
| 122 |
+
x = x | (DX[k] << (i * 3))
|
| 123 |
+
y = y | (DY[k] << (i * 3))
|
| 124 |
+
z = z | (DZ[k] << (i * 3))
|
| 125 |
+
|
| 126 |
+
return x, y, z, b
|
TRELLIS/network/__init__.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
from torch.autograd import Function
|
| 5 |
+
from torch.amp import custom_bwd, custom_fwd
|
| 6 |
+
|
| 7 |
+
class _TruncExp(Function): # pylint: disable=abstract-method
|
| 8 |
+
# Implementation from torch-ngp:
|
| 9 |
+
# https://github.com/ashawkey/torch-ngp/blob/93b08a0d4ec1cc6e69d85df7f0acdfb99603b628/activation.py
|
| 10 |
+
@staticmethod
|
| 11 |
+
@custom_fwd(cast_inputs=torch.float32, device_type='cuda')
|
| 12 |
+
def forward(ctx, x): # pylint: disable=arguments-differ
|
| 13 |
+
ctx.save_for_backward(x)
|
| 14 |
+
return torch.exp(x)
|
| 15 |
+
|
| 16 |
+
@staticmethod
|
| 17 |
+
@custom_bwd(device_type='cuda')
|
| 18 |
+
def backward(ctx, g): # pylint: disable=arguments-differ
|
| 19 |
+
x = ctx.saved_tensors[0]
|
| 20 |
+
return g * torch.exp(torch.clamp(x, max=15))
|
| 21 |
+
|
| 22 |
+
trunc_exp = _TruncExp.apply
|
| 23 |
+
|
| 24 |
+
def get_activation(name):
|
| 25 |
+
if name is None:
|
| 26 |
+
return lambda x: x
|
| 27 |
+
name = name.lower()
|
| 28 |
+
if name == "none":
|
| 29 |
+
return lambda x: x
|
| 30 |
+
elif name == "lin2srgb":
|
| 31 |
+
return lambda x: torch.where(
|
| 32 |
+
x > 0.0031308,
|
| 33 |
+
torch.pow(torch.clamp(x, min=0.0031308), 1.0 / 2.4) * 1.055 - 0.055,
|
| 34 |
+
12.92 * x,
|
| 35 |
+
).clamp(0.0, 1.0)
|
| 36 |
+
elif name == "exp":
|
| 37 |
+
return lambda x: torch.exp(x)
|
| 38 |
+
elif name == "shifted_exp":
|
| 39 |
+
return lambda x: torch.exp(x - 1.0)
|
| 40 |
+
elif name == "trunc_exp":
|
| 41 |
+
return trunc_exp
|
| 42 |
+
elif name == "shifted_trunc_exp":
|
| 43 |
+
return lambda x: trunc_exp(x - 1.0)
|
| 44 |
+
elif name == "sigmoid":
|
| 45 |
+
return lambda x: torch.sigmoid(x)
|
| 46 |
+
elif name == "tanh":
|
| 47 |
+
return lambda x: torch.tanh(x)
|
| 48 |
+
elif name == "shifted_softplus":
|
| 49 |
+
return lambda x: F.softplus(x - 1.0)
|
| 50 |
+
elif name == "scale_-11_01":
|
| 51 |
+
return lambda x: x * 0.5 + 0.5
|
| 52 |
+
else:
|
| 53 |
+
try:
|
| 54 |
+
return getattr(F, name)
|
| 55 |
+
except AttributeError:
|
| 56 |
+
raise ValueError(f"Unknown activation function: {name}")
|
| 57 |
+
|
| 58 |
+
def get_rank():
|
| 59 |
+
# SLURM_PROCID can be set even if SLURM is not managing the multiprocessing,
|
| 60 |
+
# therefore LOCAL_RANK needs to be checked first
|
| 61 |
+
rank_keys = ("RANK", "LOCAL_RANK", "SLURM_PROCID", "JSM_NAMESPACE_RANK")
|
| 62 |
+
for key in rank_keys:
|
| 63 |
+
rank = os.environ.get(key)
|
| 64 |
+
if rank is not None:
|
| 65 |
+
return int(rank)
|
| 66 |
+
return 0
|
| 67 |
+
|
| 68 |
+
class Updateable:
|
| 69 |
+
def do_update_step(
|
| 70 |
+
self, epoch: int, global_step: int, on_load_weights: bool = False
|
| 71 |
+
):
|
| 72 |
+
for attr in self.__dir__():
|
| 73 |
+
if attr.startswith("_"):
|
| 74 |
+
continue
|
| 75 |
+
try:
|
| 76 |
+
module = getattr(self, attr)
|
| 77 |
+
except:
|
| 78 |
+
continue # ignore attributes like property, which can't be retrived using getattr?
|
| 79 |
+
if isinstance(module, Updateable):
|
| 80 |
+
module.do_update_step(
|
| 81 |
+
epoch, global_step, on_load_weights=on_load_weights
|
| 82 |
+
)
|
| 83 |
+
self.update_step(epoch, global_step, on_load_weights=on_load_weights)
|
| 84 |
+
|
| 85 |
+
def do_update_step_end(self, epoch: int, global_step: int):
|
| 86 |
+
for attr in self.__dir__():
|
| 87 |
+
if attr.startswith("_"):
|
| 88 |
+
continue
|
| 89 |
+
try:
|
| 90 |
+
module = getattr(self, attr)
|
| 91 |
+
except:
|
| 92 |
+
continue # ignore attributes like property, which can't be retrived using getattr?
|
| 93 |
+
if isinstance(module, Updateable):
|
| 94 |
+
module.do_update_step_end(epoch, global_step)
|
| 95 |
+
self.update_step_end(epoch, global_step)
|
| 96 |
+
|
| 97 |
+
def update_step(self, epoch: int, global_step: int, on_load_weights: bool = False):
|
| 98 |
+
# override this method to implement custom update logic
|
| 99 |
+
# if on_load_weights is True, you should be careful doing things related to model evaluations,
|
| 100 |
+
# as the models and tensors are not guarenteed to be on the same device
|
| 101 |
+
pass
|
| 102 |
+
|
| 103 |
+
def update_step_end(self, epoch: int, global_step: int):
|
| 104 |
+
pass
|
TRELLIS/network/hash_grid.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import sys
|
| 3 |
+
sys.path.append('./')
|
| 4 |
+
|
| 5 |
+
from torch import nn
|
| 6 |
+
from torch.nn import functional as F
|
| 7 |
+
from network.tcnn import get_encoding, get_mlp
|
| 8 |
+
|
| 9 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 10 |
+
|
| 11 |
+
def generate_image_grid(height, width, normalized=True):
|
| 12 |
+
xs = torch.linspace(0, 1, steps=width) if normalized else torch.arange(width)
|
| 13 |
+
ys = torch.linspace(0, 1, steps=height) if normalized else torch.arange(height)
|
| 14 |
+
grid_y, grid_x = torch.meshgrid(ys, xs, indexing='ij')
|
| 15 |
+
return torch.stack((grid_x, grid_y), dim=-1)
|
| 16 |
+
|
| 17 |
+
def generate_surround_offset(sample_interval=0.5, step=3):
|
| 18 |
+
xs = torch.linspace(-sample_interval, sample_interval, steps=step)
|
| 19 |
+
ys = torch.linspace(-sample_interval, sample_interval, steps=step)
|
| 20 |
+
zs = torch.linspace(-sample_interval, sample_interval, steps=step)
|
| 21 |
+
offset_z, offset_y, offset_x = torch.meshgrid(zs, ys, xs, indexing='ij')
|
| 22 |
+
offset = torch.stack((offset_x, offset_y, offset_z), dim=-1)
|
| 23 |
+
offset = offset.view(-1, 1, 1, 3) / 63.
|
| 24 |
+
return offset
|
| 25 |
+
|
| 26 |
+
def generate_image_grid_3d(res, normalized=True):
|
| 27 |
+
xs = torch.linspace(-0.5, 0.5, steps=res)
|
| 28 |
+
ys = torch.linspace(-0.5, 0.5, steps=res)
|
| 29 |
+
zs = torch.linspace(-0.5, 0.5, steps=res)
|
| 30 |
+
grid_z, grid_y, grid_x = torch.meshgrid(zs, ys, xs, indexing='ij')
|
| 31 |
+
return torch.stack((grid_x, grid_y, grid_z), dim=-1)
|
| 32 |
+
|
| 33 |
+
def scale_tensor(dat, inp_scale, tgt_scale):
|
| 34 |
+
if inp_scale is None:
|
| 35 |
+
inp_scale = (0, 1)
|
| 36 |
+
if tgt_scale is None:
|
| 37 |
+
tgt_scale = (0, 1)
|
| 38 |
+
dat = (dat - inp_scale[0]) / (inp_scale[1] - inp_scale[0])
|
| 39 |
+
dat = dat * (tgt_scale[1] - tgt_scale[0]) + tgt_scale[0]
|
| 40 |
+
return dat
|
| 41 |
+
|
| 42 |
+
def contract_to_unisphere(x, bbox, unbounded=False):
|
| 43 |
+
return scale_tensor(x, bbox, (0, 1))
|
| 44 |
+
|
| 45 |
+
class HashGrid(nn.Module):
|
| 46 |
+
|
| 47 |
+
def __init__(self):
|
| 48 |
+
super().__init__()
|
| 49 |
+
|
| 50 |
+
n_feature_dims = 3
|
| 51 |
+
pos_encoding_config = {
|
| 52 |
+
"otype": "HashGrid",
|
| 53 |
+
"n_levels": 16,
|
| 54 |
+
"n_features_per_level": 2,
|
| 55 |
+
"log2_hashmap_size": 19,
|
| 56 |
+
"base_resolution": 16,
|
| 57 |
+
"per_level_scale": 1.447269237440378,
|
| 58 |
+
}
|
| 59 |
+
# default_factory=lambda: {
|
| 60 |
+
# "otype": "Frequency",
|
| 61 |
+
# "n_frequencies": 10
|
| 62 |
+
# }
|
| 63 |
+
|
| 64 |
+
mlp_network_config: dict = {
|
| 65 |
+
"otype": "VanillaMLP",
|
| 66 |
+
"activation": "ReLU",
|
| 67 |
+
"output_activation": "none",
|
| 68 |
+
"n_neurons": 64,
|
| 69 |
+
"n_hidden_layers": 1,
|
| 70 |
+
}
|
| 71 |
+
self.encoding = get_encoding(2, pos_encoding_config)
|
| 72 |
+
self.feature_network = get_mlp(
|
| 73 |
+
self.encoding.n_output_dims,
|
| 74 |
+
n_feature_dims,
|
| 75 |
+
mlp_network_config,
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def forward(self, points):
|
| 80 |
+
enc = self.encoding(points.view(-1, 2))
|
| 81 |
+
rgbs = self.feature_network(enc).view(*points.shape[:-1], 3)
|
| 82 |
+
return rgbs
|
| 83 |
+
|
| 84 |
+
class HashGridVoxel(nn.Module):
|
| 85 |
+
|
| 86 |
+
def __init__(self):
|
| 87 |
+
super().__init__()
|
| 88 |
+
|
| 89 |
+
n_feature_dims = 1
|
| 90 |
+
pos_encoding_config = {
|
| 91 |
+
"otype": "HashGrid",
|
| 92 |
+
"n_levels": 16,
|
| 93 |
+
"n_features_per_level": 2,
|
| 94 |
+
"log2_hashmap_size": 19,
|
| 95 |
+
"base_resolution": 16,
|
| 96 |
+
"per_level_scale": 1.447269237440378,
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
mlp_network_config: dict = {
|
| 100 |
+
"otype": "VanillaMLP",
|
| 101 |
+
"activation": "ReLU",
|
| 102 |
+
"output_activation": "sigmoid",
|
| 103 |
+
# "output_activation": "none",
|
| 104 |
+
"n_neurons": 64,
|
| 105 |
+
"n_hidden_layers": 1,
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
self.encoding = get_encoding(3, pos_encoding_config)
|
| 109 |
+
self.feature_network = get_mlp(
|
| 110 |
+
self.encoding.n_output_dims,
|
| 111 |
+
n_feature_dims,
|
| 112 |
+
mlp_network_config,
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
def forward(self, points):
|
| 116 |
+
enc = self.encoding(points)
|
| 117 |
+
voxels = self.feature_network(enc).view(-1, 64, 64, 64)
|
| 118 |
+
return voxels
|
| 119 |
+
|
| 120 |
+
if __name__ == '__main__':
|
| 121 |
+
|
| 122 |
+
res = 64
|
| 123 |
+
network = HashGridVoxel().to(device)
|
| 124 |
+
|
| 125 |
+
grid = generate_image_grid_3d(res)
|
| 126 |
+
grid = grid.to(device)
|
| 127 |
+
with torch.enable_grad():
|
| 128 |
+
voxels = network(grid, rot=True)
|
| 129 |
+
loss = voxels.sum() # Use sum() to make sure gradient is not zero
|
| 130 |
+
loss.backward()
|
| 131 |
+
print("rot_z.grad:", network.rot_z.grad) # Should not be None or zero
|
TRELLIS/network/loss.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import lpips
|
| 3 |
+
from torch import nn
|
| 4 |
+
|
| 5 |
+
def lpips_loss(pred, target, lpips_fun):
|
| 6 |
+
return lpips_fun(pred, target).flatten()
|
| 7 |
+
|
| 8 |
+
class LPIPSLoss(nn.Module):
|
| 9 |
+
|
| 10 |
+
def __init__(self,
|
| 11 |
+
net='vgg',
|
| 12 |
+
lpips_list=None,
|
| 13 |
+
normalize_inputs=True,
|
| 14 |
+
loss_weight=1.0):
|
| 15 |
+
super().__init__()
|
| 16 |
+
self.net = net
|
| 17 |
+
self.lpips = [] if (lpips_list is None or lpips_list[0].pnet_type != net) else lpips_list # use a list to avoid registering the LPIPS model in state_dict
|
| 18 |
+
self.normalize_inputs = normalize_inputs
|
| 19 |
+
self.loss_weight = loss_weight
|
| 20 |
+
|
| 21 |
+
def forward(self, pred, target):
|
| 22 |
+
dtype = pred.dtype
|
| 23 |
+
cdtype = torch.bfloat16
|
| 24 |
+
if len(self.lpips) == 0:
|
| 25 |
+
lpips_eval = lpips.LPIPS(
|
| 26 |
+
net=self.net, eval_mode=True, pnet_tune=False).to(
|
| 27 |
+
device=pred.device, dtype=cdtype)
|
| 28 |
+
# with torch.no_grad():
|
| 29 |
+
# lpips_eval = torch.jit.trace(lpips_eval, (pred.to(cdtype), target.to(cdtype)))
|
| 30 |
+
# lpips_eval = torch.jit.optimize_for_inference(lpips_eval)
|
| 31 |
+
self.lpips.append(lpips_eval)
|
| 32 |
+
if self.normalize_inputs:
|
| 33 |
+
pred = pred * 2 - 1
|
| 34 |
+
target = target * 2 - 1
|
| 35 |
+
with torch.jit.optimized_execution(False):
|
| 36 |
+
return lpips_loss(
|
| 37 |
+
pred.to(cdtype), target.to(cdtype), lpips_fun=self.lpips[0]
|
| 38 |
+
).to(dtype) * self.loss_weight
|
TRELLIS/network/mlp.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
|
| 5 |
+
class MLPDecoder(nn.Module):
|
| 6 |
+
|
| 7 |
+
def __init__(self, input_dim=16, hidden_dim=64, output_dim=1):
|
| 8 |
+
"""
|
| 9 |
+
Decoder-only MLP to output rotation angle.
|
| 10 |
+
- input_dim: The size of the input latent vector.
|
| 11 |
+
- hidden_dim: Number of neurons in hidden layers.
|
| 12 |
+
- output_dim: The number of output parameters (1 for rotation angle).
|
| 13 |
+
"""
|
| 14 |
+
super().__init__()
|
| 15 |
+
|
| 16 |
+
self.fc1 = nn.Linear(input_dim, hidden_dim)
|
| 17 |
+
self.fc2 = nn.Linear(hidden_dim, hidden_dim)
|
| 18 |
+
self.fc3 = nn.Linear(hidden_dim, output_dim)
|
| 19 |
+
|
| 20 |
+
# Latent code: Learnable input tensor
|
| 21 |
+
self.latent = nn.Parameter(torch.randn(input_dim) * 0.1)
|
| 22 |
+
|
| 23 |
+
def forward(self):
|
| 24 |
+
x = self.latent # Use the learnable latent vector as input
|
| 25 |
+
x = F.gelu(self.fc1(x))
|
| 26 |
+
x = F.gelu(self.fc2(x))
|
| 27 |
+
output = torch.sigmoid(self.fc3(x))
|
| 28 |
+
return output
|
| 29 |
+
|
| 30 |
+
if __name__ == '__main__':
|
| 31 |
+
|
| 32 |
+
network = MLPDecoder()
|
| 33 |
+
output = network()
|
| 34 |
+
print(output)
|
TRELLIS/network/tcnn.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import tinycudann as tcnn
|
| 2 |
+
import torch
|
| 3 |
+
from . import Updateable, get_rank, get_activation
|
| 4 |
+
from torch import nn
|
| 5 |
+
|
| 6 |
+
class TCNNEncoding(nn.Module):
|
| 7 |
+
def __init__(self, in_channels, config, dtype=torch.float32) -> None:
|
| 8 |
+
super().__init__()
|
| 9 |
+
self.n_input_dims = in_channels
|
| 10 |
+
with torch.cuda.device(get_rank()):
|
| 11 |
+
self.encoding = tcnn.Encoding(in_channels, config, dtype=dtype)
|
| 12 |
+
self.n_output_dims = self.encoding.n_output_dims
|
| 13 |
+
|
| 14 |
+
def forward(self, x):
|
| 15 |
+
return self.encoding(x)
|
| 16 |
+
|
| 17 |
+
class CompositeEncoding(nn.Module, Updateable):
|
| 18 |
+
def __init__(self, encoding, include_xyz=False, xyz_scale=2.0, xyz_offset=-1.0):
|
| 19 |
+
super(CompositeEncoding, self).__init__()
|
| 20 |
+
self.encoding = encoding
|
| 21 |
+
self.include_xyz, self.xyz_scale, self.xyz_offset = (
|
| 22 |
+
include_xyz,
|
| 23 |
+
xyz_scale,
|
| 24 |
+
xyz_offset,
|
| 25 |
+
)
|
| 26 |
+
self.n_output_dims = (
|
| 27 |
+
int(self.include_xyz) * self.encoding.n_input_dims
|
| 28 |
+
+ self.encoding.n_output_dims
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
def forward(self, x, *args):
|
| 32 |
+
return (
|
| 33 |
+
self.encoding(x, *args)
|
| 34 |
+
if not self.include_xyz
|
| 35 |
+
else torch.cat(
|
| 36 |
+
[x * self.xyz_scale + self.xyz_offset, self.encoding(x, *args)], dim=-1
|
| 37 |
+
)
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
class VanillaMLP(nn.Module):
|
| 41 |
+
def __init__(self, dim_in: int, dim_out: int, config: dict):
|
| 42 |
+
super().__init__()
|
| 43 |
+
self.n_neurons, self.n_hidden_layers = (
|
| 44 |
+
config["n_neurons"],
|
| 45 |
+
config["n_hidden_layers"],
|
| 46 |
+
)
|
| 47 |
+
layers = [
|
| 48 |
+
self.make_linear(dim_in, self.n_neurons, is_first=True, is_last=False),
|
| 49 |
+
self.make_activation(),
|
| 50 |
+
]
|
| 51 |
+
for i in range(self.n_hidden_layers - 1):
|
| 52 |
+
layers += [
|
| 53 |
+
self.make_linear(
|
| 54 |
+
self.n_neurons, self.n_neurons, is_first=False, is_last=False
|
| 55 |
+
),
|
| 56 |
+
self.make_activation(),
|
| 57 |
+
]
|
| 58 |
+
layers += [
|
| 59 |
+
self.make_linear(self.n_neurons, dim_out, is_first=False, is_last=True)
|
| 60 |
+
]
|
| 61 |
+
self.layers = nn.Sequential(*layers)
|
| 62 |
+
self.output_activation = get_activation(config.get("output_activation", None))
|
| 63 |
+
|
| 64 |
+
def forward(self, x):
|
| 65 |
+
# disable autocast
|
| 66 |
+
# strange that the parameters will have empty gradients if autocast is enabled in AMP
|
| 67 |
+
with torch.cuda.amp.autocast(enabled=False):
|
| 68 |
+
x = self.layers(x)
|
| 69 |
+
x = self.output_activation(x)
|
| 70 |
+
return x
|
| 71 |
+
|
| 72 |
+
def make_linear(self, dim_in, dim_out, is_first, is_last):
|
| 73 |
+
layer = nn.Linear(dim_in, dim_out, bias=False)
|
| 74 |
+
return layer
|
| 75 |
+
|
| 76 |
+
def make_activation(self):
|
| 77 |
+
return nn.ReLU(inplace=True)
|
| 78 |
+
|
| 79 |
+
def get_encoding(n_input_dims: int, config) -> nn.Module:
|
| 80 |
+
encoding = TCNNEncoding(n_input_dims, config)
|
| 81 |
+
encoding = CompositeEncoding(
|
| 82 |
+
encoding,
|
| 83 |
+
include_xyz=config.get("include_xyz", False),
|
| 84 |
+
xyz_scale=2.0,
|
| 85 |
+
xyz_offset=-1.0,
|
| 86 |
+
) # FIXME: hard coded
|
| 87 |
+
return encoding
|
| 88 |
+
|
| 89 |
+
def get_mlp(n_input_dims, n_output_dims, config) -> nn.Module:
|
| 90 |
+
network = VanillaMLP(n_input_dims, n_output_dims, config)
|
| 91 |
+
return network
|
TRELLIS/setup.sh
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Read Arguments
|
| 2 |
+
TEMP=`getopt -o h --long help,new-env,basic,xformers,flash-attn,diffoctreerast,vox2seq,spconv,mipgaussian,kaolin,nvdiffrast,demo -n 'setup.sh' -- "$@"`
|
| 3 |
+
|
| 4 |
+
eval set -- "$TEMP"
|
| 5 |
+
|
| 6 |
+
HELP=false
|
| 7 |
+
NEW_ENV=false
|
| 8 |
+
BASIC=false
|
| 9 |
+
XFORMERS=false
|
| 10 |
+
FLASHATTN=false
|
| 11 |
+
DIFFOCTREERAST=false
|
| 12 |
+
VOX2SEQ=false
|
| 13 |
+
LINEAR_ASSIGNMENT=false
|
| 14 |
+
SPCONV=false
|
| 15 |
+
ERROR=false
|
| 16 |
+
MIPGAUSSIAN=false
|
| 17 |
+
KAOLIN=false
|
| 18 |
+
NVDIFFRAST=false
|
| 19 |
+
DEMO=false
|
| 20 |
+
|
| 21 |
+
if [ "$#" -eq 1 ] ; then
|
| 22 |
+
HELP=true
|
| 23 |
+
fi
|
| 24 |
+
|
| 25 |
+
while true ; do
|
| 26 |
+
case "$1" in
|
| 27 |
+
-h|--help) HELP=true ; shift ;;
|
| 28 |
+
--new-env) NEW_ENV=true ; shift ;;
|
| 29 |
+
--basic) BASIC=true ; shift ;;
|
| 30 |
+
--xformers) XFORMERS=true ; shift ;;
|
| 31 |
+
--flash-attn) FLASHATTN=true ; shift ;;
|
| 32 |
+
--diffoctreerast) DIFFOCTREERAST=true ; shift ;;
|
| 33 |
+
--vox2seq) VOX2SEQ=true ; shift ;;
|
| 34 |
+
--spconv) SPCONV=true ; shift ;;
|
| 35 |
+
--mipgaussian) MIPGAUSSIAN=true ; shift ;;
|
| 36 |
+
--kaolin) KAOLIN=true ; shift ;;
|
| 37 |
+
--nvdiffrast) NVDIFFRAST=true ; shift ;;
|
| 38 |
+
--demo) DEMO=true ; shift ;;
|
| 39 |
+
--) shift ; break ;;
|
| 40 |
+
*) ERROR=true ; break ;;
|
| 41 |
+
esac
|
| 42 |
+
done
|
| 43 |
+
|
| 44 |
+
if [ "$ERROR" = true ] ; then
|
| 45 |
+
echo "Error: Invalid argument"
|
| 46 |
+
HELP=true
|
| 47 |
+
fi
|
| 48 |
+
|
| 49 |
+
if [ "$HELP" = true ] ; then
|
| 50 |
+
echo "Usage: setup.sh [OPTIONS]"
|
| 51 |
+
echo "Options:"
|
| 52 |
+
echo " -h, --help Display this help message"
|
| 53 |
+
echo " --new-env Create a new conda environment"
|
| 54 |
+
echo " --basic Install basic dependencies"
|
| 55 |
+
echo " --xformers Install xformers"
|
| 56 |
+
echo " --flash-attn Install flash-attn"
|
| 57 |
+
echo " --diffoctreerast Install diffoctreerast"
|
| 58 |
+
echo " --vox2seq Install vox2seq"
|
| 59 |
+
echo " --spconv Install spconv"
|
| 60 |
+
echo " --mipgaussian Install mip-splatting"
|
| 61 |
+
echo " --kaolin Install kaolin"
|
| 62 |
+
echo " --nvdiffrast Install nvdiffrast"
|
| 63 |
+
echo " --demo Install all dependencies for demo"
|
| 64 |
+
return
|
| 65 |
+
fi
|
| 66 |
+
|
| 67 |
+
if [ "$NEW_ENV" = true ] ; then
|
| 68 |
+
conda create -n trellis python=3.10
|
| 69 |
+
conda activate trellis
|
| 70 |
+
conda install pytorch==2.4.0 torchvision==0.19.0 pytorch-cuda=11.8 -c pytorch -c nvidia
|
| 71 |
+
fi
|
| 72 |
+
|
| 73 |
+
# Get system information
|
| 74 |
+
WORKDIR=$(pwd)
|
| 75 |
+
PYTORCH_VERSION=$(python -c "import torch; print(torch.__version__)")
|
| 76 |
+
PLATFORM=$(python -c "import torch; print(('cuda' if torch.version.cuda else ('hip' if torch.version.hip else 'unknown')) if torch.cuda.is_available() else 'cpu')")
|
| 77 |
+
case $PLATFORM in
|
| 78 |
+
cuda)
|
| 79 |
+
CUDA_VERSION=$(python -c "import torch; print(torch.version.cuda)")
|
| 80 |
+
CUDA_MAJOR_VERSION=$(echo $CUDA_VERSION | cut -d'.' -f1)
|
| 81 |
+
CUDA_MINOR_VERSION=$(echo $CUDA_VERSION | cut -d'.' -f2)
|
| 82 |
+
echo "[SYSTEM] PyTorch Version: $PYTORCH_VERSION, CUDA Version: $CUDA_VERSION"
|
| 83 |
+
;;
|
| 84 |
+
hip)
|
| 85 |
+
HIP_VERSION=$(python -c "import torch; print(torch.version.hip)")
|
| 86 |
+
HIP_MAJOR_VERSION=$(echo $HIP_VERSION | cut -d'.' -f1)
|
| 87 |
+
HIP_MINOR_VERSION=$(echo $HIP_VERSION | cut -d'.' -f2)
|
| 88 |
+
# Install pytorch 2.4.1 for hip
|
| 89 |
+
if [ "$PYTORCH_VERSION" != "2.4.1+rocm6.1" ] ; then
|
| 90 |
+
echo "[SYSTEM] Installing PyTorch 2.4.1 for HIP ($PYTORCH_VERSION -> 2.4.1+rocm6.1)"
|
| 91 |
+
pip install torch==2.4.1 torchvision==0.19.1 --index-url https://download.pytorch.org/whl/rocm6.1 --user
|
| 92 |
+
mkdir -p /tmp/extensions
|
| 93 |
+
sudo cp /opt/rocm/share/amd_smi /tmp/extensions/amd_smi -r
|
| 94 |
+
cd /tmp/extensions/amd_smi
|
| 95 |
+
sudo chmod -R 777 .
|
| 96 |
+
pip install .
|
| 97 |
+
cd $WORKDIR
|
| 98 |
+
PYTORCH_VERSION=$(python -c "import torch; print(torch.__version__)")
|
| 99 |
+
fi
|
| 100 |
+
echo "[SYSTEM] PyTorch Version: $PYTORCH_VERSION, HIP Version: $HIP_VERSION"
|
| 101 |
+
;;
|
| 102 |
+
*)
|
| 103 |
+
;;
|
| 104 |
+
esac
|
| 105 |
+
|
| 106 |
+
if [ "$BASIC" = true ] ; then
|
| 107 |
+
pip install pillow imageio imageio-ffmpeg tqdm easydict opencv-python-headless scipy ninja rembg onnxruntime trimesh xatlas pyvista pymeshfix igraph transformers
|
| 108 |
+
pip install git+https://github.com/EasternJournalist/utils3d.git@9a4eb15e4021b67b12c460c7057d642626897ec8
|
| 109 |
+
fi
|
| 110 |
+
|
| 111 |
+
if [ "$XFORMERS" = true ] ; then
|
| 112 |
+
# install xformers
|
| 113 |
+
if [ "$PLATFORM" = "cuda" ] ; then
|
| 114 |
+
if [ "$CUDA_VERSION" = "11.8" ] ; then
|
| 115 |
+
case $PYTORCH_VERSION in
|
| 116 |
+
2.0.1) pip install https://files.pythonhosted.org/packages/52/ca/82aeee5dcc24a3429ff5de65cc58ae9695f90f49fbba71755e7fab69a706/xformers-0.0.22-cp310-cp310-manylinux2014_x86_64.whl ;;
|
| 117 |
+
2.1.0) pip install xformers==0.0.22.post7 --index-url https://download.pytorch.org/whl/cu118 ;;
|
| 118 |
+
2.1.1) pip install xformers==0.0.23 --index-url https://download.pytorch.org/whl/cu118 ;;
|
| 119 |
+
2.1.2) pip install xformers==0.0.23.post1 --index-url https://download.pytorch.org/whl/cu118 ;;
|
| 120 |
+
2.2.0) pip install xformers==0.0.24 --index-url https://download.pytorch.org/whl/cu118 ;;
|
| 121 |
+
2.2.1) pip install xformers==0.0.25 --index-url https://download.pytorch.org/whl/cu118 ;;
|
| 122 |
+
2.2.2) pip install xformers==0.0.25.post1 --index-url https://download.pytorch.org/whl/cu118 ;;
|
| 123 |
+
2.3.0) pip install xformers==0.0.26.post1 --index-url https://download.pytorch.org/whl/cu118 ;;
|
| 124 |
+
2.4.0) pip install xformers==0.0.27.post2 --index-url https://download.pytorch.org/whl/cu118 ;;
|
| 125 |
+
2.4.1) pip install xformers==0.0.28 --index-url https://download.pytorch.org/whl/cu118 ;;
|
| 126 |
+
2.5.0) pip install xformers==0.0.28.post2 --index-url https://download.pytorch.org/whl/cu118 ;;
|
| 127 |
+
*) echo "[XFORMERS] Unsupported PyTorch & CUDA version: $PYTORCH_VERSION & $CUDA_VERSION" ;;
|
| 128 |
+
esac
|
| 129 |
+
elif [ "$CUDA_VERSION" = "12.1" ] ; then
|
| 130 |
+
case $PYTORCH_VERSION in
|
| 131 |
+
2.1.0) pip install xformers==0.0.22.post7 --index-url https://download.pytorch.org/whl/cu121 ;;
|
| 132 |
+
2.1.1) pip install xformers==0.0.23 --index-url https://download.pytorch.org/whl/cu121 ;;
|
| 133 |
+
2.1.2) pip install xformers==0.0.23.post1 --index-url https://download.pytorch.org/whl/cu121 ;;
|
| 134 |
+
2.2.0) pip install xformers==0.0.24 --index-url https://download.pytorch.org/whl/cu121 ;;
|
| 135 |
+
2.2.1) pip install xformers==0.0.25 --index-url https://download.pytorch.org/whl/cu121 ;;
|
| 136 |
+
2.2.2) pip install xformers==0.0.25.post1 --index-url https://download.pytorch.org/whl/cu121 ;;
|
| 137 |
+
2.3.0) pip install xformers==0.0.26.post1 --index-url https://download.pytorch.org/whl/cu121 ;;
|
| 138 |
+
2.4.0) pip install xformers==0.0.27.post2 --index-url https://download.pytorch.org/whl/cu121 ;;
|
| 139 |
+
2.4.1) pip install xformers==0.0.28 --index-url https://download.pytorch.org/whl/cu121 ;;
|
| 140 |
+
2.5.0) pip install xformers==0.0.28.post2 --index-url https://download.pytorch.org/whl/cu121 ;;
|
| 141 |
+
*) echo "[XFORMERS] Unsupported PyTorch & CUDA version: $PYTORCH_VERSION & $CUDA_VERSION" ;;
|
| 142 |
+
esac
|
| 143 |
+
elif [ "$CUDA_VERSION" = "12.4" ] ; then
|
| 144 |
+
case $PYTORCH_VERSION in
|
| 145 |
+
2.5.0) pip install xformers==0.0.28.post2 --index-url https://download.pytorch.org/whl/cu124 ;;
|
| 146 |
+
*) echo "[XFORMERS] Unsupported PyTorch & CUDA version: $PYTORCH_VERSION & $CUDA_VERSION" ;;
|
| 147 |
+
esac
|
| 148 |
+
else
|
| 149 |
+
echo "[XFORMERS] Unsupported CUDA version: $CUDA_MAJOR_VERSION"
|
| 150 |
+
fi
|
| 151 |
+
elif [ "$PLATFORM" = "hip" ] ; then
|
| 152 |
+
case $PYTORCH_VERSION in
|
| 153 |
+
2.4.1\+rocm6.1) pip install xformers==0.0.28 --index-url https://download.pytorch.org/whl/rocm6.1 ;;
|
| 154 |
+
*) echo "[XFORMERS] Unsupported PyTorch version: $PYTORCH_VERSION" ;;
|
| 155 |
+
esac
|
| 156 |
+
else
|
| 157 |
+
echo "[XFORMERS] Unsupported platform: $PLATFORM"
|
| 158 |
+
fi
|
| 159 |
+
fi
|
| 160 |
+
|
| 161 |
+
if [ "$FLASHATTN" = true ] ; then
|
| 162 |
+
if [ "$PLATFORM" = "cuda" ] ; then
|
| 163 |
+
pip install flash-attn
|
| 164 |
+
elif [ "$PLATFORM" = "hip" ] ; then
|
| 165 |
+
echo "[FLASHATTN] Prebuilt binaries not found. Building from source..."
|
| 166 |
+
mkdir -p /tmp/extensions
|
| 167 |
+
git clone --recursive https://github.com/ROCm/flash-attention.git /tmp/extensions/flash-attention
|
| 168 |
+
cd /tmp/extensions/flash-attention
|
| 169 |
+
git checkout tags/v2.6.3-cktile
|
| 170 |
+
GPU_ARCHS=gfx942 python setup.py install #MI300 series
|
| 171 |
+
cd $WORKDIR
|
| 172 |
+
else
|
| 173 |
+
echo "[FLASHATTN] Unsupported platform: $PLATFORM"
|
| 174 |
+
fi
|
| 175 |
+
fi
|
| 176 |
+
|
| 177 |
+
if [ "$KAOLIN" = true ] ; then
|
| 178 |
+
# install kaolin
|
| 179 |
+
if [ "$PLATFORM" = "cuda" ] ; then
|
| 180 |
+
case $PYTORCH_VERSION in
|
| 181 |
+
2.0.1) pip install kaolin -f https://nvidia-kaolin.s3.us-east-2.amazonaws.com/torch-2.0.1_cu118.html;;
|
| 182 |
+
2.1.0) pip install kaolin -f https://nvidia-kaolin.s3.us-east-2.amazonaws.com/torch-2.1.0_cu118.html;;
|
| 183 |
+
2.1.1) pip install kaolin -f https://nvidia-kaolin.s3.us-east-2.amazonaws.com/torch-2.1.1_cu118.html;;
|
| 184 |
+
2.2.0) pip install kaolin -f https://nvidia-kaolin.s3.us-east-2.amazonaws.com/torch-2.2.0_cu118.html;;
|
| 185 |
+
2.2.1) pip install kaolin -f https://nvidia-kaolin.s3.us-east-2.amazonaws.com/torch-2.2.1_cu118.html;;
|
| 186 |
+
2.2.2) pip install kaolin -f https://nvidia-kaolin.s3.us-east-2.amazonaws.com/torch-2.2.2_cu118.html;;
|
| 187 |
+
2.4.0) pip install kaolin -f https://nvidia-kaolin.s3.us-east-2.amazonaws.com/torch-2.4.0_cu121.html;;
|
| 188 |
+
*) echo "[KAOLIN] Unsupported PyTorch version: $PYTORCH_VERSION" ;;
|
| 189 |
+
esac
|
| 190 |
+
else
|
| 191 |
+
echo "[KAOLIN] Unsupported platform: $PLATFORM"
|
| 192 |
+
fi
|
| 193 |
+
fi
|
| 194 |
+
|
| 195 |
+
if [ "$NVDIFFRAST" = true ] ; then
|
| 196 |
+
if [ "$PLATFORM" = "cuda" ] ; then
|
| 197 |
+
mkdir -p /tmp/extensions
|
| 198 |
+
git clone https://github.com/NVlabs/nvdiffrast.git /tmp/extensions/nvdiffrast
|
| 199 |
+
pip install /tmp/extensions/nvdiffrast
|
| 200 |
+
else
|
| 201 |
+
echo "[NVDIFFRAST] Unsupported platform: $PLATFORM"
|
| 202 |
+
fi
|
| 203 |
+
fi
|
| 204 |
+
|
| 205 |
+
if [ "$DIFFOCTREERAST" = true ] ; then
|
| 206 |
+
if [ "$PLATFORM" = "cuda" ] ; then
|
| 207 |
+
mkdir -p /tmp/extensions
|
| 208 |
+
git clone --recurse-submodules https://github.com/JeffreyXiang/diffoctreerast.git /tmp/extensions/diffoctreerast
|
| 209 |
+
pip install /tmp/extensions/diffoctreerast
|
| 210 |
+
else
|
| 211 |
+
echo "[DIFFOCTREERAST] Unsupported platform: $PLATFORM"
|
| 212 |
+
fi
|
| 213 |
+
fi
|
| 214 |
+
|
| 215 |
+
if [ "$MIPGAUSSIAN" = true ] ; then
|
| 216 |
+
if [ "$PLATFORM" = "cuda" ] ; then
|
| 217 |
+
mkdir -p /tmp/extensions
|
| 218 |
+
git clone https://github.com/autonomousvision/mip-splatting.git /tmp/extensions/mip-splatting
|
| 219 |
+
pip install /tmp/extensions/mip-splatting/submodules/diff-gaussian-rasterization/
|
| 220 |
+
else
|
| 221 |
+
echo "[MIPGAUSSIAN] Unsupported platform: $PLATFORM"
|
| 222 |
+
fi
|
| 223 |
+
fi
|
| 224 |
+
|
| 225 |
+
if [ "$VOX2SEQ" = true ] ; then
|
| 226 |
+
if [ "$PLATFORM" = "cuda" ] ; then
|
| 227 |
+
mkdir -p /tmp/extensions
|
| 228 |
+
cp -r extensions/vox2seq /tmp/extensions/vox2seq
|
| 229 |
+
pip install /tmp/extensions/vox2seq
|
| 230 |
+
else
|
| 231 |
+
echo "[VOX2SEQ] Unsupported platform: $PLATFORM"
|
| 232 |
+
fi
|
| 233 |
+
fi
|
| 234 |
+
|
| 235 |
+
if [ "$SPCONV" = true ] ; then
|
| 236 |
+
# install spconv
|
| 237 |
+
if [ "$PLATFORM" = "cuda" ] ; then
|
| 238 |
+
case $CUDA_MAJOR_VERSION in
|
| 239 |
+
11) pip install spconv-cu118 ;;
|
| 240 |
+
12) pip install spconv-cu120 ;;
|
| 241 |
+
*) echo "[SPCONV] Unsupported PyTorch CUDA version: $CUDA_MAJOR_VERSION" ;;
|
| 242 |
+
esac
|
| 243 |
+
else
|
| 244 |
+
echo "[SPCONV] Unsupported platform: $PLATFORM"
|
| 245 |
+
fi
|
| 246 |
+
fi
|
| 247 |
+
|
| 248 |
+
if [ "$DEMO" = true ] ; then
|
| 249 |
+
pip install gradio==4.44.1 gradio_litmodel3d==0.0.1
|
| 250 |
+
fi
|
TRELLIS/trellis/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from . import models
|
| 2 |
+
from . import modules
|
| 3 |
+
from . import pipelines
|
| 4 |
+
from . import renderers
|
| 5 |
+
from . import representations
|
| 6 |
+
from . import utils
|
TRELLIS/trellis/models/__init__.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib
|
| 2 |
+
|
| 3 |
+
__attributes = {
|
| 4 |
+
'SparseStructureEncoder': 'sparse_structure_vae',
|
| 5 |
+
'SparseStructureDecoder': 'sparse_structure_vae',
|
| 6 |
+
'SparseStructureFlowModel': 'sparse_structure_flow',
|
| 7 |
+
'SLatEncoder': 'structured_latent_vae',
|
| 8 |
+
'SLatGaussianDecoder': 'structured_latent_vae',
|
| 9 |
+
'SLatRadianceFieldDecoder': 'structured_latent_vae',
|
| 10 |
+
'SLatMeshDecoder': 'structured_latent_vae',
|
| 11 |
+
'SLatFlowModel': 'structured_latent_flow',
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
__submodules = []
|
| 15 |
+
|
| 16 |
+
__all__ = list(__attributes.keys()) + __submodules
|
| 17 |
+
|
| 18 |
+
def __getattr__(name):
|
| 19 |
+
if name not in globals():
|
| 20 |
+
if name in __attributes:
|
| 21 |
+
module_name = __attributes[name]
|
| 22 |
+
module = importlib.import_module(f".{module_name}", __name__)
|
| 23 |
+
globals()[name] = getattr(module, name)
|
| 24 |
+
elif name in __submodules:
|
| 25 |
+
module = importlib.import_module(f".{name}", __name__)
|
| 26 |
+
globals()[name] = module
|
| 27 |
+
else:
|
| 28 |
+
raise AttributeError(f"module {__name__} has no attribute {name}")
|
| 29 |
+
return globals()[name]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def from_pretrained(path: str, **kwargs):
|
| 33 |
+
"""
|
| 34 |
+
Load a model from a pretrained checkpoint.
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
path: The path to the checkpoint. Can be either local path or a Hugging Face model name.
|
| 38 |
+
NOTE: config file and model file should take the name f'{path}.json' and f'{path}.safetensors' respectively.
|
| 39 |
+
**kwargs: Additional arguments for the model constructor.
|
| 40 |
+
"""
|
| 41 |
+
import os
|
| 42 |
+
import json
|
| 43 |
+
from safetensors.torch import load_file
|
| 44 |
+
is_local = os.path.exists(f"{path}.json") and os.path.exists(f"{path}.safetensors")
|
| 45 |
+
|
| 46 |
+
if is_local:
|
| 47 |
+
config_file = f"{path}.json"
|
| 48 |
+
model_file = f"{path}.safetensors"
|
| 49 |
+
else:
|
| 50 |
+
from huggingface_hub import hf_hub_download
|
| 51 |
+
path_parts = path.split('/')
|
| 52 |
+
repo_id = f'{path_parts[0]}/{path_parts[1]}'
|
| 53 |
+
model_name = '/'.join(path_parts[2:])
|
| 54 |
+
config_file = hf_hub_download(repo_id, f"{model_name}.json")
|
| 55 |
+
model_file = hf_hub_download(repo_id, f"{model_name}.safetensors")
|
| 56 |
+
|
| 57 |
+
with open(config_file, 'r') as f:
|
| 58 |
+
config = json.load(f)
|
| 59 |
+
model = __getattr__(config['name'])(**config['args'], **kwargs)
|
| 60 |
+
model.load_state_dict(load_file(model_file))
|
| 61 |
+
|
| 62 |
+
return model
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
# For Pylance
|
| 66 |
+
if __name__ == '__main__':
|
| 67 |
+
from .sparse_structure_vae import SparseStructureEncoder, SparseStructureDecoder
|
| 68 |
+
from .sparse_structure_flow import SparseStructureFlowModel
|
| 69 |
+
from .structured_latent_vae import SLatEncoder, SLatGaussianDecoder, SLatRadianceFieldDecoder, SLatMeshDecoder
|
| 70 |
+
from .structured_latent_flow import SLatFlowModel
|
TRELLIS/trellis/models/sparse_structure_flow.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import *
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
import numpy as np
|
| 6 |
+
from ..modules.utils import convert_module_to_f16, convert_module_to_f32
|
| 7 |
+
from ..modules.transformer import AbsolutePositionEmbedder, ModulatedTransformerCrossBlock
|
| 8 |
+
from ..modules.spatial import patchify, unpatchify
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class TimestepEmbedder(nn.Module):
|
| 12 |
+
"""
|
| 13 |
+
Embeds scalar timesteps into vector representations.
|
| 14 |
+
"""
|
| 15 |
+
def __init__(self, hidden_size, frequency_embedding_size=256):
|
| 16 |
+
super().__init__()
|
| 17 |
+
self.mlp = nn.Sequential(
|
| 18 |
+
nn.Linear(frequency_embedding_size, hidden_size, bias=True),
|
| 19 |
+
nn.SiLU(),
|
| 20 |
+
nn.Linear(hidden_size, hidden_size, bias=True),
|
| 21 |
+
)
|
| 22 |
+
self.frequency_embedding_size = frequency_embedding_size
|
| 23 |
+
|
| 24 |
+
@staticmethod
|
| 25 |
+
def timestep_embedding(t, dim, max_period=10000):
|
| 26 |
+
"""
|
| 27 |
+
Create sinusoidal timestep embeddings.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
t: a 1-D Tensor of N indices, one per batch element.
|
| 31 |
+
These may be fractional.
|
| 32 |
+
dim: the dimension of the output.
|
| 33 |
+
max_period: controls the minimum frequency of the embeddings.
|
| 34 |
+
|
| 35 |
+
Returns:
|
| 36 |
+
an (N, D) Tensor of positional embeddings.
|
| 37 |
+
"""
|
| 38 |
+
# https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
|
| 39 |
+
half = dim // 2
|
| 40 |
+
freqs = torch.exp(
|
| 41 |
+
-np.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
|
| 42 |
+
).to(device=t.device)
|
| 43 |
+
args = t[:, None].float() * freqs[None]
|
| 44 |
+
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
| 45 |
+
if dim % 2:
|
| 46 |
+
embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
|
| 47 |
+
return embedding
|
| 48 |
+
|
| 49 |
+
def forward(self, t):
|
| 50 |
+
t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
|
| 51 |
+
t_emb = self.mlp(t_freq)
|
| 52 |
+
return t_emb
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class SparseStructureFlowModel(nn.Module):
|
| 56 |
+
def __init__(
|
| 57 |
+
self,
|
| 58 |
+
resolution: int,
|
| 59 |
+
in_channels: int,
|
| 60 |
+
model_channels: int,
|
| 61 |
+
cond_channels: int,
|
| 62 |
+
out_channels: int,
|
| 63 |
+
num_blocks: int,
|
| 64 |
+
num_heads: Optional[int] = None,
|
| 65 |
+
num_head_channels: Optional[int] = 64,
|
| 66 |
+
mlp_ratio: float = 4,
|
| 67 |
+
patch_size: int = 2,
|
| 68 |
+
pe_mode: Literal["ape", "rope"] = "ape",
|
| 69 |
+
use_fp16: bool = False,
|
| 70 |
+
use_checkpoint: bool = False,
|
| 71 |
+
share_mod: bool = False,
|
| 72 |
+
qk_rms_norm: bool = False,
|
| 73 |
+
qk_rms_norm_cross: bool = False,
|
| 74 |
+
):
|
| 75 |
+
super().__init__()
|
| 76 |
+
self.resolution = resolution
|
| 77 |
+
self.in_channels = in_channels
|
| 78 |
+
self.model_channels = model_channels
|
| 79 |
+
self.cond_channels = cond_channels
|
| 80 |
+
self.out_channels = out_channels
|
| 81 |
+
self.num_blocks = num_blocks
|
| 82 |
+
self.num_heads = num_heads or model_channels // num_head_channels
|
| 83 |
+
self.mlp_ratio = mlp_ratio
|
| 84 |
+
self.patch_size = patch_size
|
| 85 |
+
self.pe_mode = pe_mode
|
| 86 |
+
self.use_fp16 = use_fp16
|
| 87 |
+
self.use_checkpoint = use_checkpoint
|
| 88 |
+
self.share_mod = share_mod
|
| 89 |
+
self.qk_rms_norm = qk_rms_norm
|
| 90 |
+
self.qk_rms_norm_cross = qk_rms_norm_cross
|
| 91 |
+
self.dtype = torch.float16 if use_fp16 else torch.float32
|
| 92 |
+
|
| 93 |
+
self.t_embedder = TimestepEmbedder(model_channels)
|
| 94 |
+
if share_mod:
|
| 95 |
+
self.adaLN_modulation = nn.Sequential(
|
| 96 |
+
nn.SiLU(),
|
| 97 |
+
nn.Linear(model_channels, 6 * model_channels, bias=True)
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
if pe_mode == "ape":
|
| 101 |
+
pos_embedder = AbsolutePositionEmbedder(model_channels, 3)
|
| 102 |
+
coords = torch.meshgrid(*[torch.arange(res, device=self.device) for res in [resolution // patch_size] * 3], indexing='ij')
|
| 103 |
+
coords = torch.stack(coords, dim=-1).reshape(-1, 3)
|
| 104 |
+
pos_emb = pos_embedder(coords)
|
| 105 |
+
self.register_buffer("pos_emb", pos_emb)
|
| 106 |
+
|
| 107 |
+
self.input_layer = nn.Linear(in_channels * patch_size**3, model_channels)
|
| 108 |
+
|
| 109 |
+
self.blocks = nn.ModuleList([
|
| 110 |
+
ModulatedTransformerCrossBlock(
|
| 111 |
+
model_channels,
|
| 112 |
+
cond_channels,
|
| 113 |
+
num_heads=self.num_heads,
|
| 114 |
+
mlp_ratio=self.mlp_ratio,
|
| 115 |
+
attn_mode='full',
|
| 116 |
+
use_checkpoint=self.use_checkpoint,
|
| 117 |
+
use_rope=(pe_mode == "rope"),
|
| 118 |
+
share_mod=share_mod,
|
| 119 |
+
qk_rms_norm=self.qk_rms_norm,
|
| 120 |
+
qk_rms_norm_cross=self.qk_rms_norm_cross,
|
| 121 |
+
)
|
| 122 |
+
for _ in range(num_blocks)
|
| 123 |
+
])
|
| 124 |
+
|
| 125 |
+
self.out_layer = nn.Linear(model_channels, out_channels * patch_size**3)
|
| 126 |
+
|
| 127 |
+
self.initialize_weights()
|
| 128 |
+
if use_fp16:
|
| 129 |
+
self.convert_to_fp16()
|
| 130 |
+
|
| 131 |
+
@property
|
| 132 |
+
def device(self) -> torch.device:
|
| 133 |
+
"""
|
| 134 |
+
Return the device of the model.
|
| 135 |
+
"""
|
| 136 |
+
return next(self.parameters()).device
|
| 137 |
+
|
| 138 |
+
def convert_to_fp16(self) -> None:
|
| 139 |
+
"""
|
| 140 |
+
Convert the torso of the model to float16.
|
| 141 |
+
"""
|
| 142 |
+
self.blocks.apply(convert_module_to_f16)
|
| 143 |
+
|
| 144 |
+
def convert_to_fp32(self) -> None:
|
| 145 |
+
"""
|
| 146 |
+
Convert the torso of the model to float32.
|
| 147 |
+
"""
|
| 148 |
+
self.blocks.apply(convert_module_to_f32)
|
| 149 |
+
|
| 150 |
+
def initialize_weights(self) -> None:
|
| 151 |
+
# Initialize transformer layers:
|
| 152 |
+
def _basic_init(module):
|
| 153 |
+
if isinstance(module, nn.Linear):
|
| 154 |
+
torch.nn.init.xavier_uniform_(module.weight)
|
| 155 |
+
if module.bias is not None:
|
| 156 |
+
nn.init.constant_(module.bias, 0)
|
| 157 |
+
self.apply(_basic_init)
|
| 158 |
+
|
| 159 |
+
# Initialize timestep embedding MLP:
|
| 160 |
+
nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02)
|
| 161 |
+
nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
|
| 162 |
+
|
| 163 |
+
# Zero-out adaLN modulation layers in DiT blocks:
|
| 164 |
+
if self.share_mod:
|
| 165 |
+
nn.init.constant_(self.adaLN_modulation[-1].weight, 0)
|
| 166 |
+
nn.init.constant_(self.adaLN_modulation[-1].bias, 0)
|
| 167 |
+
else:
|
| 168 |
+
for block in self.blocks:
|
| 169 |
+
nn.init.constant_(block.adaLN_modulation[-1].weight, 0)
|
| 170 |
+
nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
|
| 171 |
+
|
| 172 |
+
# Zero-out output layers:
|
| 173 |
+
nn.init.constant_(self.out_layer.weight, 0)
|
| 174 |
+
nn.init.constant_(self.out_layer.bias, 0)
|
| 175 |
+
|
| 176 |
+
def forward(self, x: torch.Tensor, t: torch.Tensor, cond: torch.Tensor) -> torch.Tensor:
|
| 177 |
+
assert [*x.shape] == [x.shape[0], self.in_channels, *[self.resolution] * 3], \
|
| 178 |
+
f"Input shape mismatch, got {x.shape}, expected {[x.shape[0], self.in_channels, *[self.resolution] * 3]}"
|
| 179 |
+
|
| 180 |
+
h = patchify(x, self.patch_size)
|
| 181 |
+
h = h.view(*h.shape[:2], -1).permute(0, 2, 1).contiguous()
|
| 182 |
+
|
| 183 |
+
h = self.input_layer(h)
|
| 184 |
+
h = h + self.pos_emb[None]
|
| 185 |
+
t_emb = self.t_embedder(t)
|
| 186 |
+
if self.share_mod:
|
| 187 |
+
t_emb = self.adaLN_modulation(t_emb)
|
| 188 |
+
t_emb = t_emb.type(self.dtype)
|
| 189 |
+
h = h.type(self.dtype)
|
| 190 |
+
cond = cond.type(self.dtype)
|
| 191 |
+
for block in self.blocks:
|
| 192 |
+
h = block(h, t_emb, cond)
|
| 193 |
+
h = h.type(x.dtype)
|
| 194 |
+
h = F.layer_norm(h, h.shape[-1:])
|
| 195 |
+
h = self.out_layer(h)
|
| 196 |
+
|
| 197 |
+
h = h.permute(0, 2, 1).view(h.shape[0], h.shape[2], *[self.resolution // self.patch_size] * 3)
|
| 198 |
+
h = unpatchify(h, self.patch_size).contiguous()
|
| 199 |
+
|
| 200 |
+
return h
|
TRELLIS/trellis/models/sparse_structure_vae.py
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import *
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from ..modules.norm import GroupNorm32, ChannelLayerNorm32
|
| 6 |
+
from ..modules.spatial import pixel_shuffle_3d
|
| 7 |
+
from ..modules.utils import zero_module, convert_module_to_f16, convert_module_to_f32
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def norm_layer(norm_type: str, *args, **kwargs) -> nn.Module:
|
| 11 |
+
"""
|
| 12 |
+
Return a normalization layer.
|
| 13 |
+
"""
|
| 14 |
+
if norm_type == "group":
|
| 15 |
+
return GroupNorm32(32, *args, **kwargs)
|
| 16 |
+
elif norm_type == "layer":
|
| 17 |
+
return ChannelLayerNorm32(*args, **kwargs)
|
| 18 |
+
else:
|
| 19 |
+
raise ValueError(f"Invalid norm type {norm_type}")
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class ResBlock3d(nn.Module):
|
| 23 |
+
def __init__(
|
| 24 |
+
self,
|
| 25 |
+
channels: int,
|
| 26 |
+
out_channels: Optional[int] = None,
|
| 27 |
+
norm_type: Literal["group", "layer"] = "layer",
|
| 28 |
+
):
|
| 29 |
+
super().__init__()
|
| 30 |
+
self.channels = channels
|
| 31 |
+
self.out_channels = out_channels or channels
|
| 32 |
+
|
| 33 |
+
self.norm1 = norm_layer(norm_type, channels)
|
| 34 |
+
self.norm2 = norm_layer(norm_type, self.out_channels)
|
| 35 |
+
self.conv1 = nn.Conv3d(channels, self.out_channels, 3, padding=1)
|
| 36 |
+
self.conv2 = zero_module(nn.Conv3d(self.out_channels, self.out_channels, 3, padding=1))
|
| 37 |
+
self.skip_connection = nn.Conv3d(channels, self.out_channels, 1) if channels != self.out_channels else nn.Identity()
|
| 38 |
+
|
| 39 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 40 |
+
h = self.norm1(x)
|
| 41 |
+
h = F.silu(h)
|
| 42 |
+
h = self.conv1(h)
|
| 43 |
+
h = self.norm2(h)
|
| 44 |
+
h = F.silu(h)
|
| 45 |
+
h = self.conv2(h)
|
| 46 |
+
h = h + self.skip_connection(x)
|
| 47 |
+
return h
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class DownsampleBlock3d(nn.Module):
|
| 51 |
+
def __init__(
|
| 52 |
+
self,
|
| 53 |
+
in_channels: int,
|
| 54 |
+
out_channels: int,
|
| 55 |
+
mode: Literal["conv", "avgpool"] = "conv",
|
| 56 |
+
):
|
| 57 |
+
assert mode in ["conv", "avgpool"], f"Invalid mode {mode}"
|
| 58 |
+
|
| 59 |
+
super().__init__()
|
| 60 |
+
self.in_channels = in_channels
|
| 61 |
+
self.out_channels = out_channels
|
| 62 |
+
|
| 63 |
+
if mode == "conv":
|
| 64 |
+
self.conv = nn.Conv3d(in_channels, out_channels, 2, stride=2)
|
| 65 |
+
elif mode == "avgpool":
|
| 66 |
+
assert in_channels == out_channels, "Pooling mode requires in_channels to be equal to out_channels"
|
| 67 |
+
|
| 68 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 69 |
+
if hasattr(self, "conv"):
|
| 70 |
+
return self.conv(x)
|
| 71 |
+
else:
|
| 72 |
+
return F.avg_pool3d(x, 2)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class UpsampleBlock3d(nn.Module):
|
| 76 |
+
def __init__(
|
| 77 |
+
self,
|
| 78 |
+
in_channels: int,
|
| 79 |
+
out_channels: int,
|
| 80 |
+
mode: Literal["conv", "nearest"] = "conv",
|
| 81 |
+
):
|
| 82 |
+
assert mode in ["conv", "nearest"], f"Invalid mode {mode}"
|
| 83 |
+
|
| 84 |
+
super().__init__()
|
| 85 |
+
self.in_channels = in_channels
|
| 86 |
+
self.out_channels = out_channels
|
| 87 |
+
|
| 88 |
+
if mode == "conv":
|
| 89 |
+
self.conv = nn.Conv3d(in_channels, out_channels*8, 3, padding=1)
|
| 90 |
+
elif mode == "nearest":
|
| 91 |
+
assert in_channels == out_channels, "Nearest mode requires in_channels to be equal to out_channels"
|
| 92 |
+
|
| 93 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 94 |
+
if hasattr(self, "conv"):
|
| 95 |
+
x = self.conv(x)
|
| 96 |
+
return pixel_shuffle_3d(x, 2)
|
| 97 |
+
else:
|
| 98 |
+
return F.interpolate(x, scale_factor=2, mode="nearest")
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class SparseStructureEncoder(nn.Module):
|
| 102 |
+
"""
|
| 103 |
+
Encoder for Sparse Structure (\mathcal{E}_S in the paper Sec. 3.3).
|
| 104 |
+
|
| 105 |
+
Args:
|
| 106 |
+
in_channels (int): Channels of the input.
|
| 107 |
+
latent_channels (int): Channels of the latent representation.
|
| 108 |
+
num_res_blocks (int): Number of residual blocks at each resolution.
|
| 109 |
+
channels (List[int]): Channels of the encoder blocks.
|
| 110 |
+
num_res_blocks_middle (int): Number of residual blocks in the middle.
|
| 111 |
+
norm_type (Literal["group", "layer"]): Type of normalization layer.
|
| 112 |
+
use_fp16 (bool): Whether to use FP16.
|
| 113 |
+
"""
|
| 114 |
+
def __init__(
|
| 115 |
+
self,
|
| 116 |
+
in_channels: int,
|
| 117 |
+
latent_channels: int,
|
| 118 |
+
num_res_blocks: int,
|
| 119 |
+
channels: List[int],
|
| 120 |
+
num_res_blocks_middle: int = 2,
|
| 121 |
+
norm_type: Literal["group", "layer"] = "layer",
|
| 122 |
+
use_fp16: bool = False,
|
| 123 |
+
):
|
| 124 |
+
super().__init__()
|
| 125 |
+
self.in_channels = in_channels
|
| 126 |
+
self.latent_channels = latent_channels
|
| 127 |
+
self.num_res_blocks = num_res_blocks
|
| 128 |
+
self.channels = channels
|
| 129 |
+
self.num_res_blocks_middle = num_res_blocks_middle
|
| 130 |
+
self.norm_type = norm_type
|
| 131 |
+
self.use_fp16 = use_fp16
|
| 132 |
+
self.dtype = torch.float16 if use_fp16 else torch.float32
|
| 133 |
+
|
| 134 |
+
self.input_layer = nn.Conv3d(in_channels, channels[0], 3, padding=1)
|
| 135 |
+
|
| 136 |
+
self.blocks = nn.ModuleList([])
|
| 137 |
+
for i, ch in enumerate(channels):
|
| 138 |
+
self.blocks.extend([
|
| 139 |
+
ResBlock3d(ch, ch)
|
| 140 |
+
for _ in range(num_res_blocks)
|
| 141 |
+
])
|
| 142 |
+
if i < len(channels) - 1:
|
| 143 |
+
self.blocks.append(
|
| 144 |
+
DownsampleBlock3d(ch, channels[i+1])
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
self.middle_block = nn.Sequential(*[
|
| 148 |
+
ResBlock3d(channels[-1], channels[-1])
|
| 149 |
+
for _ in range(num_res_blocks_middle)
|
| 150 |
+
])
|
| 151 |
+
|
| 152 |
+
self.out_layer = nn.Sequential(
|
| 153 |
+
norm_layer(norm_type, channels[-1]),
|
| 154 |
+
nn.SiLU(),
|
| 155 |
+
nn.Conv3d(channels[-1], latent_channels*2, 3, padding=1)
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
if use_fp16:
|
| 159 |
+
self.convert_to_fp16()
|
| 160 |
+
|
| 161 |
+
@property
|
| 162 |
+
def device(self) -> torch.device:
|
| 163 |
+
"""
|
| 164 |
+
Return the device of the model.
|
| 165 |
+
"""
|
| 166 |
+
return next(self.parameters()).device
|
| 167 |
+
|
| 168 |
+
def convert_to_fp16(self) -> None:
|
| 169 |
+
"""
|
| 170 |
+
Convert the torso of the model to float16.
|
| 171 |
+
"""
|
| 172 |
+
self.use_fp16 = True
|
| 173 |
+
self.dtype = torch.float16
|
| 174 |
+
self.blocks.apply(convert_module_to_f16)
|
| 175 |
+
self.middle_block.apply(convert_module_to_f16)
|
| 176 |
+
|
| 177 |
+
def convert_to_fp32(self) -> None:
|
| 178 |
+
"""
|
| 179 |
+
Convert the torso of the model to float32.
|
| 180 |
+
"""
|
| 181 |
+
self.use_fp16 = False
|
| 182 |
+
self.dtype = torch.float32
|
| 183 |
+
self.blocks.apply(convert_module_to_f32)
|
| 184 |
+
self.middle_block.apply(convert_module_to_f32)
|
| 185 |
+
|
| 186 |
+
def forward(self, x: torch.Tensor, sample_posterior: bool = False, return_raw: bool = False) -> torch.Tensor:
|
| 187 |
+
h = self.input_layer(x)
|
| 188 |
+
h = h.type(self.dtype)
|
| 189 |
+
|
| 190 |
+
for block in self.blocks:
|
| 191 |
+
h = block(h)
|
| 192 |
+
h = self.middle_block(h)
|
| 193 |
+
|
| 194 |
+
h = h.type(x.dtype)
|
| 195 |
+
h = self.out_layer(h)
|
| 196 |
+
|
| 197 |
+
mean, logvar = h.chunk(2, dim=1)
|
| 198 |
+
|
| 199 |
+
if sample_posterior:
|
| 200 |
+
std = torch.exp(0.5 * logvar)
|
| 201 |
+
z = mean + std * torch.randn_like(std)
|
| 202 |
+
else:
|
| 203 |
+
z = mean
|
| 204 |
+
|
| 205 |
+
if return_raw:
|
| 206 |
+
return z, mean, logvar
|
| 207 |
+
return z
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
class SparseStructureDecoder(nn.Module):
|
| 211 |
+
"""
|
| 212 |
+
Decoder for Sparse Structure (\mathcal{D}_S in the paper Sec. 3.3).
|
| 213 |
+
|
| 214 |
+
Args:
|
| 215 |
+
out_channels (int): Channels of the output.
|
| 216 |
+
latent_channels (int): Channels of the latent representation.
|
| 217 |
+
num_res_blocks (int): Number of residual blocks at each resolution.
|
| 218 |
+
channels (List[int]): Channels of the decoder blocks.
|
| 219 |
+
num_res_blocks_middle (int): Number of residual blocks in the middle.
|
| 220 |
+
norm_type (Literal["group", "layer"]): Type of normalization layer.
|
| 221 |
+
use_fp16 (bool): Whether to use FP16.
|
| 222 |
+
"""
|
| 223 |
+
def __init__(
|
| 224 |
+
self,
|
| 225 |
+
out_channels: int,
|
| 226 |
+
latent_channels: int,
|
| 227 |
+
num_res_blocks: int,
|
| 228 |
+
channels: List[int],
|
| 229 |
+
num_res_blocks_middle: int = 2,
|
| 230 |
+
norm_type: Literal["group", "layer"] = "layer",
|
| 231 |
+
use_fp16: bool = False,
|
| 232 |
+
):
|
| 233 |
+
super().__init__()
|
| 234 |
+
self.out_channels = out_channels
|
| 235 |
+
self.latent_channels = latent_channels
|
| 236 |
+
self.num_res_blocks = num_res_blocks
|
| 237 |
+
self.channels = channels
|
| 238 |
+
self.num_res_blocks_middle = num_res_blocks_middle
|
| 239 |
+
self.norm_type = norm_type
|
| 240 |
+
self.use_fp16 = use_fp16
|
| 241 |
+
self.dtype = torch.float16 if use_fp16 else torch.float32
|
| 242 |
+
|
| 243 |
+
self.input_layer = nn.Conv3d(latent_channels, channels[0], 3, padding=1)
|
| 244 |
+
|
| 245 |
+
self.middle_block = nn.Sequential(*[
|
| 246 |
+
ResBlock3d(channels[0], channels[0])
|
| 247 |
+
for _ in range(num_res_blocks_middle)
|
| 248 |
+
])
|
| 249 |
+
|
| 250 |
+
self.blocks = nn.ModuleList([])
|
| 251 |
+
for i, ch in enumerate(channels):
|
| 252 |
+
self.blocks.extend([
|
| 253 |
+
ResBlock3d(ch, ch)
|
| 254 |
+
for _ in range(num_res_blocks)
|
| 255 |
+
])
|
| 256 |
+
if i < len(channels) - 1:
|
| 257 |
+
self.blocks.append(
|
| 258 |
+
UpsampleBlock3d(ch, channels[i+1])
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
self.out_layer = nn.Sequential(
|
| 262 |
+
norm_layer(norm_type, channels[-1]),
|
| 263 |
+
nn.SiLU(),
|
| 264 |
+
nn.Conv3d(channels[-1], out_channels, 3, padding=1)
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
if use_fp16:
|
| 268 |
+
self.convert_to_fp16()
|
| 269 |
+
|
| 270 |
+
@property
|
| 271 |
+
def device(self) -> torch.device:
|
| 272 |
+
"""
|
| 273 |
+
Return the device of the model.
|
| 274 |
+
"""
|
| 275 |
+
return next(self.parameters()).device
|
| 276 |
+
|
| 277 |
+
def convert_to_fp16(self) -> None:
|
| 278 |
+
"""
|
| 279 |
+
Convert the torso of the model to float16.
|
| 280 |
+
"""
|
| 281 |
+
self.use_fp16 = True
|
| 282 |
+
self.dtype = torch.float16
|
| 283 |
+
self.blocks.apply(convert_module_to_f16)
|
| 284 |
+
self.middle_block.apply(convert_module_to_f16)
|
| 285 |
+
|
| 286 |
+
def convert_to_fp32(self) -> None:
|
| 287 |
+
"""
|
| 288 |
+
Convert the torso of the model to float32.
|
| 289 |
+
"""
|
| 290 |
+
self.use_fp16 = False
|
| 291 |
+
self.dtype = torch.float32
|
| 292 |
+
self.blocks.apply(convert_module_to_f32)
|
| 293 |
+
self.middle_block.apply(convert_module_to_f32)
|
| 294 |
+
|
| 295 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 296 |
+
h = self.input_layer(x)
|
| 297 |
+
|
| 298 |
+
h = h.type(self.dtype)
|
| 299 |
+
|
| 300 |
+
h = self.middle_block(h)
|
| 301 |
+
for block in self.blocks:
|
| 302 |
+
h = block(h)
|
| 303 |
+
|
| 304 |
+
h = h.type(x.dtype)
|
| 305 |
+
h = self.out_layer(h)
|
| 306 |
+
return h
|
TRELLIS/trellis/models/structured_latent_flow.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import *
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
import numpy as np
|
| 6 |
+
from ..modules.utils import zero_module, convert_module_to_f16, convert_module_to_f32
|
| 7 |
+
from ..modules.transformer import AbsolutePositionEmbedder
|
| 8 |
+
from ..modules.norm import LayerNorm32
|
| 9 |
+
from ..modules import sparse as sp
|
| 10 |
+
from ..modules.sparse.transformer import ModulatedSparseTransformerCrossBlock
|
| 11 |
+
from .sparse_structure_flow import TimestepEmbedder
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class SparseResBlock3d(nn.Module):
|
| 15 |
+
def __init__(
|
| 16 |
+
self,
|
| 17 |
+
channels: int,
|
| 18 |
+
emb_channels: int,
|
| 19 |
+
out_channels: Optional[int] = None,
|
| 20 |
+
downsample: bool = False,
|
| 21 |
+
upsample: bool = False,
|
| 22 |
+
):
|
| 23 |
+
super().__init__()
|
| 24 |
+
self.channels = channels
|
| 25 |
+
self.emb_channels = emb_channels
|
| 26 |
+
self.out_channels = out_channels or channels
|
| 27 |
+
self.downsample = downsample
|
| 28 |
+
self.upsample = upsample
|
| 29 |
+
|
| 30 |
+
assert not (downsample and upsample), "Cannot downsample and upsample at the same time"
|
| 31 |
+
|
| 32 |
+
self.norm1 = LayerNorm32(channels, elementwise_affine=True, eps=1e-6)
|
| 33 |
+
self.norm2 = LayerNorm32(self.out_channels, elementwise_affine=False, eps=1e-6)
|
| 34 |
+
self.conv1 = sp.SparseConv3d(channels, self.out_channels, 3)
|
| 35 |
+
self.conv2 = zero_module(sp.SparseConv3d(self.out_channels, self.out_channels, 3))
|
| 36 |
+
self.emb_layers = nn.Sequential(
|
| 37 |
+
nn.SiLU(),
|
| 38 |
+
nn.Linear(emb_channels, 2 * self.out_channels, bias=True),
|
| 39 |
+
)
|
| 40 |
+
self.skip_connection = sp.SparseLinear(channels, self.out_channels) if channels != self.out_channels else nn.Identity()
|
| 41 |
+
self.updown = None
|
| 42 |
+
if self.downsample:
|
| 43 |
+
self.updown = sp.SparseDownsample(2)
|
| 44 |
+
elif self.upsample:
|
| 45 |
+
self.updown = sp.SparseUpsample(2)
|
| 46 |
+
|
| 47 |
+
def _updown(self, x: sp.SparseTensor) -> sp.SparseTensor:
|
| 48 |
+
if self.updown is not None:
|
| 49 |
+
x = self.updown(x)
|
| 50 |
+
return x
|
| 51 |
+
|
| 52 |
+
def forward(self, x: sp.SparseTensor, emb: torch.Tensor) -> sp.SparseTensor:
|
| 53 |
+
emb_out = self.emb_layers(emb).type(x.dtype)
|
| 54 |
+
scale, shift = torch.chunk(emb_out, 2, dim=1)
|
| 55 |
+
|
| 56 |
+
x = self._updown(x)
|
| 57 |
+
h = x.replace(self.norm1(x.feats))
|
| 58 |
+
h = h.replace(F.silu(h.feats))
|
| 59 |
+
h = self.conv1(h)
|
| 60 |
+
h = h.replace(self.norm2(h.feats)) * (1 + scale) + shift
|
| 61 |
+
h = h.replace(F.silu(h.feats))
|
| 62 |
+
h = self.conv2(h)
|
| 63 |
+
h = h + self.skip_connection(x)
|
| 64 |
+
|
| 65 |
+
return h
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class SLatFlowModel(nn.Module):
|
| 69 |
+
def __init__(
|
| 70 |
+
self,
|
| 71 |
+
resolution: int,
|
| 72 |
+
in_channels: int,
|
| 73 |
+
model_channels: int,
|
| 74 |
+
cond_channels: int,
|
| 75 |
+
out_channels: int,
|
| 76 |
+
num_blocks: int,
|
| 77 |
+
num_heads: Optional[int] = None,
|
| 78 |
+
num_head_channels: Optional[int] = 64,
|
| 79 |
+
mlp_ratio: float = 4,
|
| 80 |
+
patch_size: int = 2,
|
| 81 |
+
num_io_res_blocks: int = 2,
|
| 82 |
+
io_block_channels: List[int] = None,
|
| 83 |
+
pe_mode: Literal["ape", "rope"] = "ape",
|
| 84 |
+
use_fp16: bool = False,
|
| 85 |
+
use_checkpoint: bool = False,
|
| 86 |
+
use_skip_connection: bool = True,
|
| 87 |
+
share_mod: bool = False,
|
| 88 |
+
qk_rms_norm: bool = False,
|
| 89 |
+
qk_rms_norm_cross: bool = False,
|
| 90 |
+
):
|
| 91 |
+
super().__init__()
|
| 92 |
+
self.resolution = resolution
|
| 93 |
+
self.in_channels = in_channels
|
| 94 |
+
self.model_channels = model_channels
|
| 95 |
+
self.cond_channels = cond_channels
|
| 96 |
+
self.out_channels = out_channels
|
| 97 |
+
self.num_blocks = num_blocks
|
| 98 |
+
self.num_heads = num_heads or model_channels // num_head_channels
|
| 99 |
+
self.mlp_ratio = mlp_ratio
|
| 100 |
+
self.patch_size = patch_size
|
| 101 |
+
self.num_io_res_blocks = num_io_res_blocks
|
| 102 |
+
self.io_block_channels = io_block_channels
|
| 103 |
+
self.pe_mode = pe_mode
|
| 104 |
+
self.use_fp16 = use_fp16
|
| 105 |
+
self.use_checkpoint = use_checkpoint
|
| 106 |
+
self.use_skip_connection = use_skip_connection
|
| 107 |
+
self.share_mod = share_mod
|
| 108 |
+
self.qk_rms_norm = qk_rms_norm
|
| 109 |
+
self.qk_rms_norm_cross = qk_rms_norm_cross
|
| 110 |
+
self.dtype = torch.float16 if use_fp16 else torch.float32
|
| 111 |
+
|
| 112 |
+
assert int(np.log2(patch_size)) == np.log2(patch_size), "Patch size must be a power of 2"
|
| 113 |
+
assert np.log2(patch_size) == len(io_block_channels), "Number of IO ResBlocks must match the number of stages"
|
| 114 |
+
|
| 115 |
+
self.t_embedder = TimestepEmbedder(model_channels)
|
| 116 |
+
if share_mod:
|
| 117 |
+
self.adaLN_modulation = nn.Sequential(
|
| 118 |
+
nn.SiLU(),
|
| 119 |
+
nn.Linear(model_channels, 6 * model_channels, bias=True)
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
if pe_mode == "ape":
|
| 123 |
+
self.pos_embedder = AbsolutePositionEmbedder(model_channels)
|
| 124 |
+
|
| 125 |
+
self.input_layer = sp.SparseLinear(in_channels, io_block_channels[0])
|
| 126 |
+
self.input_blocks = nn.ModuleList([])
|
| 127 |
+
for chs, next_chs in zip(io_block_channels, io_block_channels[1:] + [model_channels]):
|
| 128 |
+
self.input_blocks.extend([
|
| 129 |
+
SparseResBlock3d(
|
| 130 |
+
chs,
|
| 131 |
+
model_channels,
|
| 132 |
+
out_channels=chs,
|
| 133 |
+
)
|
| 134 |
+
for _ in range(num_io_res_blocks-1)
|
| 135 |
+
])
|
| 136 |
+
self.input_blocks.append(
|
| 137 |
+
SparseResBlock3d(
|
| 138 |
+
chs,
|
| 139 |
+
model_channels,
|
| 140 |
+
out_channels=next_chs,
|
| 141 |
+
downsample=True,
|
| 142 |
+
)
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
self.blocks = nn.ModuleList([
|
| 146 |
+
ModulatedSparseTransformerCrossBlock(
|
| 147 |
+
model_channels,
|
| 148 |
+
cond_channels,
|
| 149 |
+
num_heads=self.num_heads,
|
| 150 |
+
mlp_ratio=self.mlp_ratio,
|
| 151 |
+
attn_mode='full',
|
| 152 |
+
use_checkpoint=self.use_checkpoint,
|
| 153 |
+
use_rope=(pe_mode == "rope"),
|
| 154 |
+
share_mod=self.share_mod,
|
| 155 |
+
qk_rms_norm=self.qk_rms_norm,
|
| 156 |
+
qk_rms_norm_cross=self.qk_rms_norm_cross,
|
| 157 |
+
)
|
| 158 |
+
for _ in range(num_blocks)
|
| 159 |
+
])
|
| 160 |
+
|
| 161 |
+
self.out_blocks = nn.ModuleList([])
|
| 162 |
+
for chs, prev_chs in zip(reversed(io_block_channels), [model_channels] + list(reversed(io_block_channels[1:]))):
|
| 163 |
+
self.out_blocks.append(
|
| 164 |
+
SparseResBlock3d(
|
| 165 |
+
prev_chs * 2 if self.use_skip_connection else prev_chs,
|
| 166 |
+
model_channels,
|
| 167 |
+
out_channels=chs,
|
| 168 |
+
upsample=True,
|
| 169 |
+
)
|
| 170 |
+
)
|
| 171 |
+
self.out_blocks.extend([
|
| 172 |
+
SparseResBlock3d(
|
| 173 |
+
chs * 2 if self.use_skip_connection else chs,
|
| 174 |
+
model_channels,
|
| 175 |
+
out_channels=chs,
|
| 176 |
+
)
|
| 177 |
+
for _ in range(num_io_res_blocks-1)
|
| 178 |
+
])
|
| 179 |
+
self.out_layer = sp.SparseLinear(io_block_channels[0], out_channels)
|
| 180 |
+
|
| 181 |
+
self.initialize_weights()
|
| 182 |
+
if use_fp16:
|
| 183 |
+
self.convert_to_fp16()
|
| 184 |
+
|
| 185 |
+
@property
|
| 186 |
+
def device(self) -> torch.device:
|
| 187 |
+
"""
|
| 188 |
+
Return the device of the model.
|
| 189 |
+
"""
|
| 190 |
+
return next(self.parameters()).device
|
| 191 |
+
|
| 192 |
+
def convert_to_fp16(self) -> None:
|
| 193 |
+
"""
|
| 194 |
+
Convert the torso of the model to float16.
|
| 195 |
+
"""
|
| 196 |
+
self.input_blocks.apply(convert_module_to_f16)
|
| 197 |
+
self.blocks.apply(convert_module_to_f16)
|
| 198 |
+
self.out_blocks.apply(convert_module_to_f16)
|
| 199 |
+
|
| 200 |
+
def convert_to_fp32(self) -> None:
|
| 201 |
+
"""
|
| 202 |
+
Convert the torso of the model to float32.
|
| 203 |
+
"""
|
| 204 |
+
self.input_blocks.apply(convert_module_to_f32)
|
| 205 |
+
self.blocks.apply(convert_module_to_f32)
|
| 206 |
+
self.out_blocks.apply(convert_module_to_f32)
|
| 207 |
+
|
| 208 |
+
def initialize_weights(self) -> None:
|
| 209 |
+
# Initialize transformer layers:
|
| 210 |
+
def _basic_init(module):
|
| 211 |
+
if isinstance(module, nn.Linear):
|
| 212 |
+
torch.nn.init.xavier_uniform_(module.weight)
|
| 213 |
+
if module.bias is not None:
|
| 214 |
+
nn.init.constant_(module.bias, 0)
|
| 215 |
+
self.apply(_basic_init)
|
| 216 |
+
|
| 217 |
+
# Initialize timestep embedding MLP:
|
| 218 |
+
nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02)
|
| 219 |
+
nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
|
| 220 |
+
|
| 221 |
+
# Zero-out adaLN modulation layers in DiT blocks:
|
| 222 |
+
if self.share_mod:
|
| 223 |
+
nn.init.constant_(self.adaLN_modulation[-1].weight, 0)
|
| 224 |
+
nn.init.constant_(self.adaLN_modulation[-1].bias, 0)
|
| 225 |
+
else:
|
| 226 |
+
for block in self.blocks:
|
| 227 |
+
nn.init.constant_(block.adaLN_modulation[-1].weight, 0)
|
| 228 |
+
nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
|
| 229 |
+
|
| 230 |
+
# Zero-out output layers:
|
| 231 |
+
nn.init.constant_(self.out_layer.weight, 0)
|
| 232 |
+
nn.init.constant_(self.out_layer.bias, 0)
|
| 233 |
+
|
| 234 |
+
def forward(self, x: sp.SparseTensor, t: torch.Tensor, cond: torch.Tensor) -> sp.SparseTensor:
|
| 235 |
+
h = self.input_layer(x).type(self.dtype)
|
| 236 |
+
t_emb = self.t_embedder(t)
|
| 237 |
+
if self.share_mod:
|
| 238 |
+
t_emb = self.adaLN_modulation(t_emb)
|
| 239 |
+
t_emb = t_emb.type(self.dtype)
|
| 240 |
+
cond = cond.type(self.dtype)
|
| 241 |
+
|
| 242 |
+
skips = []
|
| 243 |
+
# pack with input blocks
|
| 244 |
+
for block in self.input_blocks:
|
| 245 |
+
h = block(h, t_emb)
|
| 246 |
+
skips.append(h.feats)
|
| 247 |
+
|
| 248 |
+
if self.pe_mode == "ape":
|
| 249 |
+
h = h + self.pos_embedder(h.coords[:, 1:]).type(self.dtype)
|
| 250 |
+
for block in self.blocks:
|
| 251 |
+
h = block(h, t_emb, cond)
|
| 252 |
+
|
| 253 |
+
# unpack with output blocks
|
| 254 |
+
for block, skip in zip(self.out_blocks, reversed(skips)):
|
| 255 |
+
if self.use_skip_connection:
|
| 256 |
+
h = block(h.replace(torch.cat([h.feats, skip], dim=1)), t_emb)
|
| 257 |
+
else:
|
| 258 |
+
h = block(h, t_emb)
|
| 259 |
+
|
| 260 |
+
h = h.replace(F.layer_norm(h.feats, h.feats.shape[-1:]))
|
| 261 |
+
h = self.out_layer(h.type(x.dtype))
|
| 262 |
+
return h
|
TRELLIS/trellis/models/structured_latent_vae/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .encoder import SLatEncoder
|
| 2 |
+
from .decoder_gs import SLatGaussianDecoder
|
| 3 |
+
from .decoder_rf import SLatRadianceFieldDecoder
|
| 4 |
+
from .decoder_mesh import SLatMeshDecoder
|
TRELLIS/trellis/models/structured_latent_vae/base.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import *
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from ...modules.utils import convert_module_to_f16, convert_module_to_f32
|
| 5 |
+
from ...modules import sparse as sp
|
| 6 |
+
from ...modules.transformer import AbsolutePositionEmbedder
|
| 7 |
+
from ...modules.sparse.transformer import SparseTransformerBlock
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def block_attn_config(self):
|
| 11 |
+
"""
|
| 12 |
+
Return the attention configuration of the model.
|
| 13 |
+
"""
|
| 14 |
+
for i in range(self.num_blocks):
|
| 15 |
+
if self.attn_mode == "shift_window":
|
| 16 |
+
yield "serialized", self.window_size, 0, (16 * (i % 2),) * 3, sp.SerializeMode.Z_ORDER
|
| 17 |
+
elif self.attn_mode == "shift_sequence":
|
| 18 |
+
yield "serialized", self.window_size, self.window_size // 2 * (i % 2), (0, 0, 0), sp.SerializeMode.Z_ORDER
|
| 19 |
+
elif self.attn_mode == "shift_order":
|
| 20 |
+
yield "serialized", self.window_size, 0, (0, 0, 0), sp.SerializeModes[i % 4]
|
| 21 |
+
elif self.attn_mode == "full":
|
| 22 |
+
yield "full", None, None, None, None
|
| 23 |
+
elif self.attn_mode == "swin":
|
| 24 |
+
yield "windowed", self.window_size, None, self.window_size // 2 * (i % 2), None
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class SparseTransformerBase(nn.Module):
|
| 28 |
+
"""
|
| 29 |
+
Sparse Transformer without output layers.
|
| 30 |
+
Serve as the base class for encoder and decoder.
|
| 31 |
+
"""
|
| 32 |
+
def __init__(
|
| 33 |
+
self,
|
| 34 |
+
in_channels: int,
|
| 35 |
+
model_channels: int,
|
| 36 |
+
num_blocks: int,
|
| 37 |
+
num_heads: Optional[int] = None,
|
| 38 |
+
num_head_channels: Optional[int] = 64,
|
| 39 |
+
mlp_ratio: float = 4.0,
|
| 40 |
+
attn_mode: Literal["full", "shift_window", "shift_sequence", "shift_order", "swin"] = "full",
|
| 41 |
+
window_size: Optional[int] = None,
|
| 42 |
+
pe_mode: Literal["ape", "rope"] = "ape",
|
| 43 |
+
use_fp16: bool = False,
|
| 44 |
+
use_checkpoint: bool = False,
|
| 45 |
+
qk_rms_norm: bool = False,
|
| 46 |
+
):
|
| 47 |
+
super().__init__()
|
| 48 |
+
self.in_channels = in_channels
|
| 49 |
+
self.model_channels = model_channels
|
| 50 |
+
self.num_blocks = num_blocks
|
| 51 |
+
self.window_size = window_size
|
| 52 |
+
self.num_heads = num_heads or model_channels // num_head_channels
|
| 53 |
+
self.mlp_ratio = mlp_ratio
|
| 54 |
+
self.attn_mode = attn_mode
|
| 55 |
+
self.pe_mode = pe_mode
|
| 56 |
+
self.use_fp16 = use_fp16
|
| 57 |
+
self.use_checkpoint = use_checkpoint
|
| 58 |
+
self.qk_rms_norm = qk_rms_norm
|
| 59 |
+
self.dtype = torch.float16 if use_fp16 else torch.float32
|
| 60 |
+
|
| 61 |
+
if pe_mode == "ape":
|
| 62 |
+
self.pos_embedder = AbsolutePositionEmbedder(model_channels)
|
| 63 |
+
|
| 64 |
+
self.input_layer = sp.SparseLinear(in_channels, model_channels)
|
| 65 |
+
self.blocks = nn.ModuleList([
|
| 66 |
+
SparseTransformerBlock(
|
| 67 |
+
model_channels,
|
| 68 |
+
num_heads=self.num_heads,
|
| 69 |
+
mlp_ratio=self.mlp_ratio,
|
| 70 |
+
attn_mode=attn_mode,
|
| 71 |
+
window_size=window_size,
|
| 72 |
+
shift_sequence=shift_sequence,
|
| 73 |
+
shift_window=shift_window,
|
| 74 |
+
serialize_mode=serialize_mode,
|
| 75 |
+
use_checkpoint=self.use_checkpoint,
|
| 76 |
+
use_rope=(pe_mode == "rope"),
|
| 77 |
+
qk_rms_norm=self.qk_rms_norm,
|
| 78 |
+
)
|
| 79 |
+
for attn_mode, window_size, shift_sequence, shift_window, serialize_mode in block_attn_config(self)
|
| 80 |
+
])
|
| 81 |
+
|
| 82 |
+
@property
|
| 83 |
+
def device(self) -> torch.device:
|
| 84 |
+
"""
|
| 85 |
+
Return the device of the model.
|
| 86 |
+
"""
|
| 87 |
+
return next(self.parameters()).device
|
| 88 |
+
|
| 89 |
+
def convert_to_fp16(self) -> None:
|
| 90 |
+
"""
|
| 91 |
+
Convert the torso of the model to float16.
|
| 92 |
+
"""
|
| 93 |
+
self.blocks.apply(convert_module_to_f16)
|
| 94 |
+
|
| 95 |
+
def convert_to_fp32(self) -> None:
|
| 96 |
+
"""
|
| 97 |
+
Convert the torso of the model to float32.
|
| 98 |
+
"""
|
| 99 |
+
self.blocks.apply(convert_module_to_f32)
|
| 100 |
+
|
| 101 |
+
def initialize_weights(self) -> None:
|
| 102 |
+
# Initialize transformer layers:
|
| 103 |
+
def _basic_init(module):
|
| 104 |
+
if isinstance(module, nn.Linear):
|
| 105 |
+
torch.nn.init.xavier_uniform_(module.weight)
|
| 106 |
+
if module.bias is not None:
|
| 107 |
+
nn.init.constant_(module.bias, 0)
|
| 108 |
+
self.apply(_basic_init)
|
| 109 |
+
|
| 110 |
+
def forward(self, x: sp.SparseTensor) -> sp.SparseTensor:
|
| 111 |
+
h = self.input_layer(x)
|
| 112 |
+
if self.pe_mode == "ape":
|
| 113 |
+
h = h + self.pos_embedder(x.coords[:, 1:])
|
| 114 |
+
h = h.type(self.dtype)
|
| 115 |
+
for block in self.blocks:
|
| 116 |
+
h = block(h)
|
| 117 |
+
return h
|
TRELLIS/trellis/models/structured_latent_vae/decoder_gs.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import *
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from ...modules import sparse as sp
|
| 6 |
+
from ...utils.random_utils import hammersley_sequence
|
| 7 |
+
from .base import SparseTransformerBase
|
| 8 |
+
from ...representations import Gaussian
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class SLatGaussianDecoder(SparseTransformerBase):
|
| 12 |
+
def __init__(
|
| 13 |
+
self,
|
| 14 |
+
resolution: int,
|
| 15 |
+
model_channels: int,
|
| 16 |
+
latent_channels: int,
|
| 17 |
+
num_blocks: int,
|
| 18 |
+
num_heads: Optional[int] = None,
|
| 19 |
+
num_head_channels: Optional[int] = 64,
|
| 20 |
+
mlp_ratio: float = 4,
|
| 21 |
+
attn_mode: Literal["full", "shift_window", "shift_sequence", "shift_order", "swin"] = "swin",
|
| 22 |
+
window_size: int = 8,
|
| 23 |
+
pe_mode: Literal["ape", "rope"] = "ape",
|
| 24 |
+
use_fp16: bool = False,
|
| 25 |
+
use_checkpoint: bool = False,
|
| 26 |
+
qk_rms_norm: bool = False,
|
| 27 |
+
representation_config: dict = None,
|
| 28 |
+
):
|
| 29 |
+
super().__init__(
|
| 30 |
+
in_channels=latent_channels,
|
| 31 |
+
model_channels=model_channels,
|
| 32 |
+
num_blocks=num_blocks,
|
| 33 |
+
num_heads=num_heads,
|
| 34 |
+
num_head_channels=num_head_channels,
|
| 35 |
+
mlp_ratio=mlp_ratio,
|
| 36 |
+
attn_mode=attn_mode,
|
| 37 |
+
window_size=window_size,
|
| 38 |
+
pe_mode=pe_mode,
|
| 39 |
+
use_fp16=use_fp16,
|
| 40 |
+
use_checkpoint=use_checkpoint,
|
| 41 |
+
qk_rms_norm=qk_rms_norm,
|
| 42 |
+
)
|
| 43 |
+
self.resolution = resolution
|
| 44 |
+
self.rep_config = representation_config
|
| 45 |
+
self._calc_layout()
|
| 46 |
+
self.out_layer = sp.SparseLinear(model_channels, self.out_channels)
|
| 47 |
+
self._build_perturbation()
|
| 48 |
+
|
| 49 |
+
self.initialize_weights()
|
| 50 |
+
if use_fp16:
|
| 51 |
+
self.convert_to_fp16()
|
| 52 |
+
|
| 53 |
+
self.part_mask = None
|
| 54 |
+
|
| 55 |
+
def initialize_weights(self) -> None:
|
| 56 |
+
super().initialize_weights()
|
| 57 |
+
# Zero-out output layers:
|
| 58 |
+
nn.init.constant_(self.out_layer.weight, 0)
|
| 59 |
+
nn.init.constant_(self.out_layer.bias, 0)
|
| 60 |
+
|
| 61 |
+
def _build_perturbation(self) -> None:
|
| 62 |
+
perturbation = [hammersley_sequence(3, i, self.rep_config['num_gaussians']) for i in range(self.rep_config['num_gaussians'])]
|
| 63 |
+
perturbation = torch.tensor(perturbation).float() * 2 - 1
|
| 64 |
+
perturbation = perturbation / self.rep_config['voxel_size']
|
| 65 |
+
perturbation = torch.atanh(perturbation).to(self.device)
|
| 66 |
+
self.register_buffer('offset_perturbation', perturbation)
|
| 67 |
+
|
| 68 |
+
def _calc_layout(self) -> None:
|
| 69 |
+
self.layout = {
|
| 70 |
+
'_xyz' : {'shape': (self.rep_config['num_gaussians'], 3), 'size': self.rep_config['num_gaussians'] * 3},
|
| 71 |
+
'_features_dc' : {'shape': (self.rep_config['num_gaussians'], 1, 3), 'size': self.rep_config['num_gaussians'] * 3},
|
| 72 |
+
'_scaling' : {'shape': (self.rep_config['num_gaussians'], 3), 'size': self.rep_config['num_gaussians'] * 3},
|
| 73 |
+
'_rotation' : {'shape': (self.rep_config['num_gaussians'], 4), 'size': self.rep_config['num_gaussians'] * 4},
|
| 74 |
+
'_opacity' : {'shape': (self.rep_config['num_gaussians'], 1), 'size': self.rep_config['num_gaussians']},
|
| 75 |
+
}
|
| 76 |
+
start = 0
|
| 77 |
+
for k, v in self.layout.items():
|
| 78 |
+
v['range'] = (start, start + v['size'])
|
| 79 |
+
start += v['size']
|
| 80 |
+
self.out_channels = start
|
| 81 |
+
|
| 82 |
+
def to_representation(self, x: sp.SparseTensor) -> List[Gaussian]:
|
| 83 |
+
"""
|
| 84 |
+
Convert a batch of network outputs to 3D representations.
|
| 85 |
+
|
| 86 |
+
Args:
|
| 87 |
+
x: The [N x * x C] sparse tensor output by the network.
|
| 88 |
+
|
| 89 |
+
Returns:
|
| 90 |
+
list of representations
|
| 91 |
+
"""
|
| 92 |
+
ret = []
|
| 93 |
+
for i in range(x.shape[0]):
|
| 94 |
+
representation = Gaussian(
|
| 95 |
+
sh_degree=0,
|
| 96 |
+
aabb=[-0.5, -0.5, -0.5, 1.0, 1.0, 1.0],
|
| 97 |
+
mininum_kernel_size = self.rep_config['3d_filter_kernel_size'],
|
| 98 |
+
scaling_bias = self.rep_config['scaling_bias'],
|
| 99 |
+
opacity_bias = self.rep_config['opacity_bias'],
|
| 100 |
+
scaling_activation = self.rep_config['scaling_activation']
|
| 101 |
+
)
|
| 102 |
+
xyz = (x.coords[x.layout[i]][:, 1:].float() + 0.5) / self.resolution
|
| 103 |
+
for k, v in self.layout.items():
|
| 104 |
+
if k == '_xyz':
|
| 105 |
+
offset = x.feats[x.layout[i]][:, v['range'][0]:v['range'][1]].reshape(-1, *v['shape'])
|
| 106 |
+
offset = offset * self.rep_config['lr'][k]
|
| 107 |
+
if self.rep_config['perturb_offset']:
|
| 108 |
+
offset = offset + self.offset_perturbation
|
| 109 |
+
offset = torch.tanh(offset) / self.resolution * 0.5 * self.rep_config['voxel_size']
|
| 110 |
+
_xyz = xyz.unsqueeze(1) + offset
|
| 111 |
+
setattr(representation, k, _xyz.flatten(0, 1))
|
| 112 |
+
else:
|
| 113 |
+
feats = x.feats[x.layout[i]][:, v['range'][0]:v['range'][1]].reshape(-1, *v['shape']).flatten(0, 1)
|
| 114 |
+
feats = feats * self.rep_config['lr'][k]
|
| 115 |
+
setattr(representation, k, feats)
|
| 116 |
+
ret.append(representation)
|
| 117 |
+
return ret
|
| 118 |
+
|
| 119 |
+
def forward(self, x: sp.SparseTensor) -> List[Gaussian]:
|
| 120 |
+
h = super().forward(x)
|
| 121 |
+
h = h.type(x.dtype)
|
| 122 |
+
h = h.replace(F.layer_norm(h.feats, h.feats.shape[-1:]))
|
| 123 |
+
h = self.out_layer(h)
|
| 124 |
+
return self.to_representation(h)
|
TRELLIS/trellis/models/structured_latent_vae/decoder_mesh.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import *
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
import numpy as np
|
| 6 |
+
from ...modules.utils import zero_module, convert_module_to_f16, convert_module_to_f32
|
| 7 |
+
from ...modules import sparse as sp
|
| 8 |
+
from .base import SparseTransformerBase
|
| 9 |
+
from ...representations import MeshExtractResult
|
| 10 |
+
from ...representations.mesh import SparseFeatures2Mesh
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class SparseSubdivideBlock3d(nn.Module):
|
| 14 |
+
"""
|
| 15 |
+
A 3D subdivide block that can subdivide the sparse tensor.
|
| 16 |
+
|
| 17 |
+
Args:
|
| 18 |
+
channels: channels in the inputs and outputs.
|
| 19 |
+
out_channels: if specified, the number of output channels.
|
| 20 |
+
num_groups: the number of groups for the group norm.
|
| 21 |
+
"""
|
| 22 |
+
def __init__(
|
| 23 |
+
self,
|
| 24 |
+
channels: int,
|
| 25 |
+
resolution: int,
|
| 26 |
+
out_channels: Optional[int] = None,
|
| 27 |
+
num_groups: int = 32
|
| 28 |
+
):
|
| 29 |
+
super().__init__()
|
| 30 |
+
self.channels = channels
|
| 31 |
+
self.resolution = resolution
|
| 32 |
+
self.out_resolution = resolution * 2
|
| 33 |
+
self.out_channels = out_channels or channels
|
| 34 |
+
|
| 35 |
+
self.act_layers = nn.Sequential(
|
| 36 |
+
sp.SparseGroupNorm32(num_groups, channels),
|
| 37 |
+
sp.SparseSiLU()
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
self.sub = sp.SparseSubdivide()
|
| 41 |
+
|
| 42 |
+
self.out_layers = nn.Sequential(
|
| 43 |
+
sp.SparseConv3d(channels, self.out_channels, 3, indice_key=f"res_{self.out_resolution}"),
|
| 44 |
+
sp.SparseGroupNorm32(num_groups, self.out_channels),
|
| 45 |
+
sp.SparseSiLU(),
|
| 46 |
+
zero_module(sp.SparseConv3d(self.out_channels, self.out_channels, 3, indice_key=f"res_{self.out_resolution}")),
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
if self.out_channels == channels:
|
| 50 |
+
self.skip_connection = nn.Identity()
|
| 51 |
+
else:
|
| 52 |
+
self.skip_connection = sp.SparseConv3d(channels, self.out_channels, 1, indice_key=f"res_{self.out_resolution}")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def forward(self, x: sp.SparseTensor) -> sp.SparseTensor:
|
| 56 |
+
"""
|
| 57 |
+
Apply the block to a Tensor, conditioned on a timestep embedding.
|
| 58 |
+
|
| 59 |
+
Args:
|
| 60 |
+
x: an [N x C x ...] Tensor of features.
|
| 61 |
+
Returns:
|
| 62 |
+
an [N x C x ...] Tensor of outputs.
|
| 63 |
+
"""
|
| 64 |
+
h = self.act_layers(x)
|
| 65 |
+
h = self.sub(h)
|
| 66 |
+
x = self.sub(x)
|
| 67 |
+
h = self.out_layers(h)
|
| 68 |
+
h = h + self.skip_connection(x)
|
| 69 |
+
return h
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class SLatMeshDecoder(SparseTransformerBase):
|
| 73 |
+
def __init__(
|
| 74 |
+
self,
|
| 75 |
+
resolution: int,
|
| 76 |
+
model_channels: int,
|
| 77 |
+
latent_channels: int,
|
| 78 |
+
num_blocks: int,
|
| 79 |
+
num_heads: Optional[int] = None,
|
| 80 |
+
num_head_channels: Optional[int] = 64,
|
| 81 |
+
mlp_ratio: float = 4,
|
| 82 |
+
attn_mode: Literal["full", "shift_window", "shift_sequence", "shift_order", "swin"] = "swin",
|
| 83 |
+
window_size: int = 8,
|
| 84 |
+
pe_mode: Literal["ape", "rope"] = "ape",
|
| 85 |
+
use_fp16: bool = False,
|
| 86 |
+
use_checkpoint: bool = False,
|
| 87 |
+
qk_rms_norm: bool = False,
|
| 88 |
+
representation_config: dict = None,
|
| 89 |
+
):
|
| 90 |
+
super().__init__(
|
| 91 |
+
in_channels=latent_channels,
|
| 92 |
+
model_channels=model_channels,
|
| 93 |
+
num_blocks=num_blocks,
|
| 94 |
+
num_heads=num_heads,
|
| 95 |
+
num_head_channels=num_head_channels,
|
| 96 |
+
mlp_ratio=mlp_ratio,
|
| 97 |
+
attn_mode=attn_mode,
|
| 98 |
+
window_size=window_size,
|
| 99 |
+
pe_mode=pe_mode,
|
| 100 |
+
use_fp16=use_fp16,
|
| 101 |
+
use_checkpoint=use_checkpoint,
|
| 102 |
+
qk_rms_norm=qk_rms_norm,
|
| 103 |
+
)
|
| 104 |
+
self.resolution = resolution
|
| 105 |
+
self.rep_config = representation_config
|
| 106 |
+
# self.mesh_extractor = SparseFeatures2Mesh(res=self.resolution*4, use_color=self.rep_config.get('use_color', False))
|
| 107 |
+
self.mesh_extractor = SparseFeatures2Mesh(device="cuda", res=self.resolution*4, use_color=True)
|
| 108 |
+
self.out_channels = self.mesh_extractor.feats_channels
|
| 109 |
+
self.upsample = nn.ModuleList([
|
| 110 |
+
SparseSubdivideBlock3d(
|
| 111 |
+
channels=model_channels,
|
| 112 |
+
resolution=resolution,
|
| 113 |
+
out_channels=model_channels // 4
|
| 114 |
+
),
|
| 115 |
+
SparseSubdivideBlock3d(
|
| 116 |
+
channels=model_channels // 4,
|
| 117 |
+
resolution=resolution * 2,
|
| 118 |
+
out_channels=model_channels // 8
|
| 119 |
+
)
|
| 120 |
+
])
|
| 121 |
+
self.out_layer = sp.SparseLinear(model_channels // 8, self.out_channels)
|
| 122 |
+
self.initialize_weights()
|
| 123 |
+
if use_fp16:
|
| 124 |
+
self.convert_to_fp16()
|
| 125 |
+
|
| 126 |
+
self.part_mask = None
|
| 127 |
+
|
| 128 |
+
def initialize_weights(self) -> None:
|
| 129 |
+
super().initialize_weights()
|
| 130 |
+
# Zero-out output layers:
|
| 131 |
+
nn.init.constant_(self.out_layer.weight, 0)
|
| 132 |
+
nn.init.constant_(self.out_layer.bias, 0)
|
| 133 |
+
|
| 134 |
+
def convert_to_fp16(self) -> None:
|
| 135 |
+
"""
|
| 136 |
+
Convert the torso of the model to float16.
|
| 137 |
+
"""
|
| 138 |
+
super().convert_to_fp16()
|
| 139 |
+
self.upsample.apply(convert_module_to_f16)
|
| 140 |
+
|
| 141 |
+
def convert_to_fp32(self) -> None:
|
| 142 |
+
"""
|
| 143 |
+
Convert the torso of the model to float32.
|
| 144 |
+
"""
|
| 145 |
+
super().convert_to_fp32()
|
| 146 |
+
self.upsample.apply(convert_module_to_f32)
|
| 147 |
+
|
| 148 |
+
def to_representation(self, x: sp.SparseTensor) -> List[MeshExtractResult]:
|
| 149 |
+
"""
|
| 150 |
+
Convert a batch of network outputs to 3D representations.
|
| 151 |
+
|
| 152 |
+
Args:
|
| 153 |
+
x: The [N x * x C] sparse tensor output by the network.
|
| 154 |
+
|
| 155 |
+
Returns:
|
| 156 |
+
list of representations
|
| 157 |
+
"""
|
| 158 |
+
ret = []
|
| 159 |
+
x_len = x.shape[0]
|
| 160 |
+
if self.part_mask is not None:
|
| 161 |
+
coords = torch.floor(x.coords[:, 1:] / 4.).long()
|
| 162 |
+
part_mask = self.part_mask[0, 0]
|
| 163 |
+
labels = part_mask[coords[:, 0], coords[:, 1], coords[:, 2]].long()
|
| 164 |
+
x_parts = []
|
| 165 |
+
for i in range(1, self.joint_num + 2):
|
| 166 |
+
if (labels == i).sum() > 0:
|
| 167 |
+
x_parts.append(sp.SparseTensor(
|
| 168 |
+
feats=x.feats[labels == i],
|
| 169 |
+
coords=x.coords[labels == i],
|
| 170 |
+
))
|
| 171 |
+
else:
|
| 172 |
+
x_parts.append(None)
|
| 173 |
+
x_len = len(x_parts)
|
| 174 |
+
x = x_parts
|
| 175 |
+
for i in range(x_len):
|
| 176 |
+
if x[i] is not None:
|
| 177 |
+
mesh = self.mesh_extractor(x[i], training=self.training)
|
| 178 |
+
ret.append(mesh)
|
| 179 |
+
else:
|
| 180 |
+
ret.append(None)
|
| 181 |
+
return ret
|
| 182 |
+
|
| 183 |
+
def forward(self, x: sp.SparseTensor) -> List[MeshExtractResult]:
|
| 184 |
+
h = super().forward(x)
|
| 185 |
+
for block in self.upsample:
|
| 186 |
+
h = block(h)
|
| 187 |
+
h = h.type(x.dtype)
|
| 188 |
+
h = self.out_layer(h)
|
| 189 |
+
return self.to_representation(h)
|
TRELLIS/trellis/models/structured_latent_vae/decoder_rf.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import *
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
import numpy as np
|
| 6 |
+
from ...modules import sparse as sp
|
| 7 |
+
from .base import SparseTransformerBase
|
| 8 |
+
from ...representations import Strivec
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class SLatRadianceFieldDecoder(SparseTransformerBase):
|
| 12 |
+
def __init__(
|
| 13 |
+
self,
|
| 14 |
+
resolution: int,
|
| 15 |
+
model_channels: int,
|
| 16 |
+
latent_channels: int,
|
| 17 |
+
num_blocks: int,
|
| 18 |
+
num_heads: Optional[int] = None,
|
| 19 |
+
num_head_channels: Optional[int] = 64,
|
| 20 |
+
mlp_ratio: float = 4,
|
| 21 |
+
attn_mode: Literal["full", "shift_window", "shift_sequence", "shift_order", "swin"] = "swin",
|
| 22 |
+
window_size: int = 8,
|
| 23 |
+
pe_mode: Literal["ape", "rope"] = "ape",
|
| 24 |
+
use_fp16: bool = False,
|
| 25 |
+
use_checkpoint: bool = False,
|
| 26 |
+
qk_rms_norm: bool = False,
|
| 27 |
+
representation_config: dict = None,
|
| 28 |
+
):
|
| 29 |
+
super().__init__(
|
| 30 |
+
in_channels=latent_channels,
|
| 31 |
+
model_channels=model_channels,
|
| 32 |
+
num_blocks=num_blocks,
|
| 33 |
+
num_heads=num_heads,
|
| 34 |
+
num_head_channels=num_head_channels,
|
| 35 |
+
mlp_ratio=mlp_ratio,
|
| 36 |
+
attn_mode=attn_mode,
|
| 37 |
+
window_size=window_size,
|
| 38 |
+
pe_mode=pe_mode,
|
| 39 |
+
use_fp16=use_fp16,
|
| 40 |
+
use_checkpoint=use_checkpoint,
|
| 41 |
+
qk_rms_norm=qk_rms_norm,
|
| 42 |
+
)
|
| 43 |
+
self.resolution = resolution
|
| 44 |
+
self.rep_config = representation_config
|
| 45 |
+
self._calc_layout()
|
| 46 |
+
self.out_layer = sp.SparseLinear(model_channels, self.out_channels)
|
| 47 |
+
|
| 48 |
+
self.initialize_weights()
|
| 49 |
+
if use_fp16:
|
| 50 |
+
self.convert_to_fp16()
|
| 51 |
+
|
| 52 |
+
def initialize_weights(self) -> None:
|
| 53 |
+
super().initialize_weights()
|
| 54 |
+
# Zero-out output layers:
|
| 55 |
+
nn.init.constant_(self.out_layer.weight, 0)
|
| 56 |
+
nn.init.constant_(self.out_layer.bias, 0)
|
| 57 |
+
|
| 58 |
+
def _calc_layout(self) -> None:
|
| 59 |
+
self.layout = {
|
| 60 |
+
'trivec': {'shape': (self.rep_config['rank'], 3, self.rep_config['dim']), 'size': self.rep_config['rank'] * 3 * self.rep_config['dim']},
|
| 61 |
+
'density': {'shape': (self.rep_config['rank'],), 'size': self.rep_config['rank']},
|
| 62 |
+
'features_dc': {'shape': (self.rep_config['rank'], 1, 3), 'size': self.rep_config['rank'] * 3},
|
| 63 |
+
}
|
| 64 |
+
start = 0
|
| 65 |
+
for k, v in self.layout.items():
|
| 66 |
+
v['range'] = (start, start + v['size'])
|
| 67 |
+
start += v['size']
|
| 68 |
+
self.out_channels = start
|
| 69 |
+
|
| 70 |
+
def to_representation(self, x: sp.SparseTensor) -> List[Strivec]:
|
| 71 |
+
"""
|
| 72 |
+
Convert a batch of network outputs to 3D representations.
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
x: The [N x * x C] sparse tensor output by the network.
|
| 76 |
+
|
| 77 |
+
Returns:
|
| 78 |
+
list of representations
|
| 79 |
+
"""
|
| 80 |
+
ret = []
|
| 81 |
+
for i in range(x.shape[0]):
|
| 82 |
+
representation = Strivec(
|
| 83 |
+
sh_degree=0,
|
| 84 |
+
resolution=self.resolution,
|
| 85 |
+
aabb=[-0.5, -0.5, -0.5, 1, 1, 1],
|
| 86 |
+
rank=self.rep_config['rank'],
|
| 87 |
+
dim=self.rep_config['dim'],
|
| 88 |
+
device='cuda',
|
| 89 |
+
)
|
| 90 |
+
representation.density_shift = 0.0
|
| 91 |
+
representation.position = (x.coords[x.layout[i]][:, 1:].float() + 0.5) / self.resolution
|
| 92 |
+
representation.depth = torch.full((representation.position.shape[0], 1), int(np.log2(self.resolution)), dtype=torch.uint8, device='cuda')
|
| 93 |
+
for k, v in self.layout.items():
|
| 94 |
+
setattr(representation, k, x.feats[x.layout[i]][:, v['range'][0]:v['range'][1]].reshape(-1, *v['shape']))
|
| 95 |
+
representation.trivec = representation.trivec + 1
|
| 96 |
+
ret.append(representation)
|
| 97 |
+
return ret
|
| 98 |
+
|
| 99 |
+
def forward(self, x: sp.SparseTensor) -> List[Strivec]:
|
| 100 |
+
h = super().forward(x)
|
| 101 |
+
h = h.type(x.dtype)
|
| 102 |
+
h = h.replace(F.layer_norm(h.feats, h.feats.shape[-1:]))
|
| 103 |
+
h = self.out_layer(h)
|
| 104 |
+
return self.to_representation(h)
|
TRELLIS/trellis/models/structured_latent_vae/encoder.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import *
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from ...modules import sparse as sp
|
| 6 |
+
from .base import SparseTransformerBase
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class SLatEncoder(SparseTransformerBase):
|
| 10 |
+
def __init__(
|
| 11 |
+
self,
|
| 12 |
+
resolution: int,
|
| 13 |
+
in_channels: int,
|
| 14 |
+
model_channels: int,
|
| 15 |
+
latent_channels: int,
|
| 16 |
+
num_blocks: int,
|
| 17 |
+
num_heads: Optional[int] = None,
|
| 18 |
+
num_head_channels: Optional[int] = 64,
|
| 19 |
+
mlp_ratio: float = 4,
|
| 20 |
+
attn_mode: Literal["full", "shift_window", "shift_sequence", "shift_order", "swin"] = "swin",
|
| 21 |
+
window_size: int = 8,
|
| 22 |
+
pe_mode: Literal["ape", "rope"] = "ape",
|
| 23 |
+
use_fp16: bool = False,
|
| 24 |
+
use_checkpoint: bool = False,
|
| 25 |
+
qk_rms_norm: bool = False,
|
| 26 |
+
):
|
| 27 |
+
super().__init__(
|
| 28 |
+
in_channels=in_channels,
|
| 29 |
+
model_channels=model_channels,
|
| 30 |
+
num_blocks=num_blocks,
|
| 31 |
+
num_heads=num_heads,
|
| 32 |
+
num_head_channels=num_head_channels,
|
| 33 |
+
mlp_ratio=mlp_ratio,
|
| 34 |
+
attn_mode=attn_mode,
|
| 35 |
+
window_size=window_size,
|
| 36 |
+
pe_mode=pe_mode,
|
| 37 |
+
use_fp16=use_fp16,
|
| 38 |
+
use_checkpoint=use_checkpoint,
|
| 39 |
+
qk_rms_norm=qk_rms_norm,
|
| 40 |
+
)
|
| 41 |
+
self.resolution = resolution
|
| 42 |
+
self.out_layer = sp.SparseLinear(model_channels, 2 * latent_channels)
|
| 43 |
+
|
| 44 |
+
self.initialize_weights()
|
| 45 |
+
if use_fp16:
|
| 46 |
+
self.convert_to_fp16()
|
| 47 |
+
|
| 48 |
+
def initialize_weights(self) -> None:
|
| 49 |
+
super().initialize_weights()
|
| 50 |
+
# Zero-out output layers:
|
| 51 |
+
nn.init.constant_(self.out_layer.weight, 0)
|
| 52 |
+
nn.init.constant_(self.out_layer.bias, 0)
|
| 53 |
+
|
| 54 |
+
def forward(self, x: sp.SparseTensor, sample_posterior=True, return_raw=False):
|
| 55 |
+
h = super().forward(x)
|
| 56 |
+
h = h.type(x.dtype)
|
| 57 |
+
h = h.replace(F.layer_norm(h.feats, h.feats.shape[-1:]))
|
| 58 |
+
h = self.out_layer(h)
|
| 59 |
+
|
| 60 |
+
# Sample from the posterior distribution
|
| 61 |
+
mean, logvar = h.feats.chunk(2, dim=-1)
|
| 62 |
+
if sample_posterior:
|
| 63 |
+
std = torch.exp(0.5 * logvar)
|
| 64 |
+
z = mean + std * torch.randn_like(std)
|
| 65 |
+
else:
|
| 66 |
+
z = mean
|
| 67 |
+
z = h.replace(z)
|
| 68 |
+
|
| 69 |
+
if return_raw:
|
| 70 |
+
return z, mean, logvar
|
| 71 |
+
else:
|
| 72 |
+
return z
|
TRELLIS/trellis/modules/attention/__init__.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import *
|
| 2 |
+
|
| 3 |
+
BACKEND = 'flash_attn'
|
| 4 |
+
DEBUG = False
|
| 5 |
+
|
| 6 |
+
def __from_env():
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
global BACKEND
|
| 10 |
+
global DEBUG
|
| 11 |
+
|
| 12 |
+
env_attn_backend = os.environ.get('ATTN_BACKEND')
|
| 13 |
+
env_sttn_debug = os.environ.get('ATTN_DEBUG')
|
| 14 |
+
|
| 15 |
+
if env_attn_backend is not None and env_attn_backend in ['xformers', 'flash_attn', 'sdpa', 'naive']:
|
| 16 |
+
BACKEND = env_attn_backend
|
| 17 |
+
if env_sttn_debug is not None:
|
| 18 |
+
DEBUG = env_sttn_debug == '1'
|
| 19 |
+
|
| 20 |
+
print(f"[ATTENTION] Using backend: {BACKEND}")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
__from_env()
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def set_backend(backend: Literal['xformers', 'flash_attn']):
|
| 27 |
+
global BACKEND
|
| 28 |
+
BACKEND = backend
|
| 29 |
+
|
| 30 |
+
def set_debug(debug: bool):
|
| 31 |
+
global DEBUG
|
| 32 |
+
DEBUG = debug
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
from .full_attn import *
|
| 36 |
+
from .modules import *
|
TRELLIS/trellis/modules/attention/full_attn.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import *
|
| 2 |
+
import torch
|
| 3 |
+
import math
|
| 4 |
+
from . import DEBUG, BACKEND
|
| 5 |
+
|
| 6 |
+
if BACKEND == 'xformers':
|
| 7 |
+
import xformers.ops as xops
|
| 8 |
+
elif BACKEND == 'flash_attn':
|
| 9 |
+
import flash_attn
|
| 10 |
+
elif BACKEND == 'sdpa':
|
| 11 |
+
from torch.nn.functional import scaled_dot_product_attention as sdpa
|
| 12 |
+
elif BACKEND == 'naive':
|
| 13 |
+
pass
|
| 14 |
+
else:
|
| 15 |
+
raise ValueError(f"Unknown attention backend: {BACKEND}")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
__all__ = [
|
| 19 |
+
'scaled_dot_product_attention',
|
| 20 |
+
]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _naive_sdpa(q, k, v):
|
| 24 |
+
"""
|
| 25 |
+
Naive implementation of scaled dot product attention.
|
| 26 |
+
"""
|
| 27 |
+
q = q.permute(0, 2, 1, 3) # [N, H, L, C]
|
| 28 |
+
k = k.permute(0, 2, 1, 3) # [N, H, L, C]
|
| 29 |
+
v = v.permute(0, 2, 1, 3) # [N, H, L, C]
|
| 30 |
+
scale_factor = 1 / math.sqrt(q.size(-1))
|
| 31 |
+
attn_weight = q @ k.transpose(-2, -1) * scale_factor
|
| 32 |
+
attn_weight = torch.softmax(attn_weight, dim=-1)
|
| 33 |
+
out = attn_weight @ v
|
| 34 |
+
out = out.permute(0, 2, 1, 3) # [N, L, H, C]
|
| 35 |
+
return out
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@overload
|
| 39 |
+
def scaled_dot_product_attention(qkv: torch.Tensor) -> torch.Tensor:
|
| 40 |
+
"""
|
| 41 |
+
Apply scaled dot product attention.
|
| 42 |
+
|
| 43 |
+
Args:
|
| 44 |
+
qkv (torch.Tensor): A [N, L, 3, H, C] tensor containing Qs, Ks, and Vs.
|
| 45 |
+
"""
|
| 46 |
+
...
|
| 47 |
+
|
| 48 |
+
@overload
|
| 49 |
+
def scaled_dot_product_attention(q: torch.Tensor, kv: torch.Tensor) -> torch.Tensor:
|
| 50 |
+
"""
|
| 51 |
+
Apply scaled dot product attention.
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
q (torch.Tensor): A [N, L, H, C] tensor containing Qs.
|
| 55 |
+
kv (torch.Tensor): A [N, L, 2, H, C] tensor containing Ks and Vs.
|
| 56 |
+
"""
|
| 57 |
+
...
|
| 58 |
+
|
| 59 |
+
@overload
|
| 60 |
+
def scaled_dot_product_attention(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor:
|
| 61 |
+
"""
|
| 62 |
+
Apply scaled dot product attention.
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
q (torch.Tensor): A [N, L, H, Ci] tensor containing Qs.
|
| 66 |
+
k (torch.Tensor): A [N, L, H, Ci] tensor containing Ks.
|
| 67 |
+
v (torch.Tensor): A [N, L, H, Co] tensor containing Vs.
|
| 68 |
+
|
| 69 |
+
Note:
|
| 70 |
+
k and v are assumed to have the same coordinate map.
|
| 71 |
+
"""
|
| 72 |
+
...
|
| 73 |
+
|
| 74 |
+
def scaled_dot_product_attention(*args, **kwargs):
|
| 75 |
+
arg_names_dict = {
|
| 76 |
+
1: ['qkv'],
|
| 77 |
+
2: ['q', 'kv'],
|
| 78 |
+
3: ['q', 'k', 'v']
|
| 79 |
+
}
|
| 80 |
+
num_all_args = len(args) + len(kwargs)
|
| 81 |
+
assert num_all_args in arg_names_dict, f"Invalid number of arguments, got {num_all_args}, expected 1, 2, or 3"
|
| 82 |
+
for key in arg_names_dict[num_all_args][len(args):]:
|
| 83 |
+
assert key in kwargs, f"Missing argument {key}"
|
| 84 |
+
|
| 85 |
+
if num_all_args == 1:
|
| 86 |
+
qkv = args[0] if len(args) > 0 else kwargs['qkv']
|
| 87 |
+
assert len(qkv.shape) == 5 and qkv.shape[2] == 3, f"Invalid shape for qkv, got {qkv.shape}, expected [N, L, 3, H, C]"
|
| 88 |
+
device = qkv.device
|
| 89 |
+
|
| 90 |
+
elif num_all_args == 2:
|
| 91 |
+
q = args[0] if len(args) > 0 else kwargs['q']
|
| 92 |
+
kv = args[1] if len(args) > 1 else kwargs['kv']
|
| 93 |
+
assert q.shape[0] == kv.shape[0], f"Batch size mismatch, got {q.shape[0]} and {kv.shape[0]}"
|
| 94 |
+
assert len(q.shape) == 4, f"Invalid shape for q, got {q.shape}, expected [N, L, H, C]"
|
| 95 |
+
assert len(kv.shape) == 5, f"Invalid shape for kv, got {kv.shape}, expected [N, L, 2, H, C]"
|
| 96 |
+
device = q.device
|
| 97 |
+
|
| 98 |
+
elif num_all_args == 3:
|
| 99 |
+
q = args[0] if len(args) > 0 else kwargs['q']
|
| 100 |
+
k = args[1] if len(args) > 1 else kwargs['k']
|
| 101 |
+
v = args[2] if len(args) > 2 else kwargs['v']
|
| 102 |
+
assert q.shape[0] == k.shape[0] == v.shape[0], f"Batch size mismatch, got {q.shape[0]}, {k.shape[0]}, and {v.shape[0]}"
|
| 103 |
+
assert len(q.shape) == 4, f"Invalid shape for q, got {q.shape}, expected [N, L, H, Ci]"
|
| 104 |
+
assert len(k.shape) == 4, f"Invalid shape for k, got {k.shape}, expected [N, L, H, Ci]"
|
| 105 |
+
assert len(v.shape) == 4, f"Invalid shape for v, got {v.shape}, expected [N, L, H, Co]"
|
| 106 |
+
device = q.device
|
| 107 |
+
|
| 108 |
+
if BACKEND == 'xformers':
|
| 109 |
+
if num_all_args == 1:
|
| 110 |
+
q, k, v = qkv.unbind(dim=2)
|
| 111 |
+
elif num_all_args == 2:
|
| 112 |
+
k, v = kv.unbind(dim=2)
|
| 113 |
+
out = xops.memory_efficient_attention(q, k, v)
|
| 114 |
+
elif BACKEND == 'flash_attn':
|
| 115 |
+
if num_all_args == 1:
|
| 116 |
+
out = flash_attn.flash_attn_qkvpacked_func(qkv)
|
| 117 |
+
elif num_all_args == 2:
|
| 118 |
+
out = flash_attn.flash_attn_kvpacked_func(q, kv)
|
| 119 |
+
elif num_all_args == 3:
|
| 120 |
+
out = flash_attn.flash_attn_func(q, k, v)
|
| 121 |
+
elif BACKEND == 'sdpa':
|
| 122 |
+
if num_all_args == 1:
|
| 123 |
+
q, k, v = qkv.unbind(dim=2)
|
| 124 |
+
elif num_all_args == 2:
|
| 125 |
+
k, v = kv.unbind(dim=2)
|
| 126 |
+
q = q.permute(0, 2, 1, 3) # [N, H, L, C]
|
| 127 |
+
k = k.permute(0, 2, 1, 3) # [N, H, L, C]
|
| 128 |
+
v = v.permute(0, 2, 1, 3) # [N, H, L, C]
|
| 129 |
+
out = sdpa(q, k, v) # [N, H, L, C]
|
| 130 |
+
out = out.permute(0, 2, 1, 3) # [N, L, H, C]
|
| 131 |
+
elif BACKEND == 'naive':
|
| 132 |
+
if num_all_args == 1:
|
| 133 |
+
q, k, v = qkv.unbind(dim=2)
|
| 134 |
+
elif num_all_args == 2:
|
| 135 |
+
k, v = kv.unbind(dim=2)
|
| 136 |
+
out = _naive_sdpa(q, k, v)
|
| 137 |
+
else:
|
| 138 |
+
raise ValueError(f"Unknown attention module: {BACKEND}")
|
| 139 |
+
|
| 140 |
+
return out
|
TRELLIS/trellis/modules/attention/modules.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import *
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from .full_attn import scaled_dot_product_attention
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class MultiHeadRMSNorm(nn.Module):
|
| 9 |
+
def __init__(self, dim: int, heads: int):
|
| 10 |
+
super().__init__()
|
| 11 |
+
self.scale = dim ** 0.5
|
| 12 |
+
self.gamma = nn.Parameter(torch.ones(heads, dim))
|
| 13 |
+
|
| 14 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 15 |
+
return (F.normalize(x.float(), dim = -1) * self.gamma * self.scale).to(x.dtype)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class RotaryPositionEmbedder(nn.Module):
|
| 19 |
+
def __init__(self, hidden_size: int, in_channels: int = 3):
|
| 20 |
+
super().__init__()
|
| 21 |
+
assert hidden_size % 2 == 0, "Hidden size must be divisible by 2"
|
| 22 |
+
self.hidden_size = hidden_size
|
| 23 |
+
self.in_channels = in_channels
|
| 24 |
+
self.freq_dim = hidden_size // in_channels // 2
|
| 25 |
+
self.freqs = torch.arange(self.freq_dim, dtype=torch.float32) / self.freq_dim
|
| 26 |
+
self.freqs = 1.0 / (10000 ** self.freqs)
|
| 27 |
+
|
| 28 |
+
def _get_phases(self, indices: torch.Tensor) -> torch.Tensor:
|
| 29 |
+
self.freqs = self.freqs.to(indices.device)
|
| 30 |
+
phases = torch.outer(indices, self.freqs)
|
| 31 |
+
phases = torch.polar(torch.ones_like(phases), phases)
|
| 32 |
+
return phases
|
| 33 |
+
|
| 34 |
+
def _rotary_embedding(self, x: torch.Tensor, phases: torch.Tensor) -> torch.Tensor:
|
| 35 |
+
x_complex = torch.view_as_complex(x.float().reshape(*x.shape[:-1], -1, 2))
|
| 36 |
+
x_rotated = x_complex * phases
|
| 37 |
+
x_embed = torch.view_as_real(x_rotated).reshape(*x_rotated.shape[:-1], -1).to(x.dtype)
|
| 38 |
+
return x_embed
|
| 39 |
+
|
| 40 |
+
def forward(self, q: torch.Tensor, k: torch.Tensor, indices: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 41 |
+
"""
|
| 42 |
+
Args:
|
| 43 |
+
q (sp.SparseTensor): [..., N, D] tensor of queries
|
| 44 |
+
k (sp.SparseTensor): [..., N, D] tensor of keys
|
| 45 |
+
indices (torch.Tensor): [..., N, C] tensor of spatial positions
|
| 46 |
+
"""
|
| 47 |
+
if indices is None:
|
| 48 |
+
indices = torch.arange(q.shape[-2], device=q.device)
|
| 49 |
+
if len(q.shape) > 2:
|
| 50 |
+
indices = indices.unsqueeze(0).expand(q.shape[:-2] + (-1,))
|
| 51 |
+
|
| 52 |
+
phases = self._get_phases(indices.reshape(-1)).reshape(*indices.shape[:-1], -1)
|
| 53 |
+
if phases.shape[1] < self.hidden_size // 2:
|
| 54 |
+
phases = torch.cat([phases, torch.polar(
|
| 55 |
+
torch.ones(*phases.shape[:-1], self.hidden_size // 2 - phases.shape[1], device=phases.device),
|
| 56 |
+
torch.zeros(*phases.shape[:-1], self.hidden_size // 2 - phases.shape[1], device=phases.device)
|
| 57 |
+
)], dim=-1)
|
| 58 |
+
q_embed = self._rotary_embedding(q, phases)
|
| 59 |
+
k_embed = self._rotary_embedding(k, phases)
|
| 60 |
+
return q_embed, k_embed
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class MultiHeadAttention(nn.Module):
|
| 64 |
+
def __init__(
|
| 65 |
+
self,
|
| 66 |
+
channels: int,
|
| 67 |
+
num_heads: int,
|
| 68 |
+
ctx_channels: Optional[int]=None,
|
| 69 |
+
type: Literal["self", "cross"] = "self",
|
| 70 |
+
attn_mode: Literal["full", "windowed"] = "full",
|
| 71 |
+
window_size: Optional[int] = None,
|
| 72 |
+
shift_window: Optional[Tuple[int, int, int]] = None,
|
| 73 |
+
qkv_bias: bool = True,
|
| 74 |
+
use_rope: bool = False,
|
| 75 |
+
qk_rms_norm: bool = False,
|
| 76 |
+
):
|
| 77 |
+
super().__init__()
|
| 78 |
+
assert channels % num_heads == 0
|
| 79 |
+
assert type in ["self", "cross"], f"Invalid attention type: {type}"
|
| 80 |
+
assert attn_mode in ["full", "windowed"], f"Invalid attention mode: {attn_mode}"
|
| 81 |
+
assert type == "self" or attn_mode == "full", "Cross-attention only supports full attention"
|
| 82 |
+
|
| 83 |
+
if attn_mode == "windowed":
|
| 84 |
+
raise NotImplementedError("Windowed attention is not yet implemented")
|
| 85 |
+
|
| 86 |
+
self.channels = channels
|
| 87 |
+
self.head_dim = channels // num_heads
|
| 88 |
+
self.ctx_channels = ctx_channels if ctx_channels is not None else channels
|
| 89 |
+
self.num_heads = num_heads
|
| 90 |
+
self._type = type
|
| 91 |
+
self.attn_mode = attn_mode
|
| 92 |
+
self.window_size = window_size
|
| 93 |
+
self.shift_window = shift_window
|
| 94 |
+
self.use_rope = use_rope
|
| 95 |
+
self.qk_rms_norm = qk_rms_norm
|
| 96 |
+
|
| 97 |
+
if self._type == "self":
|
| 98 |
+
self.to_qkv = nn.Linear(channels, channels * 3, bias=qkv_bias)
|
| 99 |
+
else:
|
| 100 |
+
self.to_q = nn.Linear(channels, channels, bias=qkv_bias)
|
| 101 |
+
self.to_kv = nn.Linear(self.ctx_channels, channels * 2, bias=qkv_bias)
|
| 102 |
+
|
| 103 |
+
if self.qk_rms_norm:
|
| 104 |
+
self.q_rms_norm = MultiHeadRMSNorm(self.head_dim, num_heads)
|
| 105 |
+
self.k_rms_norm = MultiHeadRMSNorm(self.head_dim, num_heads)
|
| 106 |
+
|
| 107 |
+
self.to_out = nn.Linear(channels, channels)
|
| 108 |
+
|
| 109 |
+
if use_rope:
|
| 110 |
+
self.rope = RotaryPositionEmbedder(channels)
|
| 111 |
+
|
| 112 |
+
def forward(self, x: torch.Tensor, context: Optional[torch.Tensor] = None, indices: Optional[torch.Tensor] = None) -> torch.Tensor:
|
| 113 |
+
B, L, C = x.shape
|
| 114 |
+
if self._type == "self":
|
| 115 |
+
qkv = self.to_qkv(x)
|
| 116 |
+
qkv = qkv.reshape(B, L, 3, self.num_heads, -1)
|
| 117 |
+
if self.use_rope:
|
| 118 |
+
q, k, v = qkv.unbind(dim=2)
|
| 119 |
+
q, k = self.rope(q, k, indices)
|
| 120 |
+
qkv = torch.stack([q, k, v], dim=2)
|
| 121 |
+
if self.attn_mode == "full":
|
| 122 |
+
if self.qk_rms_norm:
|
| 123 |
+
q, k, v = qkv.unbind(dim=2)
|
| 124 |
+
q = self.q_rms_norm(q)
|
| 125 |
+
k = self.k_rms_norm(k)
|
| 126 |
+
h = scaled_dot_product_attention(q, k, v)
|
| 127 |
+
else:
|
| 128 |
+
h = scaled_dot_product_attention(qkv)
|
| 129 |
+
elif self.attn_mode == "windowed":
|
| 130 |
+
raise NotImplementedError("Windowed attention is not yet implemented")
|
| 131 |
+
else:
|
| 132 |
+
Lkv = context.shape[1]
|
| 133 |
+
q = self.to_q(x)
|
| 134 |
+
kv = self.to_kv(context)
|
| 135 |
+
q = q.reshape(B, L, self.num_heads, -1)
|
| 136 |
+
kv = kv.reshape(B, Lkv, 2, self.num_heads, -1)
|
| 137 |
+
if self.qk_rms_norm:
|
| 138 |
+
q = self.q_rms_norm(q)
|
| 139 |
+
k, v = kv.unbind(dim=2)
|
| 140 |
+
k = self.k_rms_norm(k)
|
| 141 |
+
h = scaled_dot_product_attention(q, k, v)
|
| 142 |
+
else:
|
| 143 |
+
h = scaled_dot_product_attention(q, kv)
|
| 144 |
+
h = h.reshape(B, L, -1)
|
| 145 |
+
h = self.to_out(h)
|
| 146 |
+
return h
|
TRELLIS/trellis/modules/norm.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class LayerNorm32(nn.LayerNorm):
|
| 6 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 7 |
+
return super().forward(x.float()).type(x.dtype)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class GroupNorm32(nn.GroupNorm):
|
| 11 |
+
"""
|
| 12 |
+
A GroupNorm layer that converts to float32 before the forward pass.
|
| 13 |
+
"""
|
| 14 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 15 |
+
return super().forward(x.float()).type(x.dtype)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class ChannelLayerNorm32(LayerNorm32):
|
| 19 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 20 |
+
DIM = x.dim()
|
| 21 |
+
x = x.permute(0, *range(2, DIM), 1).contiguous()
|
| 22 |
+
x = super().forward(x)
|
| 23 |
+
x = x.permute(0, DIM-1, *range(1, DIM-1)).contiguous()
|
| 24 |
+
return x
|
| 25 |
+
|
TRELLIS/trellis/modules/sparse/__init__.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import *
|
| 2 |
+
|
| 3 |
+
BACKEND = 'spconv'
|
| 4 |
+
DEBUG = False
|
| 5 |
+
ATTN = 'flash_attn'
|
| 6 |
+
|
| 7 |
+
def __from_env():
|
| 8 |
+
import os
|
| 9 |
+
|
| 10 |
+
global BACKEND
|
| 11 |
+
global DEBUG
|
| 12 |
+
global ATTN
|
| 13 |
+
|
| 14 |
+
env_sparse_backend = os.environ.get('SPARSE_BACKEND')
|
| 15 |
+
env_sparse_debug = os.environ.get('SPARSE_DEBUG')
|
| 16 |
+
env_sparse_attn = os.environ.get('SPARSE_ATTN_BACKEND')
|
| 17 |
+
if env_sparse_attn is None:
|
| 18 |
+
env_sparse_attn = os.environ.get('ATTN_BACKEND')
|
| 19 |
+
|
| 20 |
+
if env_sparse_backend is not None and env_sparse_backend in ['spconv', 'torchsparse']:
|
| 21 |
+
BACKEND = env_sparse_backend
|
| 22 |
+
if env_sparse_debug is not None:
|
| 23 |
+
DEBUG = env_sparse_debug == '1'
|
| 24 |
+
if env_sparse_attn is not None and env_sparse_attn in ['xformers', 'flash_attn']:
|
| 25 |
+
ATTN = env_sparse_attn
|
| 26 |
+
|
| 27 |
+
print(f"[SPARSE] Backend: {BACKEND}, Attention: {ATTN}")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
__from_env()
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def set_backend(backend: Literal['spconv', 'torchsparse']):
|
| 34 |
+
global BACKEND
|
| 35 |
+
BACKEND = backend
|
| 36 |
+
|
| 37 |
+
def set_debug(debug: bool):
|
| 38 |
+
global DEBUG
|
| 39 |
+
DEBUG = debug
|
| 40 |
+
|
| 41 |
+
def set_attn(attn: Literal['xformers', 'flash_attn']):
|
| 42 |
+
global ATTN
|
| 43 |
+
ATTN = attn
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
import importlib
|
| 47 |
+
|
| 48 |
+
__attributes = {
|
| 49 |
+
'SparseTensor': 'basic',
|
| 50 |
+
'sparse_batch_broadcast': 'basic',
|
| 51 |
+
'sparse_batch_op': 'basic',
|
| 52 |
+
'sparse_cat': 'basic',
|
| 53 |
+
'sparse_unbind': 'basic',
|
| 54 |
+
'SparseGroupNorm': 'norm',
|
| 55 |
+
'SparseLayerNorm': 'norm',
|
| 56 |
+
'SparseGroupNorm32': 'norm',
|
| 57 |
+
'SparseLayerNorm32': 'norm',
|
| 58 |
+
'SparseReLU': 'nonlinearity',
|
| 59 |
+
'SparseSiLU': 'nonlinearity',
|
| 60 |
+
'SparseGELU': 'nonlinearity',
|
| 61 |
+
'SparseActivation': 'nonlinearity',
|
| 62 |
+
'SparseLinear': 'linear',
|
| 63 |
+
'sparse_scaled_dot_product_attention': 'attention',
|
| 64 |
+
'SerializeMode': 'attention',
|
| 65 |
+
'sparse_serialized_scaled_dot_product_self_attention': 'attention',
|
| 66 |
+
'sparse_windowed_scaled_dot_product_self_attention': 'attention',
|
| 67 |
+
'SparseMultiHeadAttention': 'attention',
|
| 68 |
+
'SparseConv3d': 'conv',
|
| 69 |
+
'SparseInverseConv3d': 'conv',
|
| 70 |
+
'SparseDownsample': 'spatial',
|
| 71 |
+
'SparseUpsample': 'spatial',
|
| 72 |
+
'SparseSubdivide' : 'spatial'
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
__submodules = ['transformer']
|
| 76 |
+
|
| 77 |
+
__all__ = list(__attributes.keys()) + __submodules
|
| 78 |
+
|
| 79 |
+
def __getattr__(name):
|
| 80 |
+
if name not in globals():
|
| 81 |
+
if name in __attributes:
|
| 82 |
+
module_name = __attributes[name]
|
| 83 |
+
module = importlib.import_module(f".{module_name}", __name__)
|
| 84 |
+
globals()[name] = getattr(module, name)
|
| 85 |
+
elif name in __submodules:
|
| 86 |
+
module = importlib.import_module(f".{name}", __name__)
|
| 87 |
+
globals()[name] = module
|
| 88 |
+
else:
|
| 89 |
+
raise AttributeError(f"module {__name__} has no attribute {name}")
|
| 90 |
+
return globals()[name]
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
# For Pylance
|
| 94 |
+
if __name__ == '__main__':
|
| 95 |
+
from .basic import *
|
| 96 |
+
from .norm import *
|
| 97 |
+
from .nonlinearity import *
|
| 98 |
+
from .linear import *
|
| 99 |
+
from .attention import *
|
| 100 |
+
from .conv import *
|
| 101 |
+
from .spatial import *
|
| 102 |
+
import transformer
|
TRELLIS/trellis/modules/sparse/attention/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .full_attn import *
|
| 2 |
+
from .serialized_attn import *
|
| 3 |
+
from .windowed_attn import *
|
| 4 |
+
from .modules import *
|
TRELLIS/trellis/modules/sparse/attention/full_attn.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import *
|
| 2 |
+
import torch
|
| 3 |
+
from .. import SparseTensor
|
| 4 |
+
from .. import DEBUG, ATTN
|
| 5 |
+
|
| 6 |
+
if ATTN == 'xformers':
|
| 7 |
+
import xformers.ops as xops
|
| 8 |
+
elif ATTN == 'flash_attn':
|
| 9 |
+
import flash_attn
|
| 10 |
+
else:
|
| 11 |
+
raise ValueError(f"Unknown attention module: {ATTN}")
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
__all__ = [
|
| 15 |
+
'sparse_scaled_dot_product_attention',
|
| 16 |
+
]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@overload
|
| 20 |
+
def sparse_scaled_dot_product_attention(qkv: SparseTensor) -> SparseTensor:
|
| 21 |
+
"""
|
| 22 |
+
Apply scaled dot product attention to a sparse tensor.
|
| 23 |
+
|
| 24 |
+
Args:
|
| 25 |
+
qkv (SparseTensor): A [N, *, 3, H, C] sparse tensor containing Qs, Ks, and Vs.
|
| 26 |
+
"""
|
| 27 |
+
...
|
| 28 |
+
|
| 29 |
+
@overload
|
| 30 |
+
def sparse_scaled_dot_product_attention(q: SparseTensor, kv: Union[SparseTensor, torch.Tensor]) -> SparseTensor:
|
| 31 |
+
"""
|
| 32 |
+
Apply scaled dot product attention to a sparse tensor.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
q (SparseTensor): A [N, *, H, C] sparse tensor containing Qs.
|
| 36 |
+
kv (SparseTensor or torch.Tensor): A [N, *, 2, H, C] sparse tensor or a [N, L, 2, H, C] dense tensor containing Ks and Vs.
|
| 37 |
+
"""
|
| 38 |
+
...
|
| 39 |
+
|
| 40 |
+
@overload
|
| 41 |
+
def sparse_scaled_dot_product_attention(q: torch.Tensor, kv: SparseTensor) -> torch.Tensor:
|
| 42 |
+
"""
|
| 43 |
+
Apply scaled dot product attention to a sparse tensor.
|
| 44 |
+
|
| 45 |
+
Args:
|
| 46 |
+
q (SparseTensor): A [N, L, H, C] dense tensor containing Qs.
|
| 47 |
+
kv (SparseTensor or torch.Tensor): A [N, *, 2, H, C] sparse tensor containing Ks and Vs.
|
| 48 |
+
"""
|
| 49 |
+
...
|
| 50 |
+
|
| 51 |
+
@overload
|
| 52 |
+
def sparse_scaled_dot_product_attention(q: SparseTensor, k: SparseTensor, v: SparseTensor) -> SparseTensor:
|
| 53 |
+
"""
|
| 54 |
+
Apply scaled dot product attention to a sparse tensor.
|
| 55 |
+
|
| 56 |
+
Args:
|
| 57 |
+
q (SparseTensor): A [N, *, H, Ci] sparse tensor containing Qs.
|
| 58 |
+
k (SparseTensor): A [N, *, H, Ci] sparse tensor containing Ks.
|
| 59 |
+
v (SparseTensor): A [N, *, H, Co] sparse tensor containing Vs.
|
| 60 |
+
|
| 61 |
+
Note:
|
| 62 |
+
k and v are assumed to have the same coordinate map.
|
| 63 |
+
"""
|
| 64 |
+
...
|
| 65 |
+
|
| 66 |
+
@overload
|
| 67 |
+
def sparse_scaled_dot_product_attention(q: SparseTensor, k: torch.Tensor, v: torch.Tensor) -> SparseTensor:
|
| 68 |
+
"""
|
| 69 |
+
Apply scaled dot product attention to a sparse tensor.
|
| 70 |
+
|
| 71 |
+
Args:
|
| 72 |
+
q (SparseTensor): A [N, *, H, Ci] sparse tensor containing Qs.
|
| 73 |
+
k (torch.Tensor): A [N, L, H, Ci] dense tensor containing Ks.
|
| 74 |
+
v (torch.Tensor): A [N, L, H, Co] dense tensor containing Vs.
|
| 75 |
+
"""
|
| 76 |
+
...
|
| 77 |
+
|
| 78 |
+
@overload
|
| 79 |
+
def sparse_scaled_dot_product_attention(q: torch.Tensor, k: SparseTensor, v: SparseTensor) -> torch.Tensor:
|
| 80 |
+
"""
|
| 81 |
+
Apply scaled dot product attention to a sparse tensor.
|
| 82 |
+
|
| 83 |
+
Args:
|
| 84 |
+
q (torch.Tensor): A [N, L, H, Ci] dense tensor containing Qs.
|
| 85 |
+
k (SparseTensor): A [N, *, H, Ci] sparse tensor containing Ks.
|
| 86 |
+
v (SparseTensor): A [N, *, H, Co] sparse tensor containing Vs.
|
| 87 |
+
"""
|
| 88 |
+
...
|
| 89 |
+
|
| 90 |
+
def sparse_scaled_dot_product_attention(*args, **kwargs):
|
| 91 |
+
arg_names_dict = {
|
| 92 |
+
1: ['qkv'],
|
| 93 |
+
2: ['q', 'kv'],
|
| 94 |
+
3: ['q', 'k', 'v']
|
| 95 |
+
}
|
| 96 |
+
num_all_args = len(args) + len(kwargs)
|
| 97 |
+
assert num_all_args in arg_names_dict, f"Invalid number of arguments, got {num_all_args}, expected 1, 2, or 3"
|
| 98 |
+
for key in arg_names_dict[num_all_args][len(args):]:
|
| 99 |
+
assert key in kwargs, f"Missing argument {key}"
|
| 100 |
+
|
| 101 |
+
if num_all_args == 1:
|
| 102 |
+
qkv = args[0] if len(args) > 0 else kwargs['qkv']
|
| 103 |
+
assert isinstance(qkv, SparseTensor), f"qkv must be a SparseTensor, got {type(qkv)}"
|
| 104 |
+
assert len(qkv.shape) == 4 and qkv.shape[1] == 3, f"Invalid shape for qkv, got {qkv.shape}, expected [N, *, 3, H, C]"
|
| 105 |
+
device = qkv.device
|
| 106 |
+
|
| 107 |
+
s = qkv
|
| 108 |
+
q_seqlen = [qkv.layout[i].stop - qkv.layout[i].start for i in range(qkv.shape[0])]
|
| 109 |
+
kv_seqlen = q_seqlen
|
| 110 |
+
qkv = qkv.feats # [T, 3, H, C]
|
| 111 |
+
|
| 112 |
+
elif num_all_args == 2:
|
| 113 |
+
q = args[0] if len(args) > 0 else kwargs['q']
|
| 114 |
+
kv = args[1] if len(args) > 1 else kwargs['kv']
|
| 115 |
+
assert isinstance(q, SparseTensor) and isinstance(kv, (SparseTensor, torch.Tensor)) or \
|
| 116 |
+
isinstance(q, torch.Tensor) and isinstance(kv, SparseTensor), \
|
| 117 |
+
f"Invalid types, got {type(q)} and {type(kv)}"
|
| 118 |
+
assert q.shape[0] == kv.shape[0], f"Batch size mismatch, got {q.shape[0]} and {kv.shape[0]}"
|
| 119 |
+
device = q.device
|
| 120 |
+
|
| 121 |
+
if isinstance(q, SparseTensor):
|
| 122 |
+
assert len(q.shape) == 3, f"Invalid shape for q, got {q.shape}, expected [N, *, H, C]"
|
| 123 |
+
s = q
|
| 124 |
+
q_seqlen = [q.layout[i].stop - q.layout[i].start for i in range(q.shape[0])]
|
| 125 |
+
q = q.feats # [T_Q, H, C]
|
| 126 |
+
else:
|
| 127 |
+
assert len(q.shape) == 4, f"Invalid shape for q, got {q.shape}, expected [N, L, H, C]"
|
| 128 |
+
s = None
|
| 129 |
+
N, L, H, C = q.shape
|
| 130 |
+
q_seqlen = [L] * N
|
| 131 |
+
q = q.reshape(N * L, H, C) # [T_Q, H, C]
|
| 132 |
+
|
| 133 |
+
if isinstance(kv, SparseTensor):
|
| 134 |
+
assert len(kv.shape) == 4 and kv.shape[1] == 2, f"Invalid shape for kv, got {kv.shape}, expected [N, *, 2, H, C]"
|
| 135 |
+
kv_seqlen = [kv.layout[i].stop - kv.layout[i].start for i in range(kv.shape[0])]
|
| 136 |
+
kv = kv.feats # [T_KV, 2, H, C]
|
| 137 |
+
else:
|
| 138 |
+
assert len(kv.shape) == 5, f"Invalid shape for kv, got {kv.shape}, expected [N, L, 2, H, C]"
|
| 139 |
+
N, L, _, H, C = kv.shape
|
| 140 |
+
kv_seqlen = [L] * N
|
| 141 |
+
kv = kv.reshape(N * L, 2, H, C) # [T_KV, 2, H, C]
|
| 142 |
+
|
| 143 |
+
elif num_all_args == 3:
|
| 144 |
+
q = args[0] if len(args) > 0 else kwargs['q']
|
| 145 |
+
k = args[1] if len(args) > 1 else kwargs['k']
|
| 146 |
+
v = args[2] if len(args) > 2 else kwargs['v']
|
| 147 |
+
assert isinstance(q, SparseTensor) and isinstance(k, (SparseTensor, torch.Tensor)) and type(k) == type(v) or \
|
| 148 |
+
isinstance(q, torch.Tensor) and isinstance(k, SparseTensor) and isinstance(v, SparseTensor), \
|
| 149 |
+
f"Invalid types, got {type(q)}, {type(k)}, and {type(v)}"
|
| 150 |
+
assert q.shape[0] == k.shape[0] == v.shape[0], f"Batch size mismatch, got {q.shape[0]}, {k.shape[0]}, and {v.shape[0]}"
|
| 151 |
+
device = q.device
|
| 152 |
+
|
| 153 |
+
if isinstance(q, SparseTensor):
|
| 154 |
+
assert len(q.shape) == 3, f"Invalid shape for q, got {q.shape}, expected [N, *, H, Ci]"
|
| 155 |
+
s = q
|
| 156 |
+
q_seqlen = [q.layout[i].stop - q.layout[i].start for i in range(q.shape[0])]
|
| 157 |
+
q = q.feats # [T_Q, H, Ci]
|
| 158 |
+
else:
|
| 159 |
+
assert len(q.shape) == 4, f"Invalid shape for q, got {q.shape}, expected [N, L, H, Ci]"
|
| 160 |
+
s = None
|
| 161 |
+
N, L, H, CI = q.shape
|
| 162 |
+
q_seqlen = [L] * N
|
| 163 |
+
q = q.reshape(N * L, H, CI) # [T_Q, H, Ci]
|
| 164 |
+
|
| 165 |
+
if isinstance(k, SparseTensor):
|
| 166 |
+
assert len(k.shape) == 3, f"Invalid shape for k, got {k.shape}, expected [N, *, H, Ci]"
|
| 167 |
+
assert len(v.shape) == 3, f"Invalid shape for v, got {v.shape}, expected [N, *, H, Co]"
|
| 168 |
+
kv_seqlen = [k.layout[i].stop - k.layout[i].start for i in range(k.shape[0])]
|
| 169 |
+
k = k.feats # [T_KV, H, Ci]
|
| 170 |
+
v = v.feats # [T_KV, H, Co]
|
| 171 |
+
else:
|
| 172 |
+
assert len(k.shape) == 4, f"Invalid shape for k, got {k.shape}, expected [N, L, H, Ci]"
|
| 173 |
+
assert len(v.shape) == 4, f"Invalid shape for v, got {v.shape}, expected [N, L, H, Co]"
|
| 174 |
+
N, L, H, CI, CO = *k.shape, v.shape[-1]
|
| 175 |
+
kv_seqlen = [L] * N
|
| 176 |
+
k = k.reshape(N * L, H, CI) # [T_KV, H, Ci]
|
| 177 |
+
v = v.reshape(N * L, H, CO) # [T_KV, H, Co]
|
| 178 |
+
|
| 179 |
+
if DEBUG:
|
| 180 |
+
if s is not None:
|
| 181 |
+
for i in range(s.shape[0]):
|
| 182 |
+
assert (s.coords[s.layout[i]] == i).all(), f"SparseScaledDotProductSelfAttention: batch index mismatch"
|
| 183 |
+
if num_all_args in [2, 3]:
|
| 184 |
+
assert q.shape[:2] == [1, sum(q_seqlen)], f"SparseScaledDotProductSelfAttention: q shape mismatch"
|
| 185 |
+
if num_all_args == 3:
|
| 186 |
+
assert k.shape[:2] == [1, sum(kv_seqlen)], f"SparseScaledDotProductSelfAttention: k shape mismatch"
|
| 187 |
+
assert v.shape[:2] == [1, sum(kv_seqlen)], f"SparseScaledDotProductSelfAttention: v shape mismatch"
|
| 188 |
+
|
| 189 |
+
if ATTN == 'xformers':
|
| 190 |
+
if num_all_args == 1:
|
| 191 |
+
q, k, v = qkv.unbind(dim=1)
|
| 192 |
+
elif num_all_args == 2:
|
| 193 |
+
k, v = kv.unbind(dim=1)
|
| 194 |
+
q = q.unsqueeze(0)
|
| 195 |
+
k = k.unsqueeze(0)
|
| 196 |
+
v = v.unsqueeze(0)
|
| 197 |
+
mask = xops.fmha.BlockDiagonalMask.from_seqlens(q_seqlen, kv_seqlen)
|
| 198 |
+
out = xops.memory_efficient_attention(q, k, v, mask)[0]
|
| 199 |
+
elif ATTN == 'flash_attn':
|
| 200 |
+
cu_seqlens_q = torch.cat([torch.tensor([0]), torch.cumsum(torch.tensor(q_seqlen), dim=0)]).int().to(device)
|
| 201 |
+
if num_all_args in [2, 3]:
|
| 202 |
+
cu_seqlens_kv = torch.cat([torch.tensor([0]), torch.cumsum(torch.tensor(kv_seqlen), dim=0)]).int().to(device)
|
| 203 |
+
if num_all_args == 1:
|
| 204 |
+
out = flash_attn.flash_attn_varlen_qkvpacked_func(qkv, cu_seqlens_q, max(q_seqlen))
|
| 205 |
+
elif num_all_args == 2:
|
| 206 |
+
out = flash_attn.flash_attn_varlen_kvpacked_func(q, kv, cu_seqlens_q, cu_seqlens_kv, max(q_seqlen), max(kv_seqlen))
|
| 207 |
+
elif num_all_args == 3:
|
| 208 |
+
out = flash_attn.flash_attn_varlen_func(q, k, v, cu_seqlens_q, cu_seqlens_kv, max(q_seqlen), max(kv_seqlen))
|
| 209 |
+
else:
|
| 210 |
+
raise ValueError(f"Unknown attention module: {ATTN}")
|
| 211 |
+
|
| 212 |
+
if s is not None:
|
| 213 |
+
return s.replace(out)
|
| 214 |
+
else:
|
| 215 |
+
return out.reshape(N, L, H, -1)
|
TRELLIS/trellis/modules/sparse/attention/modules.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import *
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from .. import SparseTensor
|
| 6 |
+
from .full_attn import sparse_scaled_dot_product_attention
|
| 7 |
+
from .serialized_attn import SerializeMode, sparse_serialized_scaled_dot_product_self_attention
|
| 8 |
+
from .windowed_attn import sparse_windowed_scaled_dot_product_self_attention
|
| 9 |
+
from ...attention import RotaryPositionEmbedder
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class SparseMultiHeadRMSNorm(nn.Module):
|
| 13 |
+
def __init__(self, dim: int, heads: int):
|
| 14 |
+
super().__init__()
|
| 15 |
+
self.scale = dim ** 0.5
|
| 16 |
+
self.gamma = nn.Parameter(torch.ones(heads, dim))
|
| 17 |
+
|
| 18 |
+
def forward(self, x: Union[SparseTensor, torch.Tensor]) -> Union[SparseTensor, torch.Tensor]:
|
| 19 |
+
x_type = x.dtype
|
| 20 |
+
x = x.float()
|
| 21 |
+
if isinstance(x, SparseTensor):
|
| 22 |
+
x = x.replace(F.normalize(x.feats, dim=-1))
|
| 23 |
+
else:
|
| 24 |
+
x = F.normalize(x, dim=-1)
|
| 25 |
+
return (x * self.gamma * self.scale).to(x_type)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class SparseMultiHeadAttention(nn.Module):
|
| 29 |
+
def __init__(
|
| 30 |
+
self,
|
| 31 |
+
channels: int,
|
| 32 |
+
num_heads: int,
|
| 33 |
+
ctx_channels: Optional[int] = None,
|
| 34 |
+
type: Literal["self", "cross"] = "self",
|
| 35 |
+
attn_mode: Literal["full", "serialized", "windowed"] = "full",
|
| 36 |
+
window_size: Optional[int] = None,
|
| 37 |
+
shift_sequence: Optional[int] = None,
|
| 38 |
+
shift_window: Optional[Tuple[int, int, int]] = None,
|
| 39 |
+
serialize_mode: Optional[SerializeMode] = None,
|
| 40 |
+
qkv_bias: bool = True,
|
| 41 |
+
use_rope: bool = False,
|
| 42 |
+
qk_rms_norm: bool = False,
|
| 43 |
+
):
|
| 44 |
+
super().__init__()
|
| 45 |
+
assert channels % num_heads == 0
|
| 46 |
+
assert type in ["self", "cross"], f"Invalid attention type: {type}"
|
| 47 |
+
assert attn_mode in ["full", "serialized", "windowed"], f"Invalid attention mode: {attn_mode}"
|
| 48 |
+
assert type == "self" or attn_mode == "full", "Cross-attention only supports full attention"
|
| 49 |
+
assert type == "self" or use_rope is False, "Rotary position embeddings only supported for self-attention"
|
| 50 |
+
self.channels = channels
|
| 51 |
+
self.ctx_channels = ctx_channels if ctx_channels is not None else channels
|
| 52 |
+
self.num_heads = num_heads
|
| 53 |
+
self._type = type
|
| 54 |
+
self.attn_mode = attn_mode
|
| 55 |
+
self.window_size = window_size
|
| 56 |
+
self.shift_sequence = shift_sequence
|
| 57 |
+
self.shift_window = shift_window
|
| 58 |
+
self.serialize_mode = serialize_mode
|
| 59 |
+
self.use_rope = use_rope
|
| 60 |
+
self.qk_rms_norm = qk_rms_norm
|
| 61 |
+
|
| 62 |
+
if self._type == "self":
|
| 63 |
+
self.to_qkv = nn.Linear(channels, channels * 3, bias=qkv_bias)
|
| 64 |
+
else:
|
| 65 |
+
self.to_q = nn.Linear(channels, channels, bias=qkv_bias)
|
| 66 |
+
self.to_kv = nn.Linear(self.ctx_channels, channels * 2, bias=qkv_bias)
|
| 67 |
+
|
| 68 |
+
if self.qk_rms_norm:
|
| 69 |
+
self.q_rms_norm = SparseMultiHeadRMSNorm(channels // num_heads, num_heads)
|
| 70 |
+
self.k_rms_norm = SparseMultiHeadRMSNorm(channels // num_heads, num_heads)
|
| 71 |
+
|
| 72 |
+
self.to_out = nn.Linear(channels, channels)
|
| 73 |
+
|
| 74 |
+
if use_rope:
|
| 75 |
+
self.rope = RotaryPositionEmbedder(channels)
|
| 76 |
+
|
| 77 |
+
@staticmethod
|
| 78 |
+
def _linear(module: nn.Linear, x: Union[SparseTensor, torch.Tensor]) -> Union[SparseTensor, torch.Tensor]:
|
| 79 |
+
if isinstance(x, SparseTensor):
|
| 80 |
+
return x.replace(module(x.feats))
|
| 81 |
+
else:
|
| 82 |
+
return module(x)
|
| 83 |
+
|
| 84 |
+
@staticmethod
|
| 85 |
+
def _reshape_chs(x: Union[SparseTensor, torch.Tensor], shape: Tuple[int, ...]) -> Union[SparseTensor, torch.Tensor]:
|
| 86 |
+
if isinstance(x, SparseTensor):
|
| 87 |
+
return x.reshape(*shape)
|
| 88 |
+
else:
|
| 89 |
+
return x.reshape(*x.shape[:2], *shape)
|
| 90 |
+
|
| 91 |
+
def _fused_pre(self, x: Union[SparseTensor, torch.Tensor], num_fused: int) -> Union[SparseTensor, torch.Tensor]:
|
| 92 |
+
if isinstance(x, SparseTensor):
|
| 93 |
+
x_feats = x.feats.unsqueeze(0)
|
| 94 |
+
else:
|
| 95 |
+
x_feats = x
|
| 96 |
+
x_feats = x_feats.reshape(*x_feats.shape[:2], num_fused, self.num_heads, -1)
|
| 97 |
+
return x.replace(x_feats.squeeze(0)) if isinstance(x, SparseTensor) else x_feats
|
| 98 |
+
|
| 99 |
+
def _rope(self, qkv: SparseTensor) -> SparseTensor:
|
| 100 |
+
q, k, v = qkv.feats.unbind(dim=1) # [T, H, C]
|
| 101 |
+
q, k = self.rope(q, k, qkv.coords[:, 1:])
|
| 102 |
+
qkv = qkv.replace(torch.stack([q, k, v], dim=1))
|
| 103 |
+
return qkv
|
| 104 |
+
|
| 105 |
+
def forward(self, x: Union[SparseTensor, torch.Tensor], context: Optional[Union[SparseTensor, torch.Tensor]] = None) -> Union[SparseTensor, torch.Tensor]:
|
| 106 |
+
if self._type == "self":
|
| 107 |
+
qkv = self._linear(self.to_qkv, x)
|
| 108 |
+
qkv = self._fused_pre(qkv, num_fused=3)
|
| 109 |
+
if self.use_rope:
|
| 110 |
+
qkv = self._rope(qkv)
|
| 111 |
+
if self.qk_rms_norm:
|
| 112 |
+
q, k, v = qkv.unbind(dim=1)
|
| 113 |
+
q = self.q_rms_norm(q)
|
| 114 |
+
k = self.k_rms_norm(k)
|
| 115 |
+
qkv = qkv.replace(torch.stack([q.feats, k.feats, v.feats], dim=1))
|
| 116 |
+
if self.attn_mode == "full":
|
| 117 |
+
h = sparse_scaled_dot_product_attention(qkv)
|
| 118 |
+
elif self.attn_mode == "serialized":
|
| 119 |
+
h = sparse_serialized_scaled_dot_product_self_attention(
|
| 120 |
+
qkv, self.window_size, serialize_mode=self.serialize_mode, shift_sequence=self.shift_sequence, shift_window=self.shift_window
|
| 121 |
+
)
|
| 122 |
+
elif self.attn_mode == "windowed":
|
| 123 |
+
h = sparse_windowed_scaled_dot_product_self_attention(
|
| 124 |
+
qkv, self.window_size, shift_window=self.shift_window
|
| 125 |
+
)
|
| 126 |
+
else:
|
| 127 |
+
q = self._linear(self.to_q, x)
|
| 128 |
+
q = self._reshape_chs(q, (self.num_heads, -1))
|
| 129 |
+
kv = self._linear(self.to_kv, context)
|
| 130 |
+
kv = self._fused_pre(kv, num_fused=2)
|
| 131 |
+
if self.qk_rms_norm:
|
| 132 |
+
q = self.q_rms_norm(q)
|
| 133 |
+
k, v = kv.unbind(dim=1)
|
| 134 |
+
k = self.k_rms_norm(k)
|
| 135 |
+
kv = kv.replace(torch.stack([k.feats, v.feats], dim=1))
|
| 136 |
+
h = sparse_scaled_dot_product_attention(q, kv)
|
| 137 |
+
h = self._reshape_chs(h, (-1,))
|
| 138 |
+
h = self._linear(self.to_out, h)
|
| 139 |
+
return h
|
TRELLIS/trellis/modules/sparse/attention/serialized_attn.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import *
|
| 2 |
+
from enum import Enum
|
| 3 |
+
import torch
|
| 4 |
+
import math
|
| 5 |
+
from .. import SparseTensor
|
| 6 |
+
from .. import DEBUG, ATTN
|
| 7 |
+
|
| 8 |
+
if ATTN == 'xformers':
|
| 9 |
+
import xformers.ops as xops
|
| 10 |
+
elif ATTN == 'flash_attn':
|
| 11 |
+
import flash_attn
|
| 12 |
+
else:
|
| 13 |
+
raise ValueError(f"Unknown attention module: {ATTN}")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
__all__ = [
|
| 17 |
+
'sparse_serialized_scaled_dot_product_self_attention',
|
| 18 |
+
]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class SerializeMode(Enum):
|
| 22 |
+
Z_ORDER = 0
|
| 23 |
+
Z_ORDER_TRANSPOSED = 1
|
| 24 |
+
HILBERT = 2
|
| 25 |
+
HILBERT_TRANSPOSED = 3
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
SerializeModes = [
|
| 29 |
+
SerializeMode.Z_ORDER,
|
| 30 |
+
SerializeMode.Z_ORDER_TRANSPOSED,
|
| 31 |
+
SerializeMode.HILBERT,
|
| 32 |
+
SerializeMode.HILBERT_TRANSPOSED
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def calc_serialization(
|
| 37 |
+
tensor: SparseTensor,
|
| 38 |
+
window_size: int,
|
| 39 |
+
serialize_mode: SerializeMode = SerializeMode.Z_ORDER,
|
| 40 |
+
shift_sequence: int = 0,
|
| 41 |
+
shift_window: Tuple[int, int, int] = (0, 0, 0)
|
| 42 |
+
) -> Tuple[torch.Tensor, torch.Tensor, List[int]]:
|
| 43 |
+
"""
|
| 44 |
+
Calculate serialization and partitioning for a set of coordinates.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
tensor (SparseTensor): The input tensor.
|
| 48 |
+
window_size (int): The window size to use.
|
| 49 |
+
serialize_mode (SerializeMode): The serialization mode to use.
|
| 50 |
+
shift_sequence (int): The shift of serialized sequence.
|
| 51 |
+
shift_window (Tuple[int, int, int]): The shift of serialized coordinates.
|
| 52 |
+
|
| 53 |
+
Returns:
|
| 54 |
+
(torch.Tensor, torch.Tensor): Forwards and backwards indices.
|
| 55 |
+
"""
|
| 56 |
+
fwd_indices = []
|
| 57 |
+
bwd_indices = []
|
| 58 |
+
seq_lens = []
|
| 59 |
+
seq_batch_indices = []
|
| 60 |
+
offsets = [0]
|
| 61 |
+
|
| 62 |
+
if 'vox2seq' not in globals():
|
| 63 |
+
import vox2seq
|
| 64 |
+
|
| 65 |
+
# Serialize the input
|
| 66 |
+
serialize_coords = tensor.coords[:, 1:].clone()
|
| 67 |
+
serialize_coords += torch.tensor(shift_window, dtype=torch.int32, device=tensor.device).reshape(1, 3)
|
| 68 |
+
if serialize_mode == SerializeMode.Z_ORDER:
|
| 69 |
+
code = vox2seq.encode(serialize_coords, mode='z_order', permute=[0, 1, 2])
|
| 70 |
+
elif serialize_mode == SerializeMode.Z_ORDER_TRANSPOSED:
|
| 71 |
+
code = vox2seq.encode(serialize_coords, mode='z_order', permute=[1, 0, 2])
|
| 72 |
+
elif serialize_mode == SerializeMode.HILBERT:
|
| 73 |
+
code = vox2seq.encode(serialize_coords, mode='hilbert', permute=[0, 1, 2])
|
| 74 |
+
elif serialize_mode == SerializeMode.HILBERT_TRANSPOSED:
|
| 75 |
+
code = vox2seq.encode(serialize_coords, mode='hilbert', permute=[1, 0, 2])
|
| 76 |
+
else:
|
| 77 |
+
raise ValueError(f"Unknown serialize mode: {serialize_mode}")
|
| 78 |
+
|
| 79 |
+
for bi, s in enumerate(tensor.layout):
|
| 80 |
+
num_points = s.stop - s.start
|
| 81 |
+
num_windows = (num_points + window_size - 1) // window_size
|
| 82 |
+
valid_window_size = num_points / num_windows
|
| 83 |
+
to_ordered = torch.argsort(code[s.start:s.stop])
|
| 84 |
+
if num_windows == 1:
|
| 85 |
+
fwd_indices.append(to_ordered)
|
| 86 |
+
bwd_indices.append(torch.zeros_like(to_ordered).scatter_(0, to_ordered, torch.arange(num_points, device=tensor.device)))
|
| 87 |
+
fwd_indices[-1] += s.start
|
| 88 |
+
bwd_indices[-1] += offsets[-1]
|
| 89 |
+
seq_lens.append(num_points)
|
| 90 |
+
seq_batch_indices.append(bi)
|
| 91 |
+
offsets.append(offsets[-1] + seq_lens[-1])
|
| 92 |
+
else:
|
| 93 |
+
# Partition the input
|
| 94 |
+
offset = 0
|
| 95 |
+
mids = [(i + 0.5) * valid_window_size + shift_sequence for i in range(num_windows)]
|
| 96 |
+
split = [math.floor(i * valid_window_size + shift_sequence) for i in range(num_windows + 1)]
|
| 97 |
+
bwd_index = torch.zeros((num_points,), dtype=torch.int64, device=tensor.device)
|
| 98 |
+
for i in range(num_windows):
|
| 99 |
+
mid = mids[i]
|
| 100 |
+
valid_start = split[i]
|
| 101 |
+
valid_end = split[i + 1]
|
| 102 |
+
padded_start = math.floor(mid - 0.5 * window_size)
|
| 103 |
+
padded_end = padded_start + window_size
|
| 104 |
+
fwd_indices.append(to_ordered[torch.arange(padded_start, padded_end, device=tensor.device) % num_points])
|
| 105 |
+
offset += valid_start - padded_start
|
| 106 |
+
bwd_index.scatter_(0, fwd_indices[-1][valid_start-padded_start:valid_end-padded_start], torch.arange(offset, offset + valid_end - valid_start, device=tensor.device))
|
| 107 |
+
offset += padded_end - valid_start
|
| 108 |
+
fwd_indices[-1] += s.start
|
| 109 |
+
seq_lens.extend([window_size] * num_windows)
|
| 110 |
+
seq_batch_indices.extend([bi] * num_windows)
|
| 111 |
+
bwd_indices.append(bwd_index + offsets[-1])
|
| 112 |
+
offsets.append(offsets[-1] + num_windows * window_size)
|
| 113 |
+
|
| 114 |
+
fwd_indices = torch.cat(fwd_indices)
|
| 115 |
+
bwd_indices = torch.cat(bwd_indices)
|
| 116 |
+
|
| 117 |
+
return fwd_indices, bwd_indices, seq_lens, seq_batch_indices
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def sparse_serialized_scaled_dot_product_self_attention(
|
| 121 |
+
qkv: SparseTensor,
|
| 122 |
+
window_size: int,
|
| 123 |
+
serialize_mode: SerializeMode = SerializeMode.Z_ORDER,
|
| 124 |
+
shift_sequence: int = 0,
|
| 125 |
+
shift_window: Tuple[int, int, int] = (0, 0, 0)
|
| 126 |
+
) -> SparseTensor:
|
| 127 |
+
"""
|
| 128 |
+
Apply serialized scaled dot product self attention to a sparse tensor.
|
| 129 |
+
|
| 130 |
+
Args:
|
| 131 |
+
qkv (SparseTensor): [N, *, 3, H, C] sparse tensor containing Qs, Ks, and Vs.
|
| 132 |
+
window_size (int): The window size to use.
|
| 133 |
+
serialize_mode (SerializeMode): The serialization mode to use.
|
| 134 |
+
shift_sequence (int): The shift of serialized sequence.
|
| 135 |
+
shift_window (Tuple[int, int, int]): The shift of serialized coordinates.
|
| 136 |
+
shift (int): The shift to use.
|
| 137 |
+
"""
|
| 138 |
+
assert len(qkv.shape) == 4 and qkv.shape[1] == 3, f"Invalid shape for qkv, got {qkv.shape}, expected [N, *, 3, H, C]"
|
| 139 |
+
|
| 140 |
+
serialization_spatial_cache_name = f'serialization_{serialize_mode}_{window_size}_{shift_sequence}_{shift_window}'
|
| 141 |
+
serialization_spatial_cache = qkv.get_spatial_cache(serialization_spatial_cache_name)
|
| 142 |
+
if serialization_spatial_cache is None:
|
| 143 |
+
fwd_indices, bwd_indices, seq_lens, seq_batch_indices = calc_serialization(qkv, window_size, serialize_mode, shift_sequence, shift_window)
|
| 144 |
+
qkv.register_spatial_cache(serialization_spatial_cache_name, (fwd_indices, bwd_indices, seq_lens, seq_batch_indices))
|
| 145 |
+
else:
|
| 146 |
+
fwd_indices, bwd_indices, seq_lens, seq_batch_indices = serialization_spatial_cache
|
| 147 |
+
|
| 148 |
+
M = fwd_indices.shape[0]
|
| 149 |
+
T = qkv.feats.shape[0]
|
| 150 |
+
H = qkv.feats.shape[2]
|
| 151 |
+
C = qkv.feats.shape[3]
|
| 152 |
+
|
| 153 |
+
qkv_feats = qkv.feats[fwd_indices] # [M, 3, H, C]
|
| 154 |
+
|
| 155 |
+
if DEBUG:
|
| 156 |
+
start = 0
|
| 157 |
+
qkv_coords = qkv.coords[fwd_indices]
|
| 158 |
+
for i in range(len(seq_lens)):
|
| 159 |
+
assert (qkv_coords[start:start+seq_lens[i], 0] == seq_batch_indices[i]).all(), f"SparseWindowedScaledDotProductSelfAttention: batch index mismatch"
|
| 160 |
+
start += seq_lens[i]
|
| 161 |
+
|
| 162 |
+
if all([seq_len == window_size for seq_len in seq_lens]):
|
| 163 |
+
B = len(seq_lens)
|
| 164 |
+
N = window_size
|
| 165 |
+
qkv_feats = qkv_feats.reshape(B, N, 3, H, C)
|
| 166 |
+
if ATTN == 'xformers':
|
| 167 |
+
q, k, v = qkv_feats.unbind(dim=2) # [B, N, H, C]
|
| 168 |
+
out = xops.memory_efficient_attention(q, k, v) # [B, N, H, C]
|
| 169 |
+
elif ATTN == 'flash_attn':
|
| 170 |
+
out = flash_attn.flash_attn_qkvpacked_func(qkv_feats) # [B, N, H, C]
|
| 171 |
+
else:
|
| 172 |
+
raise ValueError(f"Unknown attention module: {ATTN}")
|
| 173 |
+
out = out.reshape(B * N, H, C) # [M, H, C]
|
| 174 |
+
else:
|
| 175 |
+
if ATTN == 'xformers':
|
| 176 |
+
q, k, v = qkv_feats.unbind(dim=1) # [M, H, C]
|
| 177 |
+
q = q.unsqueeze(0) # [1, M, H, C]
|
| 178 |
+
k = k.unsqueeze(0) # [1, M, H, C]
|
| 179 |
+
v = v.unsqueeze(0) # [1, M, H, C]
|
| 180 |
+
mask = xops.fmha.BlockDiagonalMask.from_seqlens(seq_lens)
|
| 181 |
+
out = xops.memory_efficient_attention(q, k, v, mask)[0] # [M, H, C]
|
| 182 |
+
elif ATTN == 'flash_attn':
|
| 183 |
+
cu_seqlens = torch.cat([torch.tensor([0]), torch.cumsum(torch.tensor(seq_lens), dim=0)], dim=0) \
|
| 184 |
+
.to(qkv.device).int()
|
| 185 |
+
out = flash_attn.flash_attn_varlen_qkvpacked_func(qkv_feats, cu_seqlens, max(seq_lens)) # [M, H, C]
|
| 186 |
+
|
| 187 |
+
out = out[bwd_indices] # [T, H, C]
|
| 188 |
+
|
| 189 |
+
if DEBUG:
|
| 190 |
+
qkv_coords = qkv_coords[bwd_indices]
|
| 191 |
+
assert torch.equal(qkv_coords, qkv.coords), "SparseWindowedScaledDotProductSelfAttention: coordinate mismatch"
|
| 192 |
+
|
| 193 |
+
return qkv.replace(out)
|
TRELLIS/trellis/modules/sparse/attention/windowed_attn.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import *
|
| 2 |
+
import torch
|
| 3 |
+
import math
|
| 4 |
+
from .. import SparseTensor
|
| 5 |
+
from .. import DEBUG, ATTN
|
| 6 |
+
|
| 7 |
+
if ATTN == 'xformers':
|
| 8 |
+
import xformers.ops as xops
|
| 9 |
+
elif ATTN == 'flash_attn':
|
| 10 |
+
import flash_attn
|
| 11 |
+
else:
|
| 12 |
+
raise ValueError(f"Unknown attention module: {ATTN}")
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
__all__ = [
|
| 16 |
+
'sparse_windowed_scaled_dot_product_self_attention',
|
| 17 |
+
]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def calc_window_partition(
|
| 21 |
+
tensor: SparseTensor,
|
| 22 |
+
window_size: Union[int, Tuple[int, ...]],
|
| 23 |
+
shift_window: Union[int, Tuple[int, ...]] = 0
|
| 24 |
+
) -> Tuple[torch.Tensor, torch.Tensor, List[int], List[int]]:
|
| 25 |
+
"""
|
| 26 |
+
Calculate serialization and partitioning for a set of coordinates.
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
tensor (SparseTensor): The input tensor.
|
| 30 |
+
window_size (int): The window size to use.
|
| 31 |
+
shift_window (Tuple[int, ...]): The shift of serialized coordinates.
|
| 32 |
+
|
| 33 |
+
Returns:
|
| 34 |
+
(torch.Tensor): Forwards indices.
|
| 35 |
+
(torch.Tensor): Backwards indices.
|
| 36 |
+
(List[int]): Sequence lengths.
|
| 37 |
+
(List[int]): Sequence batch indices.
|
| 38 |
+
"""
|
| 39 |
+
DIM = tensor.coords.shape[1] - 1
|
| 40 |
+
shift_window = (shift_window,) * DIM if isinstance(shift_window, int) else shift_window
|
| 41 |
+
window_size = (window_size,) * DIM if isinstance(window_size, int) else window_size
|
| 42 |
+
shifted_coords = tensor.coords.clone().detach()
|
| 43 |
+
shifted_coords[:, 1:] += torch.tensor(shift_window, device=tensor.device, dtype=torch.int32).unsqueeze(0)
|
| 44 |
+
|
| 45 |
+
MAX_COORDS = shifted_coords[:, 1:].max(dim=0).values.tolist()
|
| 46 |
+
NUM_WINDOWS = [math.ceil((mc + 1) / ws) for mc, ws in zip(MAX_COORDS, window_size)]
|
| 47 |
+
OFFSET = torch.cumprod(torch.tensor([1] + NUM_WINDOWS[::-1]), dim=0).tolist()[::-1]
|
| 48 |
+
|
| 49 |
+
shifted_coords[:, 1:] //= torch.tensor(window_size, device=tensor.device, dtype=torch.int32).unsqueeze(0)
|
| 50 |
+
shifted_indices = (shifted_coords * torch.tensor(OFFSET, device=tensor.device, dtype=torch.int32).unsqueeze(0)).sum(dim=1)
|
| 51 |
+
fwd_indices = torch.argsort(shifted_indices)
|
| 52 |
+
bwd_indices = torch.empty_like(fwd_indices)
|
| 53 |
+
bwd_indices[fwd_indices] = torch.arange(fwd_indices.shape[0], device=tensor.device)
|
| 54 |
+
seq_lens = torch.bincount(shifted_indices)
|
| 55 |
+
seq_batch_indices = torch.arange(seq_lens.shape[0], device=tensor.device, dtype=torch.int32) // OFFSET[0]
|
| 56 |
+
mask = seq_lens != 0
|
| 57 |
+
seq_lens = seq_lens[mask].tolist()
|
| 58 |
+
seq_batch_indices = seq_batch_indices[mask].tolist()
|
| 59 |
+
|
| 60 |
+
return fwd_indices, bwd_indices, seq_lens, seq_batch_indices
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def sparse_windowed_scaled_dot_product_self_attention(
|
| 64 |
+
qkv: SparseTensor,
|
| 65 |
+
window_size: int,
|
| 66 |
+
shift_window: Tuple[int, int, int] = (0, 0, 0)
|
| 67 |
+
) -> SparseTensor:
|
| 68 |
+
"""
|
| 69 |
+
Apply windowed scaled dot product self attention to a sparse tensor.
|
| 70 |
+
|
| 71 |
+
Args:
|
| 72 |
+
qkv (SparseTensor): [N, *, 3, H, C] sparse tensor containing Qs, Ks, and Vs.
|
| 73 |
+
window_size (int): The window size to use.
|
| 74 |
+
shift_window (Tuple[int, int, int]): The shift of serialized coordinates.
|
| 75 |
+
shift (int): The shift to use.
|
| 76 |
+
"""
|
| 77 |
+
assert len(qkv.shape) == 4 and qkv.shape[1] == 3, f"Invalid shape for qkv, got {qkv.shape}, expected [N, *, 3, H, C]"
|
| 78 |
+
|
| 79 |
+
serialization_spatial_cache_name = f'window_partition_{window_size}_{shift_window}'
|
| 80 |
+
serialization_spatial_cache = qkv.get_spatial_cache(serialization_spatial_cache_name)
|
| 81 |
+
if serialization_spatial_cache is None:
|
| 82 |
+
fwd_indices, bwd_indices, seq_lens, seq_batch_indices = calc_window_partition(qkv, window_size, shift_window)
|
| 83 |
+
qkv.register_spatial_cache(serialization_spatial_cache_name, (fwd_indices, bwd_indices, seq_lens, seq_batch_indices))
|
| 84 |
+
else:
|
| 85 |
+
fwd_indices, bwd_indices, seq_lens, seq_batch_indices = serialization_spatial_cache
|
| 86 |
+
|
| 87 |
+
M = fwd_indices.shape[0]
|
| 88 |
+
T = qkv.feats.shape[0]
|
| 89 |
+
H = qkv.feats.shape[2]
|
| 90 |
+
C = qkv.feats.shape[3]
|
| 91 |
+
|
| 92 |
+
qkv_feats = qkv.feats[fwd_indices] # [M, 3, H, C]
|
| 93 |
+
|
| 94 |
+
if DEBUG:
|
| 95 |
+
start = 0
|
| 96 |
+
qkv_coords = qkv.coords[fwd_indices]
|
| 97 |
+
for i in range(len(seq_lens)):
|
| 98 |
+
seq_coords = qkv_coords[start:start+seq_lens[i]]
|
| 99 |
+
assert (seq_coords[:, 0] == seq_batch_indices[i]).all(), f"SparseWindowedScaledDotProductSelfAttention: batch index mismatch"
|
| 100 |
+
assert (seq_coords[:, 1:].max(dim=0).values - seq_coords[:, 1:].min(dim=0).values < window_size).all(), \
|
| 101 |
+
f"SparseWindowedScaledDotProductSelfAttention: window size exceeded"
|
| 102 |
+
start += seq_lens[i]
|
| 103 |
+
|
| 104 |
+
if all([seq_len == window_size for seq_len in seq_lens]):
|
| 105 |
+
B = len(seq_lens)
|
| 106 |
+
N = window_size
|
| 107 |
+
qkv_feats = qkv_feats.reshape(B, N, 3, H, C)
|
| 108 |
+
if ATTN == 'xformers':
|
| 109 |
+
q, k, v = qkv_feats.unbind(dim=2) # [B, N, H, C]
|
| 110 |
+
out = xops.memory_efficient_attention(q, k, v) # [B, N, H, C]
|
| 111 |
+
elif ATTN == 'flash_attn':
|
| 112 |
+
out = flash_attn.flash_attn_qkvpacked_func(qkv_feats) # [B, N, H, C]
|
| 113 |
+
else:
|
| 114 |
+
raise ValueError(f"Unknown attention module: {ATTN}")
|
| 115 |
+
out = out.reshape(B * N, H, C) # [M, H, C]
|
| 116 |
+
else:
|
| 117 |
+
if ATTN == 'xformers':
|
| 118 |
+
q, k, v = qkv_feats.unbind(dim=1) # [M, H, C]
|
| 119 |
+
q = q.unsqueeze(0) # [1, M, H, C]
|
| 120 |
+
k = k.unsqueeze(0) # [1, M, H, C]
|
| 121 |
+
v = v.unsqueeze(0) # [1, M, H, C]
|
| 122 |
+
mask = xops.fmha.BlockDiagonalMask.from_seqlens(seq_lens)
|
| 123 |
+
out = xops.memory_efficient_attention(q, k, v, mask)[0] # [M, H, C]
|
| 124 |
+
elif ATTN == 'flash_attn':
|
| 125 |
+
cu_seqlens = torch.cat([torch.tensor([0]), torch.cumsum(torch.tensor(seq_lens), dim=0)], dim=0) \
|
| 126 |
+
.to(qkv.device).int()
|
| 127 |
+
out = flash_attn.flash_attn_varlen_qkvpacked_func(qkv_feats, cu_seqlens, max(seq_lens)) # [M, H, C]
|
| 128 |
+
|
| 129 |
+
out = out[bwd_indices] # [T, H, C]
|
| 130 |
+
|
| 131 |
+
if DEBUG:
|
| 132 |
+
qkv_coords = qkv_coords[bwd_indices]
|
| 133 |
+
assert torch.equal(qkv_coords, qkv.coords), "SparseWindowedScaledDotProductSelfAttention: coordinate mismatch"
|
| 134 |
+
|
| 135 |
+
return qkv.replace(out)
|
TRELLIS/trellis/modules/sparse/basic.py
ADDED
|
@@ -0,0 +1,459 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import *
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from . import BACKEND, DEBUG
|
| 5 |
+
SparseTensorData = None # Lazy import
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = [
|
| 9 |
+
'SparseTensor',
|
| 10 |
+
'sparse_batch_broadcast',
|
| 11 |
+
'sparse_batch_op',
|
| 12 |
+
'sparse_cat',
|
| 13 |
+
'sparse_unbind',
|
| 14 |
+
]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class SparseTensor:
|
| 18 |
+
"""
|
| 19 |
+
Sparse tensor with support for both torchsparse and spconv backends.
|
| 20 |
+
|
| 21 |
+
Parameters:
|
| 22 |
+
- feats (torch.Tensor): Features of the sparse tensor.
|
| 23 |
+
- coords (torch.Tensor): Coordinates of the sparse tensor.
|
| 24 |
+
- shape (torch.Size): Shape of the sparse tensor.
|
| 25 |
+
- layout (List[slice]): Layout of the sparse tensor for each batch
|
| 26 |
+
- data (SparseTensorData): Sparse tensor data used for convolusion
|
| 27 |
+
|
| 28 |
+
NOTE:
|
| 29 |
+
- Data corresponding to a same batch should be contiguous.
|
| 30 |
+
- Coords should be in [0, 1023]
|
| 31 |
+
"""
|
| 32 |
+
@overload
|
| 33 |
+
def __init__(self, feats: torch.Tensor, coords: torch.Tensor, shape: Optional[torch.Size] = None, layout: Optional[List[slice]] = None, **kwargs): ...
|
| 34 |
+
|
| 35 |
+
@overload
|
| 36 |
+
def __init__(self, data, shape: Optional[torch.Size] = None, layout: Optional[List[slice]] = None, **kwargs): ...
|
| 37 |
+
|
| 38 |
+
def __init__(self, *args, **kwargs):
|
| 39 |
+
# Lazy import of sparse tensor backend
|
| 40 |
+
global SparseTensorData
|
| 41 |
+
if SparseTensorData is None:
|
| 42 |
+
import importlib
|
| 43 |
+
if BACKEND == 'torchsparse':
|
| 44 |
+
SparseTensorData = importlib.import_module('torchsparse').SparseTensor
|
| 45 |
+
elif BACKEND == 'spconv':
|
| 46 |
+
SparseTensorData = importlib.import_module('spconv.pytorch').SparseConvTensor
|
| 47 |
+
|
| 48 |
+
method_id = 0
|
| 49 |
+
if len(args) != 0:
|
| 50 |
+
method_id = 0 if isinstance(args[0], torch.Tensor) else 1
|
| 51 |
+
else:
|
| 52 |
+
method_id = 1 if 'data' in kwargs else 0
|
| 53 |
+
|
| 54 |
+
if method_id == 0:
|
| 55 |
+
feats, coords, shape, layout = args + (None,) * (4 - len(args))
|
| 56 |
+
if 'feats' in kwargs:
|
| 57 |
+
feats = kwargs['feats']
|
| 58 |
+
del kwargs['feats']
|
| 59 |
+
if 'coords' in kwargs:
|
| 60 |
+
coords = kwargs['coords']
|
| 61 |
+
del kwargs['coords']
|
| 62 |
+
if 'shape' in kwargs:
|
| 63 |
+
shape = kwargs['shape']
|
| 64 |
+
del kwargs['shape']
|
| 65 |
+
if 'layout' in kwargs:
|
| 66 |
+
layout = kwargs['layout']
|
| 67 |
+
del kwargs['layout']
|
| 68 |
+
|
| 69 |
+
if shape is None:
|
| 70 |
+
shape = self.__cal_shape(feats, coords)
|
| 71 |
+
if layout is None:
|
| 72 |
+
layout = self.__cal_layout(coords, shape[0])
|
| 73 |
+
if BACKEND == 'torchsparse':
|
| 74 |
+
self.data = SparseTensorData(feats, coords, **kwargs)
|
| 75 |
+
elif BACKEND == 'spconv':
|
| 76 |
+
spatial_shape = list(coords.max(0)[0] + 1)[1:]
|
| 77 |
+
self.data = SparseTensorData(feats.reshape(feats.shape[0], -1), coords, spatial_shape, shape[0], **kwargs)
|
| 78 |
+
self.data._features = feats
|
| 79 |
+
elif method_id == 1:
|
| 80 |
+
data, shape, layout = args + (None,) * (3 - len(args))
|
| 81 |
+
if 'data' in kwargs:
|
| 82 |
+
data = kwargs['data']
|
| 83 |
+
del kwargs['data']
|
| 84 |
+
if 'shape' in kwargs:
|
| 85 |
+
shape = kwargs['shape']
|
| 86 |
+
del kwargs['shape']
|
| 87 |
+
if 'layout' in kwargs:
|
| 88 |
+
layout = kwargs['layout']
|
| 89 |
+
del kwargs['layout']
|
| 90 |
+
|
| 91 |
+
self.data = data
|
| 92 |
+
if shape is None:
|
| 93 |
+
shape = self.__cal_shape(self.feats, self.coords)
|
| 94 |
+
if layout is None:
|
| 95 |
+
layout = self.__cal_layout(self.coords, shape[0])
|
| 96 |
+
|
| 97 |
+
self._shape = shape
|
| 98 |
+
self._layout = layout
|
| 99 |
+
self._scale = kwargs.get('scale', (1, 1, 1))
|
| 100 |
+
self._spatial_cache = kwargs.get('spatial_cache', {})
|
| 101 |
+
|
| 102 |
+
if DEBUG:
|
| 103 |
+
try:
|
| 104 |
+
assert self.feats.shape[0] == self.coords.shape[0], f"Invalid feats shape: {self.feats.shape}, coords shape: {self.coords.shape}"
|
| 105 |
+
assert self.shape == self.__cal_shape(self.feats, self.coords), f"Invalid shape: {self.shape}"
|
| 106 |
+
assert self.layout == self.__cal_layout(self.coords, self.shape[0]), f"Invalid layout: {self.layout}"
|
| 107 |
+
for i in range(self.shape[0]):
|
| 108 |
+
assert torch.all(self.coords[self.layout[i], 0] == i), f"The data of batch {i} is not contiguous"
|
| 109 |
+
except Exception as e:
|
| 110 |
+
print('Debugging information:')
|
| 111 |
+
print(f"- Shape: {self.shape}")
|
| 112 |
+
print(f"- Layout: {self.layout}")
|
| 113 |
+
print(f"- Scale: {self._scale}")
|
| 114 |
+
print(f"- Coords: {self.coords}")
|
| 115 |
+
raise e
|
| 116 |
+
|
| 117 |
+
def __cal_shape(self, feats, coords):
|
| 118 |
+
shape = []
|
| 119 |
+
shape.append(coords[:, 0].max().item() + 1)
|
| 120 |
+
shape.extend([*feats.shape[1:]])
|
| 121 |
+
return torch.Size(shape)
|
| 122 |
+
|
| 123 |
+
def __cal_layout(self, coords, batch_size):
|
| 124 |
+
seq_len = torch.bincount(coords[:, 0], minlength=batch_size)
|
| 125 |
+
offset = torch.cumsum(seq_len, dim=0)
|
| 126 |
+
layout = [slice((offset[i] - seq_len[i]).item(), offset[i].item()) for i in range(batch_size)]
|
| 127 |
+
return layout
|
| 128 |
+
|
| 129 |
+
@property
|
| 130 |
+
def shape(self) -> torch.Size:
|
| 131 |
+
return self._shape
|
| 132 |
+
|
| 133 |
+
def dim(self) -> int:
|
| 134 |
+
return len(self.shape)
|
| 135 |
+
|
| 136 |
+
@property
|
| 137 |
+
def layout(self) -> List[slice]:
|
| 138 |
+
return self._layout
|
| 139 |
+
|
| 140 |
+
@property
|
| 141 |
+
def feats(self) -> torch.Tensor:
|
| 142 |
+
if BACKEND == 'torchsparse':
|
| 143 |
+
return self.data.F
|
| 144 |
+
elif BACKEND == 'spconv':
|
| 145 |
+
return self.data.features
|
| 146 |
+
|
| 147 |
+
@feats.setter
|
| 148 |
+
def feats(self, value: torch.Tensor):
|
| 149 |
+
if BACKEND == 'torchsparse':
|
| 150 |
+
self.data.F = value
|
| 151 |
+
elif BACKEND == 'spconv':
|
| 152 |
+
self.data.features = value
|
| 153 |
+
|
| 154 |
+
@property
|
| 155 |
+
def coords(self) -> torch.Tensor:
|
| 156 |
+
if BACKEND == 'torchsparse':
|
| 157 |
+
return self.data.C
|
| 158 |
+
elif BACKEND == 'spconv':
|
| 159 |
+
return self.data.indices
|
| 160 |
+
|
| 161 |
+
@coords.setter
|
| 162 |
+
def coords(self, value: torch.Tensor):
|
| 163 |
+
if BACKEND == 'torchsparse':
|
| 164 |
+
self.data.C = value
|
| 165 |
+
elif BACKEND == 'spconv':
|
| 166 |
+
self.data.indices = value
|
| 167 |
+
|
| 168 |
+
@property
|
| 169 |
+
def dtype(self):
|
| 170 |
+
return self.feats.dtype
|
| 171 |
+
|
| 172 |
+
@property
|
| 173 |
+
def device(self):
|
| 174 |
+
return self.feats.device
|
| 175 |
+
|
| 176 |
+
@overload
|
| 177 |
+
def to(self, dtype: torch.dtype) -> 'SparseTensor': ...
|
| 178 |
+
|
| 179 |
+
@overload
|
| 180 |
+
def to(self, device: Optional[Union[str, torch.device]] = None, dtype: Optional[torch.dtype] = None) -> 'SparseTensor': ...
|
| 181 |
+
|
| 182 |
+
def to(self, *args, **kwargs) -> 'SparseTensor':
|
| 183 |
+
device = None
|
| 184 |
+
dtype = None
|
| 185 |
+
if len(args) == 2:
|
| 186 |
+
device, dtype = args
|
| 187 |
+
elif len(args) == 1:
|
| 188 |
+
if isinstance(args[0], torch.dtype):
|
| 189 |
+
dtype = args[0]
|
| 190 |
+
else:
|
| 191 |
+
device = args[0]
|
| 192 |
+
if 'dtype' in kwargs:
|
| 193 |
+
assert dtype is None, "to() received multiple values for argument 'dtype'"
|
| 194 |
+
dtype = kwargs['dtype']
|
| 195 |
+
if 'device' in kwargs:
|
| 196 |
+
assert device is None, "to() received multiple values for argument 'device'"
|
| 197 |
+
device = kwargs['device']
|
| 198 |
+
|
| 199 |
+
new_feats = self.feats.to(device=device, dtype=dtype)
|
| 200 |
+
new_coords = self.coords.to(device=device)
|
| 201 |
+
return self.replace(new_feats, new_coords)
|
| 202 |
+
|
| 203 |
+
def type(self, dtype):
|
| 204 |
+
new_feats = self.feats.type(dtype)
|
| 205 |
+
return self.replace(new_feats)
|
| 206 |
+
|
| 207 |
+
def cpu(self) -> 'SparseTensor':
|
| 208 |
+
new_feats = self.feats.cpu()
|
| 209 |
+
new_coords = self.coords.cpu()
|
| 210 |
+
return self.replace(new_feats, new_coords)
|
| 211 |
+
|
| 212 |
+
def cuda(self) -> 'SparseTensor':
|
| 213 |
+
new_feats = self.feats.cuda()
|
| 214 |
+
new_coords = self.coords.cuda()
|
| 215 |
+
return self.replace(new_feats, new_coords)
|
| 216 |
+
|
| 217 |
+
def half(self) -> 'SparseTensor':
|
| 218 |
+
new_feats = self.feats.half()
|
| 219 |
+
return self.replace(new_feats)
|
| 220 |
+
|
| 221 |
+
def float(self) -> 'SparseTensor':
|
| 222 |
+
new_feats = self.feats.float()
|
| 223 |
+
return self.replace(new_feats)
|
| 224 |
+
|
| 225 |
+
def detach(self) -> 'SparseTensor':
|
| 226 |
+
new_coords = self.coords.detach()
|
| 227 |
+
new_feats = self.feats.detach()
|
| 228 |
+
return self.replace(new_feats, new_coords)
|
| 229 |
+
|
| 230 |
+
def dense(self) -> torch.Tensor:
|
| 231 |
+
if BACKEND == 'torchsparse':
|
| 232 |
+
return self.data.dense()
|
| 233 |
+
elif BACKEND == 'spconv':
|
| 234 |
+
return self.data.dense()
|
| 235 |
+
|
| 236 |
+
def reshape(self, *shape) -> 'SparseTensor':
|
| 237 |
+
new_feats = self.feats.reshape(self.feats.shape[0], *shape)
|
| 238 |
+
return self.replace(new_feats)
|
| 239 |
+
|
| 240 |
+
def unbind(self, dim: int) -> List['SparseTensor']:
|
| 241 |
+
return sparse_unbind(self, dim)
|
| 242 |
+
|
| 243 |
+
def replace(self, feats: torch.Tensor, coords: Optional[torch.Tensor] = None) -> 'SparseTensor':
|
| 244 |
+
new_shape = [self.shape[0]]
|
| 245 |
+
new_shape.extend(feats.shape[1:])
|
| 246 |
+
if BACKEND == 'torchsparse':
|
| 247 |
+
new_data = SparseTensorData(
|
| 248 |
+
feats=feats,
|
| 249 |
+
coords=self.data.coords if coords is None else coords,
|
| 250 |
+
stride=self.data.stride,
|
| 251 |
+
spatial_range=self.data.spatial_range,
|
| 252 |
+
)
|
| 253 |
+
new_data._caches = self.data._caches
|
| 254 |
+
elif BACKEND == 'spconv':
|
| 255 |
+
new_data = SparseTensorData(
|
| 256 |
+
self.data.features.reshape(self.data.features.shape[0], -1),
|
| 257 |
+
self.data.indices,
|
| 258 |
+
self.data.spatial_shape,
|
| 259 |
+
self.data.batch_size,
|
| 260 |
+
self.data.grid,
|
| 261 |
+
self.data.voxel_num,
|
| 262 |
+
self.data.indice_dict
|
| 263 |
+
)
|
| 264 |
+
new_data._features = feats
|
| 265 |
+
new_data.benchmark = self.data.benchmark
|
| 266 |
+
new_data.benchmark_record = self.data.benchmark_record
|
| 267 |
+
new_data.thrust_allocator = self.data.thrust_allocator
|
| 268 |
+
new_data._timer = self.data._timer
|
| 269 |
+
new_data.force_algo = self.data.force_algo
|
| 270 |
+
new_data.int8_scale = self.data.int8_scale
|
| 271 |
+
if coords is not None:
|
| 272 |
+
new_data.indices = coords
|
| 273 |
+
new_tensor = SparseTensor(new_data, shape=torch.Size(new_shape), layout=self.layout, scale=self._scale, spatial_cache=self._spatial_cache)
|
| 274 |
+
return new_tensor
|
| 275 |
+
|
| 276 |
+
@staticmethod
|
| 277 |
+
def full(aabb, dim, value, dtype=torch.float32, device=None) -> 'SparseTensor':
|
| 278 |
+
N, C = dim
|
| 279 |
+
x = torch.arange(aabb[0], aabb[3] + 1)
|
| 280 |
+
y = torch.arange(aabb[1], aabb[4] + 1)
|
| 281 |
+
z = torch.arange(aabb[2], aabb[5] + 1)
|
| 282 |
+
coords = torch.stack(torch.meshgrid(x, y, z, indexing='ij'), dim=-1).reshape(-1, 3)
|
| 283 |
+
coords = torch.cat([
|
| 284 |
+
torch.arange(N).view(-1, 1).repeat(1, coords.shape[0]).view(-1, 1),
|
| 285 |
+
coords.repeat(N, 1),
|
| 286 |
+
], dim=1).to(dtype=torch.int32, device=device)
|
| 287 |
+
feats = torch.full((coords.shape[0], C), value, dtype=dtype, device=device)
|
| 288 |
+
return SparseTensor(feats=feats, coords=coords)
|
| 289 |
+
|
| 290 |
+
def __merge_sparse_cache(self, other: 'SparseTensor') -> dict:
|
| 291 |
+
new_cache = {}
|
| 292 |
+
for k in set(list(self._spatial_cache.keys()) + list(other._spatial_cache.keys())):
|
| 293 |
+
if k in self._spatial_cache:
|
| 294 |
+
new_cache[k] = self._spatial_cache[k]
|
| 295 |
+
if k in other._spatial_cache:
|
| 296 |
+
if k not in new_cache:
|
| 297 |
+
new_cache[k] = other._spatial_cache[k]
|
| 298 |
+
else:
|
| 299 |
+
new_cache[k].update(other._spatial_cache[k])
|
| 300 |
+
return new_cache
|
| 301 |
+
|
| 302 |
+
def __neg__(self) -> 'SparseTensor':
|
| 303 |
+
return self.replace(-self.feats)
|
| 304 |
+
|
| 305 |
+
def __elemwise__(self, other: Union[torch.Tensor, 'SparseTensor'], op: callable) -> 'SparseTensor':
|
| 306 |
+
if isinstance(other, torch.Tensor):
|
| 307 |
+
try:
|
| 308 |
+
other = torch.broadcast_to(other, self.shape)
|
| 309 |
+
other = sparse_batch_broadcast(self, other)
|
| 310 |
+
except:
|
| 311 |
+
pass
|
| 312 |
+
if isinstance(other, SparseTensor):
|
| 313 |
+
other = other.feats
|
| 314 |
+
new_feats = op(self.feats, other)
|
| 315 |
+
new_tensor = self.replace(new_feats)
|
| 316 |
+
if isinstance(other, SparseTensor):
|
| 317 |
+
new_tensor._spatial_cache = self.__merge_sparse_cache(other)
|
| 318 |
+
return new_tensor
|
| 319 |
+
|
| 320 |
+
def __add__(self, other: Union[torch.Tensor, 'SparseTensor', float]) -> 'SparseTensor':
|
| 321 |
+
return self.__elemwise__(other, torch.add)
|
| 322 |
+
|
| 323 |
+
def __radd__(self, other: Union[torch.Tensor, 'SparseTensor', float]) -> 'SparseTensor':
|
| 324 |
+
return self.__elemwise__(other, torch.add)
|
| 325 |
+
|
| 326 |
+
def __sub__(self, other: Union[torch.Tensor, 'SparseTensor', float]) -> 'SparseTensor':
|
| 327 |
+
return self.__elemwise__(other, torch.sub)
|
| 328 |
+
|
| 329 |
+
def __rsub__(self, other: Union[torch.Tensor, 'SparseTensor', float]) -> 'SparseTensor':
|
| 330 |
+
return self.__elemwise__(other, lambda x, y: torch.sub(y, x))
|
| 331 |
+
|
| 332 |
+
def __mul__(self, other: Union[torch.Tensor, 'SparseTensor', float]) -> 'SparseTensor':
|
| 333 |
+
return self.__elemwise__(other, torch.mul)
|
| 334 |
+
|
| 335 |
+
def __rmul__(self, other: Union[torch.Tensor, 'SparseTensor', float]) -> 'SparseTensor':
|
| 336 |
+
return self.__elemwise__(other, torch.mul)
|
| 337 |
+
|
| 338 |
+
def __truediv__(self, other: Union[torch.Tensor, 'SparseTensor', float]) -> 'SparseTensor':
|
| 339 |
+
return self.__elemwise__(other, torch.div)
|
| 340 |
+
|
| 341 |
+
def __rtruediv__(self, other: Union[torch.Tensor, 'SparseTensor', float]) -> 'SparseTensor':
|
| 342 |
+
return self.__elemwise__(other, lambda x, y: torch.div(y, x))
|
| 343 |
+
|
| 344 |
+
def __getitem__(self, idx):
|
| 345 |
+
if isinstance(idx, int):
|
| 346 |
+
idx = [idx]
|
| 347 |
+
elif isinstance(idx, slice):
|
| 348 |
+
idx = range(*idx.indices(self.shape[0]))
|
| 349 |
+
elif isinstance(idx, torch.Tensor):
|
| 350 |
+
if idx.dtype == torch.bool:
|
| 351 |
+
assert idx.shape == (self.shape[0],), f"Invalid index shape: {idx.shape}"
|
| 352 |
+
idx = idx.nonzero().squeeze(1)
|
| 353 |
+
elif idx.dtype in [torch.int32, torch.int64]:
|
| 354 |
+
assert len(idx.shape) == 1, f"Invalid index shape: {idx.shape}"
|
| 355 |
+
else:
|
| 356 |
+
raise ValueError(f"Unknown index type: {idx.dtype}")
|
| 357 |
+
else:
|
| 358 |
+
raise ValueError(f"Unknown index type: {type(idx)}")
|
| 359 |
+
|
| 360 |
+
coords = []
|
| 361 |
+
feats = []
|
| 362 |
+
for new_idx, old_idx in enumerate(idx):
|
| 363 |
+
coords.append(self.coords[self.layout[old_idx]].clone())
|
| 364 |
+
coords[-1][:, 0] = new_idx
|
| 365 |
+
feats.append(self.feats[self.layout[old_idx]])
|
| 366 |
+
coords = torch.cat(coords, dim=0).contiguous()
|
| 367 |
+
feats = torch.cat(feats, dim=0).contiguous()
|
| 368 |
+
return SparseTensor(feats=feats, coords=coords)
|
| 369 |
+
|
| 370 |
+
def register_spatial_cache(self, key, value) -> None:
|
| 371 |
+
"""
|
| 372 |
+
Register a spatial cache.
|
| 373 |
+
The spatial cache can be any thing you want to cache.
|
| 374 |
+
The registery and retrieval of the cache is based on current scale.
|
| 375 |
+
"""
|
| 376 |
+
scale_key = str(self._scale)
|
| 377 |
+
if scale_key not in self._spatial_cache:
|
| 378 |
+
self._spatial_cache[scale_key] = {}
|
| 379 |
+
self._spatial_cache[scale_key][key] = value
|
| 380 |
+
|
| 381 |
+
def get_spatial_cache(self, key=None):
|
| 382 |
+
"""
|
| 383 |
+
Get a spatial cache.
|
| 384 |
+
"""
|
| 385 |
+
scale_key = str(self._scale)
|
| 386 |
+
cur_scale_cache = self._spatial_cache.get(scale_key, {})
|
| 387 |
+
if key is None:
|
| 388 |
+
return cur_scale_cache
|
| 389 |
+
return cur_scale_cache.get(key, None)
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def sparse_batch_broadcast(input: SparseTensor, other: torch.Tensor) -> torch.Tensor:
|
| 393 |
+
"""
|
| 394 |
+
Broadcast a 1D tensor to a sparse tensor along the batch dimension then perform an operation.
|
| 395 |
+
|
| 396 |
+
Args:
|
| 397 |
+
input (torch.Tensor): 1D tensor to broadcast.
|
| 398 |
+
target (SparseTensor): Sparse tensor to broadcast to.
|
| 399 |
+
op (callable): Operation to perform after broadcasting. Defaults to torch.add.
|
| 400 |
+
"""
|
| 401 |
+
coords, feats = input.coords, input.feats
|
| 402 |
+
broadcasted = torch.zeros_like(feats)
|
| 403 |
+
for k in range(input.shape[0]):
|
| 404 |
+
broadcasted[input.layout[k]] = other[k]
|
| 405 |
+
return broadcasted
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
def sparse_batch_op(input: SparseTensor, other: torch.Tensor, op: callable = torch.add) -> SparseTensor:
|
| 409 |
+
"""
|
| 410 |
+
Broadcast a 1D tensor to a sparse tensor along the batch dimension then perform an operation.
|
| 411 |
+
|
| 412 |
+
Args:
|
| 413 |
+
input (torch.Tensor): 1D tensor to broadcast.
|
| 414 |
+
target (SparseTensor): Sparse tensor to broadcast to.
|
| 415 |
+
op (callable): Operation to perform after broadcasting. Defaults to torch.add.
|
| 416 |
+
"""
|
| 417 |
+
return input.replace(op(input.feats, sparse_batch_broadcast(input, other)))
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
def sparse_cat(inputs: List[SparseTensor], dim: int = 0) -> SparseTensor:
|
| 421 |
+
"""
|
| 422 |
+
Concatenate a list of sparse tensors.
|
| 423 |
+
|
| 424 |
+
Args:
|
| 425 |
+
inputs (List[SparseTensor]): List of sparse tensors to concatenate.
|
| 426 |
+
"""
|
| 427 |
+
if dim == 0:
|
| 428 |
+
start = 0
|
| 429 |
+
coords = []
|
| 430 |
+
for input in inputs:
|
| 431 |
+
coords.append(input.coords.clone())
|
| 432 |
+
coords[-1][:, 0] += start
|
| 433 |
+
start += input.shape[0]
|
| 434 |
+
coords = torch.cat(coords, dim=0)
|
| 435 |
+
feats = torch.cat([input.feats for input in inputs], dim=0)
|
| 436 |
+
output = SparseTensor(
|
| 437 |
+
coords=coords,
|
| 438 |
+
feats=feats,
|
| 439 |
+
)
|
| 440 |
+
else:
|
| 441 |
+
feats = torch.cat([input.feats for input in inputs], dim=dim)
|
| 442 |
+
output = inputs[0].replace(feats)
|
| 443 |
+
|
| 444 |
+
return output
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def sparse_unbind(input: SparseTensor, dim: int) -> List[SparseTensor]:
|
| 448 |
+
"""
|
| 449 |
+
Unbind a sparse tensor along a dimension.
|
| 450 |
+
|
| 451 |
+
Args:
|
| 452 |
+
input (SparseTensor): Sparse tensor to unbind.
|
| 453 |
+
dim (int): Dimension to unbind.
|
| 454 |
+
"""
|
| 455 |
+
if dim == 0:
|
| 456 |
+
return [input[i] for i in range(input.shape[0])]
|
| 457 |
+
else:
|
| 458 |
+
feats = input.feats.unbind(dim)
|
| 459 |
+
return [input.replace(f) for f in feats]
|
TRELLIS/trellis/modules/sparse/conv/__init__.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .. import BACKEND
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
SPCONV_ALGO = 'auto' # 'auto', 'implicit_gemm', 'native'
|
| 5 |
+
|
| 6 |
+
def __from_env():
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
global SPCONV_ALGO
|
| 10 |
+
env_spconv_algo = os.environ.get('SPCONV_ALGO')
|
| 11 |
+
if env_spconv_algo is not None and env_spconv_algo in ['auto', 'implicit_gemm', 'native']:
|
| 12 |
+
SPCONV_ALGO = env_spconv_algo
|
| 13 |
+
print(f"[SPARSE][CONV] spconv algo: {SPCONV_ALGO}")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
__from_env()
|
| 17 |
+
|
| 18 |
+
if BACKEND == 'torchsparse':
|
| 19 |
+
from .conv_torchsparse import *
|
| 20 |
+
elif BACKEND == 'spconv':
|
| 21 |
+
from .conv_spconv import *
|