first commit

This commit is contained in:
Yiwen Chen 2024-06-17 00:07:35 +08:00
commit df361407d9
64 changed files with 64763 additions and 0 deletions

8
.idea/.gitignore vendored Normal file
View File

@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

8
.idea/MeshAnything.iml Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@ -0,0 +1,97 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredPackages">
<value>
<list size="83">
<item index="0" class="java.lang.String" itemvalue="jax" />
<item index="1" class="java.lang.String" itemvalue="jaxlib" />
<item index="2" class="java.lang.String" itemvalue="numpy" />
<item index="3" class="java.lang.String" itemvalue="absl-py" />
<item index="4" class="java.lang.String" itemvalue="scipy" />
<item index="5" class="java.lang.String" itemvalue="opencv-python" />
<item index="6" class="java.lang.String" itemvalue="opt-einsum" />
<item index="7" class="java.lang.String" itemvalue="immutabledict" />
<item index="8" class="java.lang.String" itemvalue="tqdm" />
<item index="9" class="java.lang.String" itemvalue="flax" />
<item index="10" class="java.lang.String" itemvalue="tensorflow" />
<item index="11" class="java.lang.String" itemvalue="imageio" />
<item index="12" class="java.lang.String" itemvalue="matplotlib" />
<item index="13" class="java.lang.String" itemvalue="oauthlib" />
<item index="14" class="java.lang.String" itemvalue="optax" />
<item index="15" class="java.lang.String" itemvalue="Markdown" />
<item index="16" class="java.lang.String" itemvalue="Pillow" />
<item index="17" class="java.lang.String" itemvalue="nerfies" />
<item index="18" class="java.lang.String" itemvalue="pycolmap" />
<item index="19" class="java.lang.String" itemvalue="mediapipe" />
<item index="20" class="java.lang.String" itemvalue="xatlas" />
<item index="21" class="java.lang.String" itemvalue="torch-ema" />
<item index="22" class="java.lang.String" itemvalue="transformers" />
<item index="23" class="java.lang.String" itemvalue="diffusers" />
<item index="24" class="java.lang.String" itemvalue="scikit-learn" />
<item index="25" class="java.lang.String" itemvalue="PyMCubes" />
<item index="26" class="java.lang.String" itemvalue="imageio-ffmpeg" />
<item index="27" class="java.lang.String" itemvalue="rich" />
<item index="28" class="java.lang.String" itemvalue="torch" />
<item index="29" class="java.lang.String" itemvalue="trimesh" />
<item index="30" class="java.lang.String" itemvalue="pandas" />
<item index="31" class="java.lang.String" itemvalue="tensorboard" />
<item index="32" class="java.lang.String" itemvalue="pymeshlab" />
<item index="33" class="java.lang.String" itemvalue="ninja" />
<item index="34" class="java.lang.String" itemvalue="tensorboardX" />
<item index="35" class="java.lang.String" itemvalue="dearpygui" />
<item index="36" class="java.lang.String" itemvalue="accelerate" />
<item index="37" class="java.lang.String" itemvalue="huggingface_hub" />
<item index="38" class="java.lang.String" itemvalue="controlnet_aux" />
<item index="39" class="java.lang.String" itemvalue="envlight" />
<item index="40" class="java.lang.String" itemvalue="ftfy" />
<item index="41" class="java.lang.String" itemvalue="ipywidgets" />
<item index="42" class="java.lang.String" itemvalue="lightning" />
<item index="43" class="java.lang.String" itemvalue="nvdiffrast" />
<item index="44" class="java.lang.String" itemvalue="gradio" />
<item index="45" class="java.lang.String" itemvalue="xformers" />
<item index="46" class="java.lang.String" itemvalue="libigl" />
<item index="47" class="java.lang.String" itemvalue="nerfacc" />
<item index="48" class="java.lang.String" itemvalue="typeguard" />
<item index="49" class="java.lang.String" itemvalue="omegaconf" />
<item index="50" class="java.lang.String" itemvalue="pysdf" />
<item index="51" class="java.lang.String" itemvalue="bitsandbytes" />
<item index="52" class="java.lang.String" itemvalue="CLIP" />
<item index="53" class="java.lang.String" itemvalue="kornia" />
<item index="54" class="java.lang.String" itemvalue="taming-transformers-rom1504" />
<item index="55" class="java.lang.String" itemvalue="sentencepiece" />
<item index="56" class="java.lang.String" itemvalue="safetensors" />
<item index="57" class="java.lang.String" itemvalue="wandb" />
<item index="58" class="java.lang.String" itemvalue="jaxtyping" />
<item index="59" class="java.lang.String" itemvalue="einops" />
<item index="60" class="java.lang.String" itemvalue="lang-segment-anything" />
<item index="61" class="java.lang.String" itemvalue="kiuikit" />
<item index="62" class="java.lang.String" itemvalue="scikit-image" />
<item index="63" class="java.lang.String" itemvalue="transforms3d" />
<item index="64" class="java.lang.String" itemvalue="torchmetrics" />
<item index="65" class="java.lang.String" itemvalue="matplotlib-inline" />
<item index="66" class="java.lang.String" itemvalue="tabulate" />
<item index="67" class="java.lang.String" itemvalue="plyfile" />
<item index="68" class="java.lang.String" itemvalue="ballpark" />
<item index="69" class="java.lang.String" itemvalue="flash-attn" />
<item index="70" class="java.lang.String" itemvalue="plotly" />
<item index="71" class="java.lang.String" itemvalue="easydict" />
<item index="72" class="java.lang.String" itemvalue="prettytable" />
<item index="73" class="java.lang.String" itemvalue="pytorch-lightning" />
<item index="74" class="java.lang.String" itemvalue="einops-exts" />
<item index="75" class="java.lang.String" itemvalue="hydra-core" />
<item index="76" class="java.lang.String" itemvalue="lightning-utilities" />
<item index="77" class="java.lang.String" itemvalue="moviepy" />
<item index="78" class="java.lang.String" itemvalue="vispy" />
<item index="79" class="java.lang.String" itemvalue="vector-quantize-pytorch" />
<item index="80" class="java.lang.String" itemvalue="torch_geometric" />
<item index="81" class="java.lang.String" itemvalue="randomname" />
<item index="82" class="java.lang.String" itemvalue="pyrender" />
</list>
</value>
</option>
</inspection_tool>
</profile>
</component>

View File

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

9
.idea/misc.xml Normal file
View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.9" project-jdk-type="Python SDK" />
<component name="SshConsoleOptionsProvider">
<option name="myEncoding" value="UTF-8" />
<option name="myConnectionType" value="NONE" />
<option name="myConnectionId" value="" />
</component>
</project>

8
.idea/modules.xml Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/MeshAnything.iml" filepath="$PROJECT_DIR$/.idea/MeshAnything.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

35
LICENSE.txt Normal file
View File

@ -0,0 +1,35 @@
S-Lab License 1.0
Copyright 2023 S-Lab
Redistribution and use for non-commercial purpose in source and
binary forms, with or without modification, are permitted provided
that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
In the event that redistribution and/or use for commercial purpose in
source or binary forms, with or without modification is required,
please contact the contributor(s) of the work.

674
MeshAnything/miche/LICENSE Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@ -0,0 +1,73 @@
# -*- coding: utf-8 -*-
import argparse
from omegaconf import OmegaConf
import numpy as np
import torch
from .michelangelo.utils.misc import instantiate_from_config
def load_surface(fp):
with np.load(fp) as input_pc:
surface = input_pc['points']
normal = input_pc['normals']
rng = np.random.default_rng()
ind = rng.choice(surface.shape[0], 4096, replace=False)
surface = torch.FloatTensor(surface[ind])
normal = torch.FloatTensor(normal[ind])
surface = torch.cat([surface, normal], dim=-1).unsqueeze(0).cuda()
return surface
def reconstruction(args, model, bounds=(-1.25, -1.25, -1.25, 1.25, 1.25, 1.25), octree_depth=7, num_chunks=10000):
surface = load_surface(args.pointcloud_path)
# old_surface = surface.clone()
# surface[0,:,0]*=-1
# surface[0,:,1]*=-1
surface[0,:,2]*=-1
# encoding
shape_embed, shape_latents = model.model.encode_shape_embed(surface, return_latents=True)
shape_zq, posterior = model.model.shape_model.encode_kl_embed(shape_latents)
# decoding
latents = model.model.shape_model.decode(shape_zq)
# geometric_func = partial(model.model.shape_model.query_geometry, latents=latents)
return 0
def load_model(ckpt_path="MeshAnything/miche/shapevae-256.ckpt"):
model_config = OmegaConf.load("MeshAnything/miche/shapevae-256.yaml")
# print(model_config)
if hasattr(model_config, "model"):
model_config = model_config.model
model = instantiate_from_config(model_config, ckpt_path=ckpt_path)
model = model.cuda()
model = model.eval()
return model
if __name__ == "__main__":
'''
1. Reconstruct point cloud
2. Image-conditioned generation
3. Text-conditioned generation
'''
parser = argparse.ArgumentParser()
parser.add_argument("--config_path", type=str, required=True)
parser.add_argument("--ckpt_path", type=str, required=True)
parser.add_argument("--pointcloud_path", type=str, default='./example_data/surface.npz', help='Path to the input point cloud')
parser.add_argument("--image_path", type=str, help='Path to the input image')
parser.add_argument("--text", type=str, help='Input text within a format: A 3D model of motorcar; Porsche 911.')
parser.add_argument("--output_dir", type=str, default='./output')
parser.add_argument("-s", "--seed", type=int, default=0)
args = parser.parse_args()
print(f'-----------------------------------------------------------------------------')
print(f'>>> Output directory: {args.output_dir}')
print(f'-----------------------------------------------------------------------------')
reconstruction(args, load_model(args))

View File

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

View File

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

View File

@ -0,0 +1,69 @@
{
"shape": [
"a point cloud model of {}.",
"There is a {} in the scene.",
"There is the {} in the scene.",
"a photo of a {} in the scene.",
"a photo of the {} in the scene.",
"a photo of one {} in the scene.",
"itap of a {}.",
"itap of my {}.",
"itap of the {}.",
"a photo of a {}.",
"a photo of my {}.",
"a photo of the {}.",
"a photo of one {}.",
"a photo of many {}.",
"a good photo of a {}.",
"a good photo of the {}.",
"a bad photo of a {}.",
"a bad photo of the {}.",
"a photo of a nice {}.",
"a photo of the nice {}.",
"a photo of a cool {}.",
"a photo of the cool {}.",
"a photo of a weird {}.",
"a photo of the weird {}.",
"a photo of a small {}.",
"a photo of the small {}.",
"a photo of a large {}.",
"a photo of the large {}.",
"a photo of a clean {}.",
"a photo of the clean {}.",
"a photo of a dirty {}.",
"a photo of the dirty {}.",
"a bright photo of a {}.",
"a bright photo of the {}.",
"a dark photo of a {}.",
"a dark photo of the {}.",
"a photo of a hard to see {}.",
"a photo of the hard to see {}.",
"a low resolution photo of a {}.",
"a low resolution photo of the {}.",
"a cropped photo of a {}.",
"a cropped photo of the {}.",
"a close-up photo of a {}.",
"a close-up photo of the {}.",
"a jpeg corrupted photo of a {}.",
"a jpeg corrupted photo of the {}.",
"a blurry photo of a {}.",
"a blurry photo of the {}.",
"a pixelated photo of a {}.",
"a pixelated photo of the {}.",
"a black and white photo of the {}.",
"a black and white photo of a {}",
"a plastic {}.",
"the plastic {}.",
"a toy {}.",
"the toy {}.",
"a plushie {}.",
"the plushie {}.",
"a cartoon {}.",
"the cartoon {}.",
"an embroidered {}.",
"the embroidered {}.",
"a painting of the {}.",
"a painting of a {}."
]
}

View File

@ -0,0 +1,407 @@
# -*- coding: utf-8 -*-
import os
import time
import numpy as np
import warnings
import random
from omegaconf.listconfig import ListConfig
from webdataset import pipelinefilter
import torch
import torchvision.transforms.functional as TVF
from torchvision.transforms import InterpolationMode
from torchvision.transforms.transforms import _interpolation_modes_from_int
from typing import Sequence
from MeshAnything.miche.michelangelo.utils import instantiate_from_config
def _uid_buffer_pick(buf_dict, rng):
uid_keys = list(buf_dict.keys())
selected_uid = rng.choice(uid_keys)
buf = buf_dict[selected_uid]
k = rng.randint(0, len(buf) - 1)
sample = buf[k]
buf[k] = buf[-1]
buf.pop()
if len(buf) == 0:
del buf_dict[selected_uid]
return sample
def _add_to_buf_dict(buf_dict, sample):
key = sample["__key__"]
uid, uid_sample_id = key.split("_")
if uid not in buf_dict:
buf_dict[uid] = []
buf_dict[uid].append(sample)
return buf_dict
def _uid_shuffle(data, bufsize=1000, initial=100, rng=None, handler=None):
"""Shuffle the data in the stream.
This uses a buffer of size `bufsize`. Shuffling at
startup is less random; this is traded off against
yielding samples quickly.
data: iterator
bufsize: buffer size for shuffling
returns: iterator
rng: either random module or random.Random instance
"""
if rng is None:
rng = random.Random(int((os.getpid() + time.time()) * 1e9))
initial = min(initial, bufsize)
buf_dict = dict()
current_samples = 0
for sample in data:
_add_to_buf_dict(buf_dict, sample)
current_samples += 1
if current_samples < bufsize:
try:
_add_to_buf_dict(buf_dict, next(data)) # skipcq: PYL-R1708
current_samples += 1
except StopIteration:
pass
if current_samples >= initial:
current_samples -= 1
yield _uid_buffer_pick(buf_dict, rng)
while current_samples > 0:
current_samples -= 1
yield _uid_buffer_pick(buf_dict, rng)
uid_shuffle = pipelinefilter(_uid_shuffle)
class RandomSample(object):
def __init__(self,
num_volume_samples: int = 1024,
num_near_samples: int = 1024):
super().__init__()
self.num_volume_samples = num_volume_samples
self.num_near_samples = num_near_samples
def __call__(self, sample):
rng = np.random.default_rng()
# 1. sample surface input
total_surface = sample["surface"]
ind = rng.choice(total_surface.shape[0], replace=False)
surface = total_surface[ind]
# 2. sample volume/near geometric points
vol_points = sample["vol_points"]
vol_label = sample["vol_label"]
near_points = sample["near_points"]
near_label = sample["near_label"]
ind = rng.choice(vol_points.shape[0], self.num_volume_samples, replace=False)
vol_points = vol_points[ind]
vol_label = vol_label[ind]
vol_points_labels = np.concatenate([vol_points, vol_label[:, np.newaxis]], axis=1)
ind = rng.choice(near_points.shape[0], self.num_near_samples, replace=False)
near_points = near_points[ind]
near_label = near_label[ind]
near_points_labels = np.concatenate([near_points, near_label[:, np.newaxis]], axis=1)
# concat sampled volume and near points
geo_points = np.concatenate([vol_points_labels, near_points_labels], axis=0)
sample = {
"surface": surface,
"geo_points": geo_points
}
return sample
class SplitRandomSample(object):
def __init__(self,
use_surface_sample: bool = False,
num_surface_samples: int = 4096,
num_volume_samples: int = 1024,
num_near_samples: int = 1024):
super().__init__()
self.use_surface_sample = use_surface_sample
self.num_surface_samples = num_surface_samples
self.num_volume_samples = num_volume_samples
self.num_near_samples = num_near_samples
def __call__(self, sample):
rng = np.random.default_rng()
# 1. sample surface input
surface = sample["surface"]
if self.use_surface_sample:
replace = surface.shape[0] < self.num_surface_samples
ind = rng.choice(surface.shape[0], self.num_surface_samples, replace=replace)
surface = surface[ind]
# 2. sample volume/near geometric points
vol_points = sample["vol_points"]
vol_label = sample["vol_label"]
near_points = sample["near_points"]
near_label = sample["near_label"]
ind = rng.choice(vol_points.shape[0], self.num_volume_samples, replace=False)
vol_points = vol_points[ind]
vol_label = vol_label[ind]
vol_points_labels = np.concatenate([vol_points, vol_label[:, np.newaxis]], axis=1)
ind = rng.choice(near_points.shape[0], self.num_near_samples, replace=False)
near_points = near_points[ind]
near_label = near_label[ind]
near_points_labels = np.concatenate([near_points, near_label[:, np.newaxis]], axis=1)
# concat sampled volume and near points
geo_points = np.concatenate([vol_points_labels, near_points_labels], axis=0)
sample = {
"surface": surface,
"geo_points": geo_points
}
return sample
class FeatureSelection(object):
VALID_SURFACE_FEATURE_DIMS = {
"none": [0, 1, 2], # xyz
"watertight_normal": [0, 1, 2, 3, 4, 5], # xyz, normal
"normal": [0, 1, 2, 6, 7, 8]
}
def __init__(self, surface_feature_type: str):
self.surface_feature_type = surface_feature_type
self.surface_dims = self.VALID_SURFACE_FEATURE_DIMS[surface_feature_type]
def __call__(self, sample):
sample["surface"] = sample["surface"][:, self.surface_dims]
return sample
class AxisScaleTransform(object):
def __init__(self, interval=(0.75, 1.25), jitter=True, jitter_scale=0.005):
assert isinstance(interval, (tuple, list, ListConfig))
self.interval = interval
self.min_val = interval[0]
self.max_val = interval[1]
self.inter_size = interval[1] - interval[0]
self.jitter = jitter
self.jitter_scale = jitter_scale
def __call__(self, sample):
surface = sample["surface"][..., 0:3]
geo_points = sample["geo_points"][..., 0:3]
scaling = torch.rand(1, 3) * self.inter_size + self.min_val
# print(scaling)
surface = surface * scaling
geo_points = geo_points * scaling
scale = (1 / torch.abs(surface).max().item()) * 0.999999
surface *= scale
geo_points *= scale
if self.jitter:
surface += self.jitter_scale * torch.randn_like(surface)
surface.clamp_(min=-1.015, max=1.015)
sample["surface"][..., 0:3] = surface
sample["geo_points"][..., 0:3] = geo_points
return sample
class ToTensor(object):
def __init__(self, tensor_keys=("surface", "geo_points", "tex_points")):
self.tensor_keys = tensor_keys
def __call__(self, sample):
for key in self.tensor_keys:
if key not in sample:
continue
sample[key] = torch.tensor(sample[key], dtype=torch.float32)
return sample
class AxisScale(object):
def __init__(self, interval=(0.75, 1.25), jitter=True, jitter_scale=0.005):
assert isinstance(interval, (tuple, list, ListConfig))
self.interval = interval
self.jitter = jitter
self.jitter_scale = jitter_scale
def __call__(self, surface, *args):
scaling = torch.rand(1, 3) * 0.5 + 0.75
# print(scaling)
surface = surface * scaling
scale = (1 / torch.abs(surface).max().item()) * 0.999999
surface *= scale
args_outputs = []
for _arg in args:
_arg = _arg * scaling * scale
args_outputs.append(_arg)
if self.jitter:
surface += self.jitter_scale * torch.randn_like(surface)
surface.clamp_(min=-1, max=1)
if len(args) == 0:
return surface
else:
return surface, *args_outputs
class RandomResize(torch.nn.Module):
"""Apply randomly Resize with a given probability."""
def __init__(
self,
size,
resize_radio=(0.5, 1),
allow_resize_interpolations=(InterpolationMode.BICUBIC, InterpolationMode.BILINEAR, InterpolationMode.BILINEAR),
interpolation=InterpolationMode.BICUBIC,
max_size=None,
antialias=None,
):
super().__init__()
if not isinstance(size, (int, Sequence)):
raise TypeError(f"Size should be int or sequence. Got {type(size)}")
if isinstance(size, Sequence) and len(size) not in (1, 2):
raise ValueError("If size is a sequence, it should have 1 or 2 values")
self.size = size
self.max_size = max_size
# Backward compatibility with integer value
if isinstance(interpolation, int):
warnings.warn(
"Argument 'interpolation' of type int is deprecated since 0.13 and will be removed in 0.15. "
"Please use InterpolationMode enum."
)
interpolation = _interpolation_modes_from_int(interpolation)
self.interpolation = interpolation
self.antialias = antialias
self.resize_radio = resize_radio
self.allow_resize_interpolations = allow_resize_interpolations
def random_resize_params(self):
radio = torch.rand(1) * (self.resize_radio[1] - self.resize_radio[0]) + self.resize_radio[0]
if isinstance(self.size, int):
size = int(self.size * radio)
elif isinstance(self.size, Sequence):
size = list(self.size)
size = (int(size[0] * radio), int(size[1] * radio))
else:
raise RuntimeError()
interpolation = self.allow_resize_interpolations[
torch.randint(low=0, high=len(self.allow_resize_interpolations), size=(1,))
]
return size, interpolation
def forward(self, img):
size, interpolation = self.random_resize_params()
img = TVF.resize(img, size, interpolation, self.max_size, self.antialias)
img = TVF.resize(img, self.size, self.interpolation, self.max_size, self.antialias)
return img
def __repr__(self) -> str:
detail = f"(size={self.size}, interpolation={self.interpolation.value},"
detail += f"max_size={self.max_size}, antialias={self.antialias}), resize_radio={self.resize_radio}"
return f"{self.__class__.__name__}{detail}"
class Compose(object):
"""Composes several transforms together. This transform does not support torchscript.
Please, see the note below.
Args:
transforms (list of ``Transform`` objects): list of transforms to compose.
Example:
>>> transforms.Compose([
>>> transforms.CenterCrop(10),
>>> transforms.ToTensor(),
>>> ])
.. note::
In order to script the transformations, please use ``torch.nn.Sequential`` as below.
>>> transforms = torch.nn.Sequential(
>>> transforms.CenterCrop(10),
>>> transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
>>> )
>>> scripted_transforms = torch.jit.script(transforms)
Make sure to use only scriptable transformations, i.e. that work with ``torch.Tensor``, does not require
`lambda` functions or ``PIL.Image``.
"""
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, *args):
for t in self.transforms:
args = t(*args)
return args
def __repr__(self):
format_string = self.__class__.__name__ + '('
for t in self.transforms:
format_string += '\n'
format_string += ' {0}'.format(t)
format_string += '\n)'
return format_string
def identity(*args, **kwargs):
if len(args) == 1:
return args[0]
else:
return args
def build_transforms(cfg):
if cfg is None:
return identity
transforms = []
for transform_name, cfg_instance in cfg.items():
transform_instance = instantiate_from_config(cfg_instance)
transforms.append(transform_instance)
print(f"Build transform: {transform_instance}")
transforms = Compose(transforms)
return transforms

View File

@ -0,0 +1,59 @@
# -*- coding: utf-8 -*-
import torch
import numpy as np
def worker_init_fn(_):
worker_info = torch.utils.data.get_worker_info()
worker_id = worker_info.id
# dataset = worker_info.dataset
# split_size = dataset.num_records // worker_info.num_workers
# # reset num_records to the true number to retain reliable length information
# dataset.sample_ids = dataset.valid_ids[worker_id * split_size:(worker_id + 1) * split_size]
# current_id = np.random.choice(len(np.random.get_state()[1]), 1)
# return np.random.seed(np.random.get_state()[1][current_id] + worker_id)
return np.random.seed(np.random.get_state()[1][0] + worker_id)
def collation_fn(samples, combine_tensors=True, combine_scalars=True):
"""
Args:
samples (list[dict]):
combine_tensors:
combine_scalars:
Returns:
"""
result = {}
keys = samples[0].keys()
for key in keys:
result[key] = []
for sample in samples:
for key in keys:
val = sample[key]
result[key].append(val)
for key in keys:
val_list = result[key]
if isinstance(val_list[0], (int, float)):
if combine_scalars:
result[key] = np.array(result[key])
elif isinstance(val_list[0], torch.Tensor):
if combine_tensors:
result[key] = torch.stack(val_list)
elif isinstance(val_list[0], np.ndarray):
if combine_tensors:
result[key] = np.stack(val_list)
return result

View File

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

View File

@ -0,0 +1,9 @@
# -*- coding: utf-8 -*-
from .volume import generate_dense_grid_points
from .mesh import (
MeshOutput,
save_obj,
savemeshtes2
)

View File

@ -0,0 +1,114 @@
# -*- coding: utf-8 -*-
import os
import cv2
import numpy as np
import PIL.Image
from typing import Optional
import trimesh
def save_obj(pointnp_px3, facenp_fx3, fname):
fid = open(fname, "w")
write_str = ""
for pidx, p in enumerate(pointnp_px3):
pp = p
write_str += "v %f %f %f\n" % (pp[0], pp[1], pp[2])
for i, f in enumerate(facenp_fx3):
f1 = f + 1
write_str += "f %d %d %d\n" % (f1[0], f1[1], f1[2])
fid.write(write_str)
fid.close()
return
def savemeshtes2(pointnp_px3, tcoords_px2, facenp_fx3, facetex_fx3, tex_map, fname):
fol, na = os.path.split(fname)
na, _ = os.path.splitext(na)
matname = "%s/%s.mtl" % (fol, na)
fid = open(matname, "w")
fid.write("newmtl material_0\n")
fid.write("Kd 1 1 1\n")
fid.write("Ka 0 0 0\n")
fid.write("Ks 0.4 0.4 0.4\n")
fid.write("Ns 10\n")
fid.write("illum 2\n")
fid.write("map_Kd %s.png\n" % na)
fid.close()
####
fid = open(fname, "w")
fid.write("mtllib %s.mtl\n" % na)
for pidx, p in enumerate(pointnp_px3):
pp = p
fid.write("v %f %f %f\n" % (pp[0], pp[1], pp[2]))
for pidx, p in enumerate(tcoords_px2):
pp = p
fid.write("vt %f %f\n" % (pp[0], pp[1]))
fid.write("usemtl material_0\n")
for i, f in enumerate(facenp_fx3):
f1 = f + 1
f2 = facetex_fx3[i] + 1
fid.write("f %d/%d %d/%d %d/%d\n" % (f1[0], f2[0], f1[1], f2[1], f1[2], f2[2]))
fid.close()
PIL.Image.fromarray(np.ascontiguousarray(tex_map), "RGB").save(
os.path.join(fol, "%s.png" % na))
return
class MeshOutput(object):
def __init__(self,
mesh_v: np.ndarray,
mesh_f: np.ndarray,
vertex_colors: Optional[np.ndarray] = None,
uvs: Optional[np.ndarray] = None,
mesh_tex_idx: Optional[np.ndarray] = None,
tex_map: Optional[np.ndarray] = None):
self.mesh_v = mesh_v
self.mesh_f = mesh_f
self.vertex_colors = vertex_colors
self.uvs = uvs
self.mesh_tex_idx = mesh_tex_idx
self.tex_map = tex_map
def contain_uv_texture(self):
return (self.uvs is not None) and (self.mesh_tex_idx is not None) and (self.tex_map is not None)
def contain_vertex_colors(self):
return self.vertex_colors is not None
def export(self, fname):
if self.contain_uv_texture():
savemeshtes2(
self.mesh_v,
self.uvs,
self.mesh_f,
self.mesh_tex_idx,
self.tex_map,
fname
)
elif self.contain_vertex_colors():
mesh_obj = trimesh.Trimesh(vertices=self.mesh_v, faces=self.mesh_f, vertex_colors=self.vertex_colors)
mesh_obj.export(fname)
else:
save_obj(
self.mesh_v,
self.mesh_f,
fname
)

View File

@ -0,0 +1,21 @@
# -*- coding: utf-8 -*-
import numpy as np
def generate_dense_grid_points(bbox_min: np.ndarray,
bbox_max: np.ndarray,
octree_depth: int,
indexing: str = "ij"):
length = bbox_max - bbox_min
num_cells = np.exp2(octree_depth)
x = np.linspace(bbox_min[0], bbox_max[0], int(num_cells) + 1, dtype=np.float32)
y = np.linspace(bbox_min[1], bbox_max[1], int(num_cells) + 1, dtype=np.float32)
z = np.linspace(bbox_min[2], bbox_max[2], int(num_cells) + 1, dtype=np.float32)
[xs, ys, zs] = np.meshgrid(x, y, z, indexing=indexing)
xyz = np.stack((xs, ys, zs), axis=-1)
xyz = xyz.reshape(-1, 3)
grid_size = [int(num_cells) + 1, int(num_cells) + 1, int(num_cells) + 1]
return xyz, grid_size, length

View File

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

View File

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

View File

@ -0,0 +1,483 @@
# -*- coding: utf-8 -*-
from omegaconf import DictConfig
from typing import List, Tuple, Dict, Optional, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.optim import lr_scheduler
import pytorch_lightning as pl
from pytorch_lightning.utilities import rank_zero_only
from einops import rearrange
from diffusers.schedulers import (
DDPMScheduler,
DDIMScheduler,
KarrasVeScheduler,
DPMSolverMultistepScheduler
)
from MeshAnything.miche.michelangelo.utils import instantiate_from_config
# from MeshAnything.miche.michelangelo.models.tsal.tsal_base import ShapeAsLatentPLModule
from MeshAnything.miche.michelangelo.models.tsal.tsal_base import AlignedShapeAsLatentPLModule
from MeshAnything.miche.michelangelo.models.asl_diffusion.inference_utils import ddim_sample
SchedulerType = Union[DDIMScheduler, KarrasVeScheduler, DPMSolverMultistepScheduler]
def disabled_train(self, mode=True):
"""Overwrite model.train with this function to make sure train/eval mode
does not change anymore."""
return self
class ASLDiffuser(pl.LightningModule):
first_stage_model: Optional[AlignedShapeAsLatentPLModule]
# cond_stage_model: Optional[Union[nn.Module, pl.LightningModule]]
model: nn.Module
def __init__(self, *,
first_stage_config,
denoiser_cfg,
scheduler_cfg,
optimizer_cfg,
loss_cfg,
first_stage_key: str = "surface",
cond_stage_key: str = "image",
cond_stage_trainable: bool = True,
scale_by_std: bool = False,
z_scale_factor: float = 1.0,
ckpt_path: Optional[str] = None,
ignore_keys: Union[Tuple[str], List[str]] = ()):
super().__init__()
self.first_stage_key = first_stage_key
self.cond_stage_key = cond_stage_key
self.cond_stage_trainable = cond_stage_trainable
# 1. initialize first stage.
# Note: the condition model contained in the first stage model.
self.first_stage_config = first_stage_config
self.first_stage_model = None
# self.instantiate_first_stage(first_stage_config)
# 2. initialize conditional stage
# self.instantiate_cond_stage(cond_stage_config)
self.cond_stage_model = {
"image": self.encode_image,
"image_unconditional_embedding": self.empty_img_cond,
"text": self.encode_text,
"text_unconditional_embedding": self.empty_text_cond,
"surface": self.encode_surface,
"surface_unconditional_embedding": self.empty_surface_cond,
}
# 3. diffusion model
self.model = instantiate_from_config(
denoiser_cfg, device=None, dtype=None
)
self.optimizer_cfg = optimizer_cfg
# 4. scheduling strategy
self.scheduler_cfg = scheduler_cfg
self.noise_scheduler: DDPMScheduler = instantiate_from_config(scheduler_cfg.noise)
self.denoise_scheduler: SchedulerType = instantiate_from_config(scheduler_cfg.denoise)
# 5. loss configures
self.loss_cfg = loss_cfg
self.scale_by_std = scale_by_std
if scale_by_std:
self.register_buffer("z_scale_factor", torch.tensor(z_scale_factor))
else:
self.z_scale_factor = z_scale_factor
self.ckpt_path = ckpt_path
if ckpt_path is not None:
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
def instantiate_first_stage(self, config):
model = instantiate_from_config(config)
self.first_stage_model = model.eval()
self.first_stage_model.train = disabled_train
for param in self.first_stage_model.parameters():
param.requires_grad = False
self.first_stage_model = self.first_stage_model.to(self.device)
# def instantiate_cond_stage(self, config):
# if not self.cond_stage_trainable:
# if config == "__is_first_stage__":
# print("Using first stage also as cond stage.")
# self.cond_stage_model = self.first_stage_model
# elif config == "__is_unconditional__":
# print(f"Training {self.__class__.__name__} as an unconditional model.")
# self.cond_stage_model = None
# # self.be_unconditional = True
# else:
# model = instantiate_from_config(config)
# self.cond_stage_model = model.eval()
# self.cond_stage_model.train = disabled_train
# for param in self.cond_stage_model.parameters():
# param.requires_grad = False
# else:
# assert config != "__is_first_stage__"
# assert config != "__is_unconditional__"
# model = instantiate_from_config(config)
# self.cond_stage_model = model
def init_from_ckpt(self, path, ignore_keys=()):
state_dict = torch.load(path, map_location="cpu")["state_dict"]
keys = list(state_dict.keys())
for k in keys:
for ik in ignore_keys:
if k.startswith(ik):
print("Deleting key {} from state_dict.".format(k))
del state_dict[k]
missing, unexpected = self.load_state_dict(state_dict, strict=False)
print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
if len(missing) > 0:
print(f"Missing Keys: {missing}")
print(f"Unexpected Keys: {unexpected}")
@property
def zero_rank(self):
if self._trainer:
zero_rank = self.trainer.local_rank == 0
else:
zero_rank = True
return zero_rank
def configure_optimizers(self) -> Tuple[List, List]:
lr = self.learning_rate
trainable_parameters = list(self.model.parameters())
# if the conditional encoder is trainable
# if self.cond_stage_trainable:
# conditioner_params = [p for p in self.cond_stage_model.parameters() if p.requires_grad]
# trainable_parameters += conditioner_params
# print(f"number of trainable conditional parameters: {len(conditioner_params)}.")
if self.optimizer_cfg is None:
optimizers = [torch.optim.AdamW(trainable_parameters, lr=lr, betas=(0.9, 0.99), weight_decay=1e-3)]
schedulers = []
else:
optimizer = instantiate_from_config(self.optimizer_cfg.optimizer, params=trainable_parameters)
scheduler_func = instantiate_from_config(
self.optimizer_cfg.scheduler,
max_decay_steps=self.trainer.max_steps,
lr_max=lr
)
scheduler = {
"scheduler": lr_scheduler.LambdaLR(optimizer, lr_lambda=scheduler_func.schedule),
"interval": "step",
"frequency": 1
}
optimizers = [optimizer]
schedulers = [scheduler]
return optimizers, schedulers
@torch.no_grad()
def encode_text(self, text):
b = text.shape[0]
text_tokens = rearrange(text, "b t l -> (b t) l")
text_embed = self.first_stage_model.model.encode_text_embed(text_tokens)
text_embed = rearrange(text_embed, "(b t) d -> b t d", b=b)
text_embed = text_embed.mean(dim=1)
text_embed = text_embed / text_embed.norm(dim=-1, keepdim=True)
return text_embed
@torch.no_grad()
def encode_image(self, img):
return self.first_stage_model.model.encode_image_embed(img)
@torch.no_grad()
def encode_surface(self, surface):
return self.first_stage_model.model.encode_shape_embed(surface, return_latents=False)
@torch.no_grad()
def empty_text_cond(self, cond):
return torch.zeros_like(cond, device=cond.device)
@torch.no_grad()
def empty_img_cond(self, cond):
return torch.zeros_like(cond, device=cond.device)
@torch.no_grad()
def empty_surface_cond(self, cond):
return torch.zeros_like(cond, device=cond.device)
@torch.no_grad()
def encode_first_stage(self, surface: torch.FloatTensor, sample_posterior=True):
z_q = self.first_stage_model.encode(surface, sample_posterior)
z_q = self.z_scale_factor * z_q
return z_q
@torch.no_grad()
def decode_first_stage(self, z_q: torch.FloatTensor, **kwargs):
z_q = 1. / self.z_scale_factor * z_q
latents = self.first_stage_model.decode(z_q, **kwargs)
return latents
@rank_zero_only
@torch.no_grad()
def on_train_batch_start(self, batch, batch_idx):
# only for very first batch
if self.scale_by_std and self.current_epoch == 0 and self.global_step == 0 \
and batch_idx == 0 and self.ckpt_path is None:
# set rescale weight to 1./std of encodings
print("### USING STD-RESCALING ###")
z_q = self.encode_first_stage(batch[self.first_stage_key])
z = z_q.detach()
del self.z_scale_factor
self.register_buffer("z_scale_factor", 1. / z.flatten().std())
print(f"setting self.z_scale_factor to {self.z_scale_factor}")
print("### USING STD-RESCALING ###")
def compute_loss(self, model_outputs, split):
"""
Args:
model_outputs (dict):
- x_0:
- noise:
- noise_prior:
- noise_pred:
- noise_pred_prior:
split (str):
Returns:
"""
pred = model_outputs["pred"]
if self.noise_scheduler.prediction_type == "epsilon":
target = model_outputs["noise"]
elif self.noise_scheduler.prediction_type == "sample":
target = model_outputs["x_0"]
else:
raise NotImplementedError(f"Prediction Type: {self.noise_scheduler.prediction_type} not yet supported.")
if self.loss_cfg.loss_type == "l1":
simple = F.l1_loss(pred, target, reduction="mean")
elif self.loss_cfg.loss_type in ["mse", "l2"]:
simple = F.mse_loss(pred, target, reduction="mean")
else:
raise NotImplementedError(f"Loss Type: {self.loss_cfg.loss_type} not yet supported.")
total_loss = simple
loss_dict = {
f"{split}/total_loss": total_loss.clone().detach(),
f"{split}/simple": simple.detach(),
}
return total_loss, loss_dict
def forward(self, batch):
"""
Args:
batch:
Returns:
"""
if self.first_stage_model is None:
self.instantiate_first_stage(self.first_stage_config)
latents = self.encode_first_stage(batch[self.first_stage_key])
# conditions = self.cond_stage_model.encode(batch[self.cond_stage_key])
conditions = self.cond_stage_model[self.cond_stage_key](batch[self.cond_stage_key]).unsqueeze(1)
mask = torch.rand((len(conditions), 1, 1), device=conditions.device, dtype=conditions.dtype) >= 0.1
conditions = conditions * mask.to(conditions)
# Sample noise that we"ll add to the latents
# [batch_size, n_token, latent_dim]
noise = torch.randn_like(latents)
bs = latents.shape[0]
# Sample a random timestep for each motion
timesteps = torch.randint(
0,
self.noise_scheduler.config.num_train_timesteps,
(bs,),
device=latents.device,
)
timesteps = timesteps.long()
# Add noise to the latents according to the noise magnitude at each timestep
noisy_z = self.noise_scheduler.add_noise(latents, noise, timesteps)
# diffusion model forward
noise_pred = self.model(noisy_z, timesteps, conditions)
diffusion_outputs = {
"x_0": noisy_z,
"noise": noise,
"pred": noise_pred
}
return diffusion_outputs
def training_step(self, batch: Dict[str, Union[torch.FloatTensor, List[str]]],
batch_idx: int, optimizer_idx: int = 0) -> torch.FloatTensor:
"""
Args:
batch (dict): the batch sample, and it contains:
- surface (torch.FloatTensor):
- image (torch.FloatTensor): if provide, [bs, 3, h, w], item range [0, 1]
- depth (torch.FloatTensor): if provide, [bs, 1, h, w], item range [-1, 1]
- normal (torch.FloatTensor): if provide, [bs, 3, h, w], item range [-1, 1]
- text (list of str):
batch_idx (int):
optimizer_idx (int):
Returns:
loss (torch.FloatTensor):
"""
diffusion_outputs = self(batch)
loss, loss_dict = self.compute_loss(diffusion_outputs, "train")
self.log_dict(loss_dict, prog_bar=True, logger=True, sync_dist=False, rank_zero_only=True)
return loss
def validation_step(self, batch: Dict[str, torch.FloatTensor],
batch_idx: int, optimizer_idx: int = 0) -> torch.FloatTensor:
"""
Args:
batch (dict): the batch sample, and it contains:
- surface_pc (torch.FloatTensor): [n_pts, 4]
- surface_feats (torch.FloatTensor): [n_pts, c]
- text (list of str):
batch_idx (int):
optimizer_idx (int):
Returns:
loss (torch.FloatTensor):
"""
diffusion_outputs = self(batch)
loss, loss_dict = self.compute_loss(diffusion_outputs, "val")
self.log_dict(loss_dict, prog_bar=True, logger=True, sync_dist=False, rank_zero_only=True)
return loss
@torch.no_grad()
def sample(self,
batch: Dict[str, Union[torch.FloatTensor, List[str]]],
sample_times: int = 1,
steps: Optional[int] = None,
guidance_scale: Optional[float] = None,
eta: float = 0.0,
return_intermediates: bool = False, **kwargs):
if self.first_stage_model is None:
self.instantiate_first_stage(self.first_stage_config)
if steps is None:
steps = self.scheduler_cfg.num_inference_steps
if guidance_scale is None:
guidance_scale = self.scheduler_cfg.guidance_scale
do_classifier_free_guidance = guidance_scale > 0
# conditional encode
xc = batch[self.cond_stage_key]
# cond = self.cond_stage_model[self.cond_stage_key](xc)
cond = self.cond_stage_model[self.cond_stage_key](xc).unsqueeze(1)
if do_classifier_free_guidance:
"""
Note: There are two kinds of uncond for text.
1: using "" as uncond text; (in SAL diffusion)
2: zeros_like(cond) as uncond text; (in MDM)
"""
# un_cond = self.cond_stage_model.unconditional_embedding(batch_size=len(xc))
un_cond = self.cond_stage_model[f"{self.cond_stage_key}_unconditional_embedding"](cond)
# un_cond = torch.zeros_like(cond, device=cond.device)
cond = torch.cat([un_cond, cond], dim=0)
outputs = []
latents = None
if not return_intermediates:
for _ in range(sample_times):
sample_loop = ddim_sample(
self.denoise_scheduler,
self.model,
shape=self.first_stage_model.latent_shape,
cond=cond,
steps=steps,
guidance_scale=guidance_scale,
do_classifier_free_guidance=do_classifier_free_guidance,
device=self.device,
eta=eta,
disable_prog=not self.zero_rank
)
for sample, t in sample_loop:
latents = sample
outputs.append(self.decode_first_stage(latents, **kwargs))
else:
sample_loop = ddim_sample(
self.denoise_scheduler,
self.model,
shape=self.first_stage_model.latent_shape,
cond=cond,
steps=steps,
guidance_scale=guidance_scale,
do_classifier_free_guidance=do_classifier_free_guidance,
device=self.device,
eta=eta,
disable_prog=not self.zero_rank
)
iter_size = steps // sample_times
i = 0
for sample, t in sample_loop:
latents = sample
if i % iter_size == 0 or i == steps - 1:
outputs.append(self.decode_first_stage(latents, **kwargs))
i += 1
return outputs

View File

@ -0,0 +1,104 @@
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
from typing import Optional
from diffusers.models.embeddings import Timesteps
import math
from MeshAnything.miche.michelangelo.models.modules.transformer_blocks import MLP
from MeshAnything.miche.michelangelo.models.modules.diffusion_transformer import UNetDiffusionTransformer
class ConditionalASLUDTDenoiser(nn.Module):
def __init__(self, *,
device: Optional[torch.device],
dtype: Optional[torch.dtype],
input_channels: int,
output_channels: int,
n_ctx: int,
width: int,
layers: int,
heads: int,
context_dim: int,
context_ln: bool = True,
skip_ln: bool = False,
init_scale: float = 0.25,
flip_sin_to_cos: bool = False,
use_checkpoint: bool = False):
super().__init__()
self.use_checkpoint = use_checkpoint
init_scale = init_scale * math.sqrt(1.0 / width)
self.backbone = UNetDiffusionTransformer(
device=device,
dtype=dtype,
n_ctx=n_ctx,
width=width,
layers=layers,
heads=heads,
skip_ln=skip_ln,
init_scale=init_scale,
use_checkpoint=use_checkpoint
)
self.ln_post = nn.LayerNorm(width, device=device, dtype=dtype)
self.input_proj = nn.Linear(input_channels, width, device=device, dtype=dtype)
self.output_proj = nn.Linear(width, output_channels, device=device, dtype=dtype)
# timestep embedding
self.time_embed = Timesteps(width, flip_sin_to_cos=flip_sin_to_cos, downscale_freq_shift=0)
self.time_proj = MLP(
device=device, dtype=dtype, width=width, init_scale=init_scale
)
self.context_embed = nn.Sequential(
nn.LayerNorm(context_dim, device=device, dtype=dtype),
nn.Linear(context_dim, width, device=device, dtype=dtype),
)
if context_ln:
self.context_embed = nn.Sequential(
nn.LayerNorm(context_dim, device=device, dtype=dtype),
nn.Linear(context_dim, width, device=device, dtype=dtype),
)
else:
self.context_embed = nn.Linear(context_dim, width, device=device, dtype=dtype)
def forward(self,
model_input: torch.FloatTensor,
timestep: torch.LongTensor,
context: torch.FloatTensor):
r"""
Args:
model_input (torch.FloatTensor): [bs, n_data, c]
timestep (torch.LongTensor): [bs,]
context (torch.FloatTensor): [bs, context_tokens, c]
Returns:
sample (torch.FloatTensor): [bs, n_data, c]
"""
_, n_data, _ = model_input.shape
# 1. time
t_emb = self.time_proj(self.time_embed(timestep)).unsqueeze(dim=1)
# 2. conditions projector
context = self.context_embed(context)
# 3. denoiser
x = self.input_proj(model_input)
x = torch.cat([t_emb, context, x], dim=1)
x = self.backbone(x)
x = self.ln_post(x)
x = x[:, -n_data:]
sample = self.output_proj(x)
return sample

View File

@ -0,0 +1,13 @@
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
class BaseDenoiser(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x, t, context):
raise NotImplementedError

View File

@ -0,0 +1,393 @@
# -*- coding: utf-8 -*-
from omegaconf import DictConfig
from typing import List, Tuple, Dict, Optional, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.optim import lr_scheduler
import pytorch_lightning as pl
from pytorch_lightning.utilities import rank_zero_only
from diffusers.schedulers import (
DDPMScheduler,
DDIMScheduler,
KarrasVeScheduler,
DPMSolverMultistepScheduler
)
from MeshAnything.miche.michelangelo.utils import instantiate_from_config
from MeshAnything.miche.michelangelo.models.tsal.tsal_base import AlignedShapeAsLatentPLModule
from MeshAnything.miche.michelangelo.models.asl_diffusion.inference_utils import ddim_sample
SchedulerType = Union[DDIMScheduler, KarrasVeScheduler, DPMSolverMultistepScheduler]
def disabled_train(self, mode=True):
"""Overwrite model.train with this function to make sure train/eval mode
does not change anymore."""
return self
class ClipASLDiffuser(pl.LightningModule):
first_stage_model: Optional[AlignedShapeAsLatentPLModule]
cond_stage_model: Optional[Union[nn.Module, pl.LightningModule]]
model: nn.Module
def __init__(self, *,
first_stage_config,
cond_stage_config,
denoiser_cfg,
scheduler_cfg,
optimizer_cfg,
loss_cfg,
first_stage_key: str = "surface",
cond_stage_key: str = "image",
scale_by_std: bool = False,
z_scale_factor: float = 1.0,
ckpt_path: Optional[str] = None,
ignore_keys: Union[Tuple[str], List[str]] = ()):
super().__init__()
self.first_stage_key = first_stage_key
self.cond_stage_key = cond_stage_key
# 1. lazy initialize first stage
self.instantiate_first_stage(first_stage_config)
# 2. initialize conditional stage
self.instantiate_cond_stage(cond_stage_config)
# 3. diffusion model
self.model = instantiate_from_config(
denoiser_cfg, device=None, dtype=None
)
self.optimizer_cfg = optimizer_cfg
# 4. scheduling strategy
self.scheduler_cfg = scheduler_cfg
self.noise_scheduler: DDPMScheduler = instantiate_from_config(scheduler_cfg.noise)
self.denoise_scheduler: SchedulerType = instantiate_from_config(scheduler_cfg.denoise)
# 5. loss configures
self.loss_cfg = loss_cfg
self.scale_by_std = scale_by_std
if scale_by_std:
self.register_buffer("z_scale_factor", torch.tensor(z_scale_factor))
else:
self.z_scale_factor = z_scale_factor
self.ckpt_path = ckpt_path
if ckpt_path is not None:
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
def instantiate_non_trainable_model(self, config):
model = instantiate_from_config(config)
model = model.eval()
model.train = disabled_train
for param in model.parameters():
param.requires_grad = False
return model
def instantiate_first_stage(self, first_stage_config):
self.first_stage_model = self.instantiate_non_trainable_model(first_stage_config)
self.first_stage_model.set_shape_model_only()
def instantiate_cond_stage(self, cond_stage_config):
self.cond_stage_model = self.instantiate_non_trainable_model(cond_stage_config)
def init_from_ckpt(self, path, ignore_keys=()):
state_dict = torch.load(path, map_location="cpu")["state_dict"]
keys = list(state_dict.keys())
for k in keys:
for ik in ignore_keys:
if k.startswith(ik):
print("Deleting key {} from state_dict.".format(k))
del state_dict[k]
missing, unexpected = self.load_state_dict(state_dict, strict=False)
print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
if len(missing) > 0:
print(f"Missing Keys: {missing}")
print(f"Unexpected Keys: {unexpected}")
@property
def zero_rank(self):
if self._trainer:
zero_rank = self.trainer.local_rank == 0
else:
zero_rank = True
return zero_rank
def configure_optimizers(self) -> Tuple[List, List]:
lr = self.learning_rate
trainable_parameters = list(self.model.parameters())
if self.optimizer_cfg is None:
optimizers = [torch.optim.AdamW(trainable_parameters, lr=lr, betas=(0.9, 0.99), weight_decay=1e-3)]
schedulers = []
else:
optimizer = instantiate_from_config(self.optimizer_cfg.optimizer, params=trainable_parameters)
scheduler_func = instantiate_from_config(
self.optimizer_cfg.scheduler,
max_decay_steps=self.trainer.max_steps,
lr_max=lr
)
scheduler = {
"scheduler": lr_scheduler.LambdaLR(optimizer, lr_lambda=scheduler_func.schedule),
"interval": "step",
"frequency": 1
}
optimizers = [optimizer]
schedulers = [scheduler]
return optimizers, schedulers
@torch.no_grad()
def encode_first_stage(self, surface: torch.FloatTensor, sample_posterior=True):
z_q = self.first_stage_model.encode(surface, sample_posterior)
z_q = self.z_scale_factor * z_q
return z_q
@torch.no_grad()
def decode_first_stage(self, z_q: torch.FloatTensor, **kwargs):
z_q = 1. / self.z_scale_factor * z_q
latents = self.first_stage_model.decode(z_q, **kwargs)
return latents
@rank_zero_only
@torch.no_grad()
def on_train_batch_start(self, batch, batch_idx):
# only for very first batch
if self.scale_by_std and self.current_epoch == 0 and self.global_step == 0 \
and batch_idx == 0 and self.ckpt_path is None:
# set rescale weight to 1./std of encodings
print("### USING STD-RESCALING ###")
z_q = self.encode_first_stage(batch[self.first_stage_key])
z = z_q.detach()
del self.z_scale_factor
self.register_buffer("z_scale_factor", 1. / z.flatten().std())
print(f"setting self.z_scale_factor to {self.z_scale_factor}")
print("### USING STD-RESCALING ###")
def compute_loss(self, model_outputs, split):
"""
Args:
model_outputs (dict):
- x_0:
- noise:
- noise_prior:
- noise_pred:
- noise_pred_prior:
split (str):
Returns:
"""
pred = model_outputs["pred"]
if self.noise_scheduler.prediction_type == "epsilon":
target = model_outputs["noise"]
elif self.noise_scheduler.prediction_type == "sample":
target = model_outputs["x_0"]
else:
raise NotImplementedError(f"Prediction Type: {self.noise_scheduler.prediction_type} not yet supported.")
if self.loss_cfg.loss_type == "l1":
simple = F.l1_loss(pred, target, reduction="mean")
elif self.loss_cfg.loss_type in ["mse", "l2"]:
simple = F.mse_loss(pred, target, reduction="mean")
else:
raise NotImplementedError(f"Loss Type: {self.loss_cfg.loss_type} not yet supported.")
total_loss = simple
loss_dict = {
f"{split}/total_loss": total_loss.clone().detach(),
f"{split}/simple": simple.detach(),
}
return total_loss, loss_dict
def forward(self, batch):
"""
Args:
batch:
Returns:
"""
latents = self.encode_first_stage(batch[self.first_stage_key])
conditions = self.cond_stage_model.encode(batch[self.cond_stage_key])
# Sample noise that we"ll add to the latents
# [batch_size, n_token, latent_dim]
noise = torch.randn_like(latents)
bs = latents.shape[0]
# Sample a random timestep for each motion
timesteps = torch.randint(
0,
self.noise_scheduler.config.num_train_timesteps,
(bs,),
device=latents.device,
)
timesteps = timesteps.long()
# Add noise to the latents according to the noise magnitude at each timestep
noisy_z = self.noise_scheduler.add_noise(latents, noise, timesteps)
# diffusion model forward
noise_pred = self.model(noisy_z, timesteps, conditions)
diffusion_outputs = {
"x_0": noisy_z,
"noise": noise,
"pred": noise_pred
}
return diffusion_outputs
def training_step(self, batch: Dict[str, Union[torch.FloatTensor, List[str]]],
batch_idx: int, optimizer_idx: int = 0) -> torch.FloatTensor:
"""
Args:
batch (dict): the batch sample, and it contains:
- surface (torch.FloatTensor):
- image (torch.FloatTensor): if provide, [bs, 3, h, w], item range [0, 1]
- depth (torch.FloatTensor): if provide, [bs, 1, h, w], item range [-1, 1]
- normal (torch.FloatTensor): if provide, [bs, 3, h, w], item range [-1, 1]
- text (list of str):
batch_idx (int):
optimizer_idx (int):
Returns:
loss (torch.FloatTensor):
"""
diffusion_outputs = self(batch)
loss, loss_dict = self.compute_loss(diffusion_outputs, "train")
self.log_dict(loss_dict, prog_bar=True, logger=True, sync_dist=False, rank_zero_only=True)
return loss
def validation_step(self, batch: Dict[str, torch.FloatTensor],
batch_idx: int, optimizer_idx: int = 0) -> torch.FloatTensor:
"""
Args:
batch (dict): the batch sample, and it contains:
- surface_pc (torch.FloatTensor): [n_pts, 4]
- surface_feats (torch.FloatTensor): [n_pts, c]
- text (list of str):
batch_idx (int):
optimizer_idx (int):
Returns:
loss (torch.FloatTensor):
"""
diffusion_outputs = self(batch)
loss, loss_dict = self.compute_loss(diffusion_outputs, "val")
self.log_dict(loss_dict, prog_bar=True, logger=True, sync_dist=False, rank_zero_only=True)
return loss
@torch.no_grad()
def sample(self,
batch: Dict[str, Union[torch.FloatTensor, List[str]]],
sample_times: int = 1,
steps: Optional[int] = None,
guidance_scale: Optional[float] = None,
eta: float = 0.0,
return_intermediates: bool = False, **kwargs):
if steps is None:
steps = self.scheduler_cfg.num_inference_steps
if guidance_scale is None:
guidance_scale = self.scheduler_cfg.guidance_scale
do_classifier_free_guidance = guidance_scale > 0
# conditional encode
xc = batch[self.cond_stage_key]
# print(self.first_stage_model.device, self.cond_stage_model.device, self.device)
cond = self.cond_stage_model(xc)
if do_classifier_free_guidance:
un_cond = self.cond_stage_model.unconditional_embedding(batch_size=len(xc))
cond = torch.cat([un_cond, cond], dim=0)
outputs = []
latents = None
if not return_intermediates:
for _ in range(sample_times):
sample_loop = ddim_sample(
self.denoise_scheduler,
self.model,
shape=self.first_stage_model.latent_shape,
cond=cond,
steps=steps,
guidance_scale=guidance_scale,
do_classifier_free_guidance=do_classifier_free_guidance,
device=self.device,
eta=eta,
disable_prog=not self.zero_rank
)
for sample, t in sample_loop:
latents = sample
outputs.append(self.decode_first_stage(latents, **kwargs))
else:
sample_loop = ddim_sample(
self.denoise_scheduler,
self.model,
shape=self.first_stage_model.latent_shape,
cond=cond,
steps=steps,
guidance_scale=guidance_scale,
do_classifier_free_guidance=do_classifier_free_guidance,
device=self.device,
eta=eta,
disable_prog=not self.zero_rank
)
iter_size = steps // sample_times
i = 0
for sample, t in sample_loop:
latents = sample
if i % iter_size == 0 or i == steps - 1:
outputs.append(self.decode_first_stage(latents, **kwargs))
i += 1
return outputs

View File

@ -0,0 +1,80 @@
# -*- coding: utf-8 -*-
import torch
from tqdm import tqdm
from typing import Tuple, List, Union, Optional
from diffusers.schedulers import DDIMScheduler
__all__ = ["ddim_sample"]
def ddim_sample(ddim_scheduler: DDIMScheduler,
diffusion_model: torch.nn.Module,
shape: Union[List[int], Tuple[int]],
cond: torch.FloatTensor,
steps: int,
eta: float = 0.0,
guidance_scale: float = 3.0,
do_classifier_free_guidance: bool = True,
generator: Optional[torch.Generator] = None,
device: torch.device = "cuda:0",
disable_prog: bool = True):
assert steps > 0, f"{steps} must > 0."
# init latents
bsz = cond.shape[0]
if do_classifier_free_guidance:
bsz = bsz // 2
latents = torch.randn(
(bsz, *shape),
generator=generator,
device=cond.device,
dtype=cond.dtype,
)
# scale the initial noise by the standard deviation required by the scheduler
latents = latents * ddim_scheduler.init_noise_sigma
# set timesteps
ddim_scheduler.set_timesteps(steps)
timesteps = ddim_scheduler.timesteps.to(device)
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
# eta (η) is only used with the DDIMScheduler, and between [0, 1]
extra_step_kwargs = {
"eta": eta,
"generator": generator
}
# reverse
for i, t in enumerate(tqdm(timesteps, disable=disable_prog, desc="DDIM Sampling:", leave=False)):
# expand the latents if we are doing classifier free guidance
latent_model_input = (
torch.cat([latents] * 2)
if do_classifier_free_guidance
else latents
)
# latent_model_input = scheduler.scale_model_input(latent_model_input, t)
# predict the noise residual
timestep_tensor = torch.tensor([t], dtype=torch.long, device=device)
timestep_tensor = timestep_tensor.expand(latent_model_input.shape[0])
noise_pred = diffusion_model.forward(latent_model_input, timestep_tensor, cond)
# perform guidance
if do_classifier_free_guidance:
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
noise_pred = noise_pred_uncond + guidance_scale * (
noise_pred_text - noise_pred_uncond
)
# text_embeddings_for_guidance = encoder_hidden_states.chunk(
# 2)[1] if do_classifier_free_guidance else encoder_hidden_states
# compute the previous noisy sample x_t -> x_t-1
latents = ddim_scheduler.step(
noise_pred, t, latents, **extra_step_kwargs
).prev_sample
yield latents, t
def karra_sample():
pass

View File

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

View File

@ -0,0 +1,89 @@
# -*- coding: utf-8 -*-
import torch
import numpy as np
from PIL import Image
from dataclasses import dataclass
from torchvision.transforms import Normalize
from transformers import CLIPModel, CLIPTokenizer
from transformers.utils import ModelOutput
from typing import Iterable, Optional, Union, List
ImageType = Union[np.ndarray, torch.Tensor, Image.Image]
@dataclass
class CLIPEmbedOutput(ModelOutput):
last_hidden_state: torch.FloatTensor = None
pooler_output: torch.FloatTensor = None
embeds: torch.FloatTensor = None
class CLIPEncoder(torch.nn.Module):
def __init__(self, model_path="openai/clip-vit-base-patch32"):
super().__init__()
# Load the CLIP model and processor
self.model: CLIPModel = CLIPModel.from_pretrained(model_path)
self.tokenizer = CLIPTokenizer.from_pretrained(model_path)
self.image_preprocess = Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
self.model.training = False
for p in self.model.parameters():
p.requires_grad = False
@torch.no_grad()
def encode_image(self, images: Iterable[Optional[ImageType]]):
pixel_values = self.image_preprocess(images)
vision_outputs = self.model.vision_model(pixel_values=pixel_values)
pooler_output = vision_outputs[1] # pooled_output
image_features = self.model.visual_projection(pooler_output)
visual_embeds = CLIPEmbedOutput(
last_hidden_state=vision_outputs.last_hidden_state,
pooler_output=pooler_output,
embeds=image_features
)
return visual_embeds
@torch.no_grad()
def encode_text(self, texts: List[str]):
text_inputs = self.tokenizer(texts, padding=True, return_tensors="pt")
text_outputs = self.model.text_model(input_ids=text_inputs)
pooler_output = text_outputs[1] # pooled_output
text_features = self.model.text_projection(pooler_output)
text_embeds = CLIPEmbedOutput(
last_hidden_state=text_outputs.last_hidden_state,
pooler_output=pooler_output,
embeds=text_features
)
return text_embeds
def forward(self,
images: Iterable[Optional[ImageType]],
texts: List[str]):
visual_embeds = self.encode_image(images)
text_embeds = self.encode_text(texts)
return visual_embeds, text_embeds

View File

@ -0,0 +1,562 @@
# -*- coding: utf-8 -*-
import os
import torch
import torch.nn as nn
from torchvision import transforms
from transformers import CLIPModel, CLIPTokenizer
from collections import OrderedDict
from MeshAnything.miche.michelangelo.data.transforms import RandomResize
class AbstractEncoder(nn.Module):
embedding_dim: int
def __init__(self):
super().__init__()
def encode(self, *args, **kwargs):
raise NotImplementedError
class ClassEmbedder(nn.Module):
def __init__(self, embed_dim, n_classes=1000, key="class"):
super().__init__()
self.key = key
self.embedding = nn.Embedding(n_classes, embed_dim)
def forward(self, batch, key=None):
if key is None:
key = self.key
# this is for use in crossattn
c = batch[key][:, None]
c = self.embedding(c)
return c
class FrozenCLIPTextEmbedder(AbstractEncoder):
"""Uses the CLIP transformer encoder for text (from Hugging Face)"""
def __init__(
self,
version="openai/clip-vit-large-patch14",
tokenizer_version=None,
device="cuda",
max_length=77,
zero_embedding_radio: float = 0.1,
):
super().__init__()
self.tokenizer = CLIPTokenizer.from_pretrained(tokenizer_version or version)
self.device = device
self.max_length = max_length
self.zero_embedding_radio = zero_embedding_radio
self.clip_dict = OrderedDict()
self.clip_name = os.path.split(version)[-1]
transformer = CLIPModel.from_pretrained(version).text_model
for param in transformer.parameters():
param.requires_grad = False
self.clip_dict[self.clip_name] = transformer
self._move_flag = False
@property
def clip(self):
return self.clip_dict[self.clip_name]
def move(self):
if self._move_flag:
return
self.clip_dict[self.clip_name] = self.clip_dict[self.clip_name].to(self.device)
self._move_flag = True
def unconditional_embedding(self, batch_size):
empty_text = [""] * batch_size
empty_z = self.forward(empty_text)
return empty_z
def forward(self, text):
self.move()
batch_encoding = self.tokenizer(
text,
truncation=True,
max_length=self.max_length,
return_length=True,
return_overflowing_tokens=False,
padding="max_length",
return_tensors="pt",
)
tokens = batch_encoding["input_ids"].to(self.device)
outputs = self.clip(input_ids=tokens)
z = outputs.last_hidden_state
return z
def encode(self, text):
batch_size = len(text)
batch_mask = torch.rand((batch_size,))
for i in range(batch_size):
if batch_mask[i] < self.zero_embedding_radio:
text[i] = ""
return self(text)
class FrozenAlignedCLIPTextEmbedder(AbstractEncoder):
"""Uses the CLIP transformer encoder for text (from Hugging Face)"""
def __init__(
self,
version="openai/clip-vit-large-patch14",
tokenizer_version=None,
device="cuda",
max_length=77,
zero_embedding_radio: float = 0.1,
):
super().__init__()
self.tokenizer = CLIPTokenizer.from_pretrained(tokenizer_version or version)
self.device = device
self.max_length = max_length
self.zero_embedding_radio = zero_embedding_radio
self.clip_dict = OrderedDict()
self.clip_name = os.path.split(version)[-1]
transformer = CLIPModel.from_pretrained(version).text_model
for param in transformer.parameters():
param.requires_grad = False
self.clip_dict[self.clip_name] = transformer
self._move_flag = False
@property
def clip(self):
return self.clip_dict[self.clip_name]
def move(self):
if self._move_flag:
return
self.clip_dict[self.clip_name] = self.clip_dict[self.clip_name].to(self.device)
self._move_flag = True
def unconditional_embedding(self, batch_size):
empty_text = [""] * batch_size
empty_z = self.forward(empty_text)
return empty_z
def forward(self, text):
self.move()
batch_encoding = self.tokenizer(
text,
truncation=True,
max_length=self.max_length,
return_length=True,
return_overflowing_tokens=False,
padding="max_length",
return_tensors="pt",
)
tokens = batch_encoding["input_ids"].to(self.device)
outputs = self.clip(input_ids=tokens)
z = outputs.last_hidden_state
return z
def encode(self, text):
batch_size = len(text)
batch_mask = torch.rand((batch_size,))
for i in range(batch_size):
if batch_mask[i] < self.zero_embedding_radio:
text[i] = ""
return self(text)
class FrozenCLIPImageEmbedder(AbstractEncoder):
"""Uses the CLIP transformer encoder for text (from Hugging Face)"""
def __init__(
self,
version="openai/clip-vit-large-patch14",
device="cuda",
zero_embedding_radio=0.1,
normalize_embedding=True,
num_projection_vector=0,
linear_mapping_bias=True,
reverse_visual_projection=False,
):
super().__init__()
self.device = device
self.clip_dict = OrderedDict()
self.clip_name = os.path.split(version)[-1]
clip_model = CLIPModel.from_pretrained(version)
clip_model.text_model = None
clip_model.text_projection = None
clip_model = clip_model.eval()
for param in self.parameters():
param.requires_grad = False
self.clip_dict[self.clip_name] = clip_model
self.transform = transforms.Compose(
[
transforms.Resize(224, transforms.InterpolationMode.BICUBIC, antialias=True),
transforms.CenterCrop(224), # crop a (224, 224) square
transforms.Normalize(
mean=[0.48145466, 0.4578275, 0.40821073],
std=[0.26862954, 0.26130258, 0.27577711],
),
]
)
self.zero_embedding_radio = zero_embedding_radio
self.num_projection_vector = num_projection_vector
self.reverse_visual_projection = reverse_visual_projection
self.normalize_embedding = normalize_embedding
embedding_dim = (
clip_model.visual_projection.in_features
if reverse_visual_projection
else clip_model.visual_projection.out_features
)
self.embedding_dim = embedding_dim
if self.num_projection_vector > 0:
self.projection = nn.Linear(
embedding_dim,
clip_model.visual_projection.out_features * num_projection_vector,
bias=linear_mapping_bias,
)
nn.init.normal_(self.projection.weight, std=embedding_dim ** -0.5)
self._move_flag = False
@property
def clip(self):
return self.clip_dict[self.clip_name]
def unconditional_embedding(self, batch_size):
zero = torch.zeros(
batch_size,
1,
self.embedding_dim,
device=self.device,
dtype=self.clip.visual_projection.weight.dtype,
)
if self.num_projection_vector > 0:
zero = self.projection(zero).view(batch_size, self.num_projection_vector, -1)
return zero
def forward(self, image, value_range=(-1, 1), zero_embedding_radio=0):
if value_range is not None:
low, high = value_range
image = (image - low) / (high - low)
image = image.to(self.device, dtype=self.clip.visual_projection.weight.dtype)
if self.reverse_visual_projection:
z = self.clip.vision_model(self.transform(image))[1]
else:
z = self.clip.get_image_features(self.transform(image))
if self.normalize_embedding:
z = z / z.norm(dim=-1, keepdim=True)
if z.ndim == 2:
z = z.unsqueeze(dim=-2)
if zero_embedding_radio > 0:
mask = torch.rand((len(image), 1, 1), device=z.device, dtype=z.dtype) < zero_embedding_radio
z = z * mask.to(z)
if self.num_projection_vector > 0:
z = self.projection(z).view(len(image), self.num_projection_vector, -1)
return z
def move(self):
if self._move_flag:
return
self.clip_dict[self.clip_name] = self.clip_dict[self.clip_name].to(self.device)
self._move_flag = True
def encode(self, image):
self.move()
return self(image, zero_embedding_radio=self.zero_embedding_radio)
class FrozenCLIPImageGridEmbedder(AbstractEncoder):
def __init__(
self,
version="openai/clip-vit-large-patch14",
device="cuda",
zero_embedding_radio=0.1,
):
super().__init__()
self.device = device
self.clip_dict = OrderedDict()
self.clip_name = os.path.split(version)[-1]
clip_model: CLIPModel = CLIPModel.from_pretrained(version)
clip_model.text_model = None
clip_model.text_projection = None
clip_model = clip_model.eval()
for param in self.parameters():
param.requires_grad = False
self.clip_dict[self.clip_name] = clip_model
self.transform = transforms.Compose(
[
transforms.Resize(224, transforms.InterpolationMode.BILINEAR, antialias=True),
transforms.CenterCrop(224), # crop a (224, 224) square
transforms.Normalize(
mean=[0.48145466, 0.4578275, 0.40821073],
std=[0.26862954, 0.26130258, 0.27577711],
),
]
)
self.zero_embedding_radio = zero_embedding_radio
self.embedding_dim = clip_model.vision_embed_dim
self._move_flag = False
@property
def clip(self):
return self.clip_dict[self.clip_name]
def move(self):
if self._move_flag:
return
self.clip_dict[self.clip_name] = self.clip_dict[self.clip_name].to(self.device)
self._move_flag = True
def unconditional_embedding(self, batch_size):
zero = torch.zeros(
batch_size,
self.clip.vision_model.embeddings.num_positions,
self.embedding_dim,
device=self.device,
dtype=self.clip.visual_projection.weight.dtype,
)
return zero
def forward(self, image, value_range=(-1, 1), zero_embedding_radio=0):
self.move()
if value_range is not None:
low, high = value_range
image = (image - low) / (high - low)
image = image.to(self.device, dtype=self.clip.visual_projection.weight.dtype)
z = self.clip.vision_model(self.transform(image)).last_hidden_state
if zero_embedding_radio > 0:
mask = torch.rand((len(image), 1, 1), device=z.device, dtype=z.dtype) >= zero_embedding_radio
z = z * mask.to(z)
return z
def encode(self, image):
return self(image, zero_embedding_radio=self.zero_embedding_radio)
class MoECLIPImageEncoder(nn.Module):
def __init__(
self,
versions,
hidden_state_dim,
num_projection_vector=8,
zero_embedding_radio=0.1,
device="cuda",
precision="fp16",
normalize=False,
clip_max=0,
transform_type="base",
argument_p=0.2,
):
super().__init__()
self.device = torch.device(device)
self.hidden_state_dim = hidden_state_dim
self.zero_embedding_radio = zero_embedding_radio
self.num_projection_vector = num_projection_vector
self.dtype = dict(fp16=torch.float16, fp32=torch.float32, bf16=torch.bfloat16)[precision]
self.normalize = normalize
self.clip_max = clip_max
if transform_type == "base":
self.transform = transforms.Compose(
[
transforms.Resize(224, transforms.InterpolationMode.BICUBIC, antialias=True),
transforms.CenterCrop(224), # crop a (224, 224) square
transforms.Normalize(
mean=[0.48145466, 0.4578275, 0.40821073],
std=[0.26862954, 0.26130258, 0.27577711],
),
]
)
elif transform_type == "crop_blur_resize":
self.transform = transforms.Compose(
[
transforms.Resize(224, transforms.InterpolationMode.BICUBIC, antialias=True),
transforms.CenterCrop(224), # crop a (224, 224) square
transforms.RandomApply(
transforms=[
transforms.RandomResizedCrop(
size=224,
scale=(0.8, 1.0),
ratio=(0.99, 1.01),
interpolation=transforms.InterpolationMode.BICUBIC,
),
],
p=argument_p,
),
transforms.RandomApply(
transforms=[
transforms.GaussianBlur(kernel_size=9, sigma=(0.1, 5)),
],
p=argument_p,
),
transforms.RandomApply(
transforms=[
RandomResize(size=224, resize_radio=(0.2, 1)),
],
p=argument_p,
),
transforms.Normalize(
mean=[0.48145466, 0.4578275, 0.40821073],
std=[0.26862954, 0.26130258, 0.27577711],
),
]
)
else:
raise ValueError(f"invalid {transform_type=}")
if isinstance(versions, str):
versions = (versions,)
# 如果直接把clips定位为当前类的子module1. 会在保存ckp时存无用的多个权重。 2. pl会调用to导致layer_norm的权重也被转换成fp16
clips = OrderedDict()
for v in versions:
# 因为clips不是子module直接指定device="cuda"会错误地导致clip模型权重都被放到cuda:0上。
clips[v], _ = clip.load(name=v, device="cpu", jit=False, download_root=None)
delattr(clips[v], "transformer")
clips[v].eval()
clips[v].requires_grad_(False)
self.clips_hidden_dim = sum(clips[v].ln_final.weight.size(0) for v in clips)
if self.num_projection_vector == 0:
self.projection = nn.Identity()
else:
self.projection = nn.Linear(self.clips_hidden_dim, hidden_state_dim * self.num_projection_vector, bias=True)
self.projection.to(dtype=self.dtype)
nn.init.normal_(self.projection.weight, std=self.clips_hidden_dim ** -0.5)
self.clips = clips
self._move_flag = False
def move(self):
if self._move_flag:
return
def convert_weights(model: nn.Module):
"""Convert applicable model parameters to fp16"""
def _convert_weights_to_fp16(l):
if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
l.weight.data = l.weight.data.type(self.dtype)
if l.bias is not None:
l.bias.data = l.bias.data.type(self.dtype)
if isinstance(l, nn.MultiheadAttention):
for attr in [
*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]],
"in_proj_bias",
"bias_k",
"bias_v",
]:
tensor = getattr(l, attr)
if tensor is not None:
tensor.data = tensor.data.type(self.dtype)
for name in ["text_projection", "proj"]:
if hasattr(l, name):
attr = getattr(l, name)
if attr is not None:
attr.data = attr.data.type(self.dtype)
model.apply(_convert_weights_to_fp16)
for k in self.clips:
self.clips[k].to(self.device)
convert_weights(self.clips[k]) # fp32 -> self.dtype
self._move_flag = True
def unconditional_embedding(self, batch_size=None):
zero = torch.zeros(
batch_size,
self.clips_hidden_dim,
device=self.device,
dtype=self.dtype,
)
if self.num_projection_vector > 0:
zero = self.projection(zero).view(batch_size, self.num_projection_vector, -1)
return zero
def convert_embedding(self, z):
if self.num_projection_vector > 0:
z = self.projection(z.type(self.projection.weight.dtype)).view(len(z), self.num_projection_vector, -1)
return z
def forward(self, image, value_range=(-1, 1), zero_embedding_radio=0):
if value_range is not None:
low, high = value_range
image = (image - low) / (high - low)
image = self.transform(image)
with torch.no_grad():
embs = []
for v in self.clips:
x = self.clips[v].encode_image(image)
if self.normalize:
x = x / x.norm(p=2, dim=-1, keepdim=True) * (x.size(-1) ** 0.5)
# clip_max only works with normalization
if self.clip_max > 0:
x = x.clamp(-self.clip_max, self.clip_max)
embs.append(x)
z = torch.cat(embs, dim=-1)
if self.normalize:
z /= z.size(-1) ** 0.5
if zero_embedding_radio > 0:
mask = torch.rand((len(image), 1, 1), device=z.device, dtype=z.dtype) >= zero_embedding_radio
z = z + mask.to(z)
if self.num_projection_vector > 0:
z = self.projection(z).view(len(image), self.num_projection_vector, -1)
return z
def encode(self, image):
self.move()
return self(image, zero_embedding_radio=self.zero_embedding_radio)

View File

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

View File

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

View File

@ -0,0 +1,218 @@
# -*- coding: utf-8 -*-
import math
import torch
import torch.nn as nn
from typing import Optional
from MeshAnything.miche.michelangelo.models.modules.checkpoint import checkpoint
from MeshAnything.miche.michelangelo.models.modules.transformer_blocks import (
init_linear,
MLP,
MultiheadCrossAttention,
MultiheadAttention,
ResidualAttentionBlock
)
class AdaLayerNorm(nn.Module):
def __init__(self,
device: torch.device,
dtype: torch.dtype,
width: int):
super().__init__()
self.silu = nn.SiLU(inplace=True)
self.linear = nn.Linear(width, width * 2, device=device, dtype=dtype)
self.layernorm = nn.LayerNorm(width, elementwise_affine=False, device=device, dtype=dtype)
def forward(self, x, timestep):
emb = self.linear(timestep)
scale, shift = torch.chunk(emb, 2, dim=2)
x = self.layernorm(x) * (1 + scale) + shift
return x
class DitBlock(nn.Module):
def __init__(
self,
*,
device: torch.device,
dtype: torch.dtype,
n_ctx: int,
width: int,
heads: int,
context_dim: int,
qkv_bias: bool = False,
init_scale: float = 1.0,
use_checkpoint: bool = False
):
super().__init__()
self.use_checkpoint = use_checkpoint
self.attn = MultiheadAttention(
device=device,
dtype=dtype,
n_ctx=n_ctx,
width=width,
heads=heads,
init_scale=init_scale,
qkv_bias=qkv_bias
)
self.ln_1 = AdaLayerNorm(device, dtype, width)
if context_dim is not None:
self.ln_2 = AdaLayerNorm(device, dtype, width)
self.cross_attn = MultiheadCrossAttention(
device=device,
dtype=dtype,
width=width,
heads=heads,
data_width=context_dim,
init_scale=init_scale,
qkv_bias=qkv_bias
)
self.mlp = MLP(device=device, dtype=dtype, width=width, init_scale=init_scale)
self.ln_3 = AdaLayerNorm(device, dtype, width)
def forward(self, x: torch.Tensor, t: torch.Tensor, context: Optional[torch.Tensor] = None):
return checkpoint(self._forward, (x, t, context), self.parameters(), self.use_checkpoint)
def _forward(self, x: torch.Tensor, t: torch.Tensor, context: Optional[torch.Tensor] = None):
x = x + self.attn(self.ln_1(x, t))
if context is not None:
x = x + self.cross_attn(self.ln_2(x, t), context)
x = x + self.mlp(self.ln_3(x, t))
return x
class DiT(nn.Module):
def __init__(
self,
*,
device: Optional[torch.device],
dtype: Optional[torch.dtype],
n_ctx: int,
width: int,
layers: int,
heads: int,
context_dim: int,
init_scale: float = 0.25,
qkv_bias: bool = False,
use_checkpoint: bool = False
):
super().__init__()
self.n_ctx = n_ctx
self.width = width
self.layers = layers
self.resblocks = nn.ModuleList(
[
DitBlock(
device=device,
dtype=dtype,
n_ctx=n_ctx,
width=width,
heads=heads,
context_dim=context_dim,
qkv_bias=qkv_bias,
init_scale=init_scale,
use_checkpoint=use_checkpoint
)
for _ in range(layers)
]
)
def forward(self, x: torch.Tensor, t: torch.Tensor, context: Optional[torch.Tensor] = None):
for block in self.resblocks:
x = block(x, t, context)
return x
class UNetDiffusionTransformer(nn.Module):
def __init__(
self,
*,
device: Optional[torch.device],
dtype: Optional[torch.dtype],
n_ctx: int,
width: int,
layers: int,
heads: int,
init_scale: float = 0.25,
qkv_bias: bool = False,
skip_ln: bool = False,
use_checkpoint: bool = False
):
super().__init__()
self.n_ctx = n_ctx
self.width = width
self.layers = layers
self.encoder = nn.ModuleList()
for _ in range(layers):
resblock = ResidualAttentionBlock(
device=device,
dtype=dtype,
n_ctx=n_ctx,
width=width,
heads=heads,
init_scale=init_scale,
qkv_bias=qkv_bias,
use_checkpoint=use_checkpoint
)
self.encoder.append(resblock)
self.middle_block = ResidualAttentionBlock(
device=device,
dtype=dtype,
n_ctx=n_ctx,
width=width,
heads=heads,
init_scale=init_scale,
qkv_bias=qkv_bias,
use_checkpoint=use_checkpoint
)
self.decoder = nn.ModuleList()
for _ in range(layers):
resblock = ResidualAttentionBlock(
device=device,
dtype=dtype,
n_ctx=n_ctx,
width=width,
heads=heads,
init_scale=init_scale,
qkv_bias=qkv_bias,
use_checkpoint=use_checkpoint
)
linear = nn.Linear(width * 2, width, device=device, dtype=dtype)
init_linear(linear, init_scale)
layer_norm = nn.LayerNorm(width, device=device, dtype=dtype) if skip_ln else None
self.decoder.append(nn.ModuleList([resblock, linear, layer_norm]))
def forward(self, x: torch.Tensor):
enc_outputs = []
for block in self.encoder:
x = block(x)
enc_outputs.append(x)
x = self.middle_block(x)
for i, (resblock, linear, layer_norm) in enumerate(self.decoder):
x = torch.cat([enc_outputs.pop(), x], dim=-1)
x = linear(x)
if layer_norm is not None:
x = layer_norm(x)
x = resblock(x)
return x

View File

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

View File

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

View File

@ -0,0 +1,286 @@
# -*- coding: utf-8 -*-
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Optional
from MeshAnything.miche.michelangelo.models.modules.checkpoint import checkpoint
def init_linear(l, stddev):
nn.init.normal_(l.weight, std=stddev)
if l.bias is not None:
nn.init.constant_(l.bias, 0.0)
class MultiheadAttention(nn.Module):
def __init__(
self,
*,
device: torch.device,
dtype: torch.dtype,
n_ctx: int,
width: int,
heads: int,
init_scale: float,
qkv_bias: bool,
flash: bool = False
):
super().__init__()
self.n_ctx = n_ctx
self.width = width
self.heads = heads
self.c_qkv = nn.Linear(width, width * 3, bias=qkv_bias, device=device, dtype=dtype)
self.c_proj = nn.Linear(width, width, device=device, dtype=dtype)
self.attention = QKVMultiheadAttention(device=device, dtype=dtype, heads=heads, n_ctx=n_ctx, flash=flash)
init_linear(self.c_qkv, init_scale)
init_linear(self.c_proj, init_scale)
def forward(self, x):
x = self.c_qkv(x)
x = checkpoint(self.attention, (x,), (), True)
x = self.c_proj(x)
return x
class QKVMultiheadAttention(nn.Module):
def __init__(self, *, device: torch.device, dtype: torch.dtype, heads: int, n_ctx: int, flash: bool = False):
super().__init__()
self.device = device
self.dtype = dtype
self.heads = heads
self.n_ctx = n_ctx
self.flash = flash
def forward(self, qkv):
bs, n_ctx, width = qkv.shape
attn_ch = width // self.heads // 3
scale = 1 / math.sqrt(math.sqrt(attn_ch))
qkv = qkv.view(bs, n_ctx, self.heads, -1)
q, k, v = torch.split(qkv, attn_ch, dim=-1)
if self.flash:
out = F.scaled_dot_product_attention(q, k, v)
else:
weight = torch.einsum(
"bthc,bshc->bhts", q * scale, k * scale
) # More stable with f16 than dividing afterwards
wdtype = weight.dtype
weight = torch.softmax(weight.float(), dim=-1).type(wdtype)
out = torch.einsum("bhts,bshc->bthc", weight, v).reshape(bs, n_ctx, -1)
return out
class ResidualAttentionBlock(nn.Module):
def __init__(
self,
*,
device: torch.device,
dtype: torch.dtype,
n_ctx: int,
width: int,
heads: int,
init_scale: float = 1.0,
qkv_bias: bool = True,
flash: bool = False,
use_checkpoint: bool = False
):
super().__init__()
self.use_checkpoint = use_checkpoint
self.attn = MultiheadAttention(
device=device,
dtype=dtype,
n_ctx=n_ctx,
width=width,
heads=heads,
init_scale=init_scale,
qkv_bias=qkv_bias,
flash=flash
)
self.ln_1 = nn.LayerNorm(width, device=device, dtype=dtype)
self.mlp = MLP(device=device, dtype=dtype, width=width, init_scale=init_scale)
self.ln_2 = nn.LayerNorm(width, device=device, dtype=dtype)
def _forward(self, x: torch.Tensor):
x = x + self.attn(self.ln_1(x))
x = x + self.mlp(self.ln_2(x))
return x
def forward(self, x: torch.Tensor):
return checkpoint(self._forward, (x,), self.parameters(), self.use_checkpoint)
class MultiheadCrossAttention(nn.Module):
def __init__(
self,
*,
device: torch.device,
dtype: torch.dtype,
width: int,
heads: int,
init_scale: float,
qkv_bias: bool = True,
flash: bool = False,
n_data: Optional[int] = None,
data_width: Optional[int] = None,
):
super().__init__()
self.n_data = n_data
self.width = width
self.heads = heads
self.data_width = width if data_width is None else data_width
self.c_q = nn.Linear(width, width, bias=qkv_bias, device=device, dtype=dtype)
self.c_kv = nn.Linear(self.data_width, width * 2, bias=qkv_bias, device=device, dtype=dtype)
self.c_proj = nn.Linear(width, width, device=device, dtype=dtype)
self.attention = QKVMultiheadCrossAttention(
device=device, dtype=dtype, heads=heads, n_data=n_data, flash=flash
)
init_linear(self.c_q, init_scale)
init_linear(self.c_kv, init_scale)
init_linear(self.c_proj, init_scale)
def forward(self, x, data):
x = self.c_q(x)
data = self.c_kv(data)
x = checkpoint(self.attention, (x, data), (), True)
x = self.c_proj(x)
return x
class QKVMultiheadCrossAttention(nn.Module):
def __init__(self, *, device: torch.device, dtype: torch.dtype, heads: int,
flash: bool = False, n_data: Optional[int] = None):
super().__init__()
self.device = device
self.dtype = dtype
self.heads = heads
self.n_data = n_data
self.flash = flash
def forward(self, q, kv):
_, n_ctx, _ = q.shape
bs, n_data, width = kv.shape
attn_ch = width // self.heads // 2
scale = 1 / math.sqrt(math.sqrt(attn_ch))
q = q.view(bs, n_ctx, self.heads, -1)
kv = kv.view(bs, n_data, self.heads, -1)
k, v = torch.split(kv, attn_ch, dim=-1)
if self.flash:
out = F.scaled_dot_product_attention(q, k, v)
else:
weight = torch.einsum(
"bthc,bshc->bhts", q * scale, k * scale
) # More stable with f16 than dividing afterwards
wdtype = weight.dtype
weight = torch.softmax(weight.float(), dim=-1).type(wdtype)
out = torch.einsum("bhts,bshc->bthc", weight, v).reshape(bs, n_ctx, -1)
return out
class ResidualCrossAttentionBlock(nn.Module):
def __init__(
self,
*,
device: Optional[torch.device],
dtype: Optional[torch.dtype],
n_data: Optional[int] = None,
width: int,
heads: int,
data_width: Optional[int] = None,
init_scale: float = 0.25,
qkv_bias: bool = True,
flash: bool = False
):
super().__init__()
if data_width is None:
data_width = width
self.attn = MultiheadCrossAttention(
device=device,
dtype=dtype,
n_data=n_data,
width=width,
heads=heads,
data_width=data_width,
init_scale=init_scale,
qkv_bias=qkv_bias,
flash=flash,
)
self.ln_1 = nn.LayerNorm(width, device=device, dtype=dtype)
self.ln_2 = nn.LayerNorm(data_width, device=device, dtype=dtype)
self.mlp = MLP(device=device, dtype=dtype, width=width, init_scale=init_scale)
self.ln_3 = nn.LayerNorm(width, device=device, dtype=dtype)
def forward(self, x: torch.Tensor, data: torch.Tensor):
x = x + self.attn(self.ln_1(x), self.ln_2(data))
x = x + self.mlp(self.ln_3(x))
return x
class MLP(nn.Module):
def __init__(self, *,
device: Optional[torch.device],
dtype: Optional[torch.dtype],
width: int,
init_scale: float):
super().__init__()
self.width = width
self.c_fc = nn.Linear(width, width * 4, device=device, dtype=dtype)
self.c_proj = nn.Linear(width * 4, width, device=device, dtype=dtype)
self.gelu = nn.GELU()
init_linear(self.c_fc, init_scale)
init_linear(self.c_proj, init_scale)
def forward(self, x):
return self.c_proj(self.gelu(self.c_fc(x)))
class Transformer(nn.Module):
def __init__(
self,
*,
device: Optional[torch.device],
dtype: Optional[torch.dtype],
n_ctx: int,
width: int,
layers: int,
heads: int,
init_scale: float = 0.25,
qkv_bias: bool = True,
flash: bool = False,
use_checkpoint: bool = False
):
super().__init__()
self.n_ctx = n_ctx
self.width = width
self.layers = layers
self.resblocks = nn.ModuleList(
[
ResidualAttentionBlock(
device=device,
dtype=dtype,
n_ctx=n_ctx,
width=width,
heads=heads,
init_scale=init_scale,
qkv_bias=qkv_bias,
flash=flash,
use_checkpoint=use_checkpoint
)
for _ in range(layers)
]
)
def forward(self, x: torch.Tensor):
for block in self.resblocks:
x = block(x)
return x

View File

@ -0,0 +1,308 @@
# -*- coding: utf-8 -*-
import math
import torch
import torch.nn as nn
from typing import Optional
import warnings
from MeshAnything.miche.michelangelo.models.modules.checkpoint import checkpoint
def _trunc_normal_(tensor, mean, std, a, b):
# Cut & paste from PyTorch official master until it's in a few official releases - RW
# Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
def norm_cdf(x):
# Computes standard normal cumulative distribution function
return (1. + math.erf(x / math.sqrt(2.))) / 2.
if (mean < a - 2 * std) or (mean > b + 2 * std):
warnings.warn("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
"The distribution of values may be incorrect.",
stacklevel=2)
# Values are generated by using a truncated uniform distribution and
# then using the inverse CDF for the normal distribution.
# Get upper and lower cdf values
l = norm_cdf((a - mean) / std)
u = norm_cdf((b - mean) / std)
# Uniformly fill tensor with values from [l, u], then translate to
# [2l-1, 2u-1].
tensor.uniform_(2 * l - 1, 2 * u - 1)
# Use inverse cdf transform for normal distribution to get truncated
# standard normal
tensor.erfinv_()
# Transform to proper mean, std
tensor.mul_(std * math.sqrt(2.))
tensor.add_(mean)
# Clamp to ensure it's in the proper range
tensor.clamp_(min=a, max=b)
return tensor
def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.):
# type: (Tensor | nn.Parameter, float, float, float, float) -> Tensor
r"""Fills the input Tensor with values drawn from a truncated
normal distribution. The values are effectively drawn from the
normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)`
with values outside :math:`[a, b]` redrawn until they are within
the bounds. The method used for generating the random values works
best when :math:`a \leq \text{mean} \leq b`.
NOTE: this impl is similar to the PyTorch trunc_normal_, the bounds [a, b] are
applied while sampling the normal with mean/std applied, therefore a, b args
should be adjusted to match the range of mean, std args.
Args:
tensor: an n-dimensional `torch.Tensor`
mean: the mean of the normal distribution
std: the standard deviation of the normal distribution
a: the minimum cutoff value
b: the maximum cutoff value
Examples:
>>> w = torch.empty(3, 5)
>>> nn.init.trunc_normal_(w)
"""
with torch.no_grad():
return _trunc_normal_(tensor, mean, std, a, b)
def init_weights(m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.LayerNorm):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
class MultiheadAttention(nn.Module):
def __init__(
self,
*,
device: torch.device,
dtype: torch.dtype,
n_ctx: int,
width: int,
heads: int,
qkv_bias: bool
):
super().__init__()
self.n_ctx = n_ctx
self.width = width
self.heads = heads
self.c_qkv = nn.Linear(width, width * 3, bias=qkv_bias, device=device, dtype=dtype)
self.c_proj = nn.Linear(width, width, device=device, dtype=dtype)
self.attention = QKVMultiheadAttention(device=device, dtype=dtype, heads=heads, n_ctx=n_ctx)
def forward(self, x):
x = self.c_qkv(x)
x = checkpoint(self.attention, (x,), (), True)
x = self.c_proj(x)
return x
class QKVMultiheadAttention(nn.Module):
def __init__(self, *, device: torch.device, dtype: torch.dtype, heads: int, n_ctx: int):
super().__init__()
self.device = device
self.dtype = dtype
self.heads = heads
self.n_ctx = n_ctx
def forward(self, qkv):
bs, n_ctx, width = qkv.shape
attn_ch = width // self.heads // 3
scale = 1 / math.sqrt(attn_ch)
qkv = qkv.view(bs, n_ctx, self.heads, -1)
q, k, v = torch.split(qkv, attn_ch, dim=-1)
weight = torch.einsum("bthc,bshc->bhts", q, k) * scale
wdtype = weight.dtype
weight = torch.softmax(weight.float(), dim=-1).type(wdtype)
return torch.einsum("bhts,bshc->bthc", weight, v).reshape(bs, n_ctx, -1)
class ResidualAttentionBlock(nn.Module):
def __init__(
self,
*,
device: torch.device,
dtype: torch.dtype,
n_ctx: int,
width: int,
heads: int,
qkv_bias: bool = True,
use_checkpoint: bool = False
):
super().__init__()
self.use_checkpoint = use_checkpoint
self.attn = MultiheadAttention(
device=device,
dtype=dtype,
n_ctx=n_ctx,
width=width,
heads=heads,
qkv_bias=qkv_bias
)
self.ln_1 = nn.LayerNorm(width, device=device, dtype=dtype)
self.mlp = MLP(device=device, dtype=dtype, width=width)
self.ln_2 = nn.LayerNorm(width, device=device, dtype=dtype)
def _forward(self, x: torch.Tensor):
x = x + self.attn(self.ln_1(x))
x = x + self.mlp(self.ln_2(x))
return x
def forward(self, x: torch.Tensor):
return checkpoint(self._forward, (x,), self.parameters(), self.use_checkpoint)
class MultiheadCrossAttention(nn.Module):
def __init__(
self,
*,
device: torch.device,
dtype: torch.dtype,
width: int,
heads: int,
qkv_bias: bool = True,
n_data: Optional[int] = None,
data_width: Optional[int] = None,
):
super().__init__()
self.n_data = n_data
self.width = width
self.heads = heads
self.data_width = width if data_width is None else data_width
self.c_q = nn.Linear(width, width, bias=qkv_bias, device=device, dtype=dtype)
self.c_kv = nn.Linear(self.data_width, width * 2, bias=qkv_bias, device=device, dtype=dtype)
self.c_proj = nn.Linear(width, width, device=device, dtype=dtype)
self.attention = QKVMultiheadCrossAttention(
device=device, dtype=dtype, heads=heads, n_data=n_data
)
def forward(self, x, data):
x = self.c_q(x)
data = self.c_kv(data)
x = checkpoint(self.attention, (x, data), (), True)
x = self.c_proj(x)
return x
class QKVMultiheadCrossAttention(nn.Module):
def __init__(self, *, device: torch.device, dtype: torch.dtype, heads: int, n_data: Optional[int] = None):
super().__init__()
self.device = device
self.dtype = dtype
self.heads = heads
self.n_data = n_data
def forward(self, q, kv):
_, n_ctx, _ = q.shape
bs, n_data, width = kv.shape
attn_ch = width // self.heads // 2
scale = 1 / math.sqrt(attn_ch)
q = q.view(bs, n_ctx, self.heads, -1)
kv = kv.view(bs, n_data, self.heads, -1)
k, v = torch.split(kv, attn_ch, dim=-1)
weight = torch.einsum("bthc,bshc->bhts", q, k) * scale
wdtype = weight.dtype
weight = torch.softmax(weight.float(), dim=-1).type(wdtype)
return torch.einsum("bhts,bshc->bthc", weight, v).reshape(bs, n_ctx, -1)
class ResidualCrossAttentionBlock(nn.Module):
def __init__(
self,
*,
device: Optional[torch.device],
dtype: Optional[torch.dtype],
n_data: Optional[int] = None,
width: int,
heads: int,
data_width: Optional[int] = None,
qkv_bias: bool = True
):
super().__init__()
if data_width is None:
data_width = width
self.attn = MultiheadCrossAttention(
device=device,
dtype=dtype,
n_data=n_data,
width=width,
heads=heads,
data_width=data_width,
qkv_bias=qkv_bias
)
self.ln_1 = nn.LayerNorm(width, device=device, dtype=dtype)
self.ln_2 = nn.LayerNorm(data_width, device=device, dtype=dtype)
self.mlp = MLP(device=device, dtype=dtype, width=width)
self.ln_3 = nn.LayerNorm(width, device=device, dtype=dtype)
def forward(self, x: torch.Tensor, data: torch.Tensor):
x = x + self.attn(self.ln_1(x), self.ln_2(data))
x = x + self.mlp(self.ln_3(x))
return x
class MLP(nn.Module):
def __init__(self, *,
device: Optional[torch.device],
dtype: Optional[torch.dtype],
width: int):
super().__init__()
self.width = width
self.c_fc = nn.Linear(width, width * 4, device=device, dtype=dtype)
self.c_proj = nn.Linear(width * 4, width, device=device, dtype=dtype)
self.gelu = nn.GELU()
def forward(self, x):
return self.c_proj(self.gelu(self.c_fc(x)))
class Transformer(nn.Module):
def __init__(
self,
*,
device: Optional[torch.device],
dtype: Optional[torch.dtype],
n_ctx: int,
width: int,
layers: int,
heads: int,
qkv_bias: bool = True,
use_checkpoint: bool = False
):
super().__init__()
self.n_ctx = n_ctx
self.width = width
self.layers = layers
self.resblocks = nn.ModuleList(
[
ResidualAttentionBlock(
device=device,
dtype=dtype,
n_ctx=n_ctx,
width=width,
heads=heads,
qkv_bias=qkv_bias,
use_checkpoint=use_checkpoint
)
for _ in range(layers)
]
)
self.apply(init_weights)
def forward(self, x: torch.Tensor):
for block in self.resblocks:
x = block(x)
return x

View File

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

View File

@ -0,0 +1,395 @@
# -*- coding: utf-8 -*-
from typing import List, Tuple, Dict, Optional
from omegaconf import DictConfig
import torch
import torch.nn.functional as F
from torch import nn
from torch.optim import lr_scheduler
from typing import Union
from functools import partial
from MeshAnything.miche.michelangelo.utils import instantiate_from_config
from .tsal_base import (
AlignedShapeAsLatentModule,
ShapeAsLatentModule,
Latent2MeshOutput,
AlignedMeshOutput
)
from MeshAnything.miche.michelangelo.models.tsal.inference_utils import extract_geometry
import trimesh
class AlignedShapeAsLatentPLModule(nn.Module):
def __init__(self, *,
shape_module_cfg,
aligned_module_cfg,
loss_cfg,
optimizer_cfg: Optional[DictConfig] = None,
ckpt_path: Optional[str] = None,
ignore_keys: Union[Tuple[str], List[str]] = ()):
super().__init__()
shape_model: ShapeAsLatentModule = instantiate_from_config(
shape_module_cfg, device=None, dtype=None
)
self.model: AlignedShapeAsLatentModule = instantiate_from_config(
aligned_module_cfg, shape_model=shape_model
)
self.loss = instantiate_from_config(loss_cfg)
self.optimizer_cfg = optimizer_cfg
if ckpt_path is not None:
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
def set_shape_model_only(self):
self.model.set_shape_model_only()
@property
def latent_shape(self):
return self.model.shape_model.latent_shape
@property
def zero_rank(self):
if self._trainer:
zero_rank = self.trainer.local_rank == 0
else:
zero_rank = True
return zero_rank
def init_from_ckpt(self, path, ignore_keys=()):
state_dict = torch.load(path, map_location="cpu")["state_dict"]
keys = list(state_dict.keys())
for k in keys:
for ik in ignore_keys:
if k.startswith(ik):
print("Deleting key {} from state_dict.".format(k))
del state_dict[k]
missing, unexpected = self.load_state_dict(state_dict, strict=False)
print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
if len(missing) > 0:
print(f"Missing Keys: {missing}")
print(f"Unexpected Keys: {unexpected}")
def configure_optimizers(self) -> Tuple[List, List]:
lr = self.learning_rate
trainable_parameters = list(self.model.parameters())
if self.optimizer_cfg is None:
optimizers = [torch.optim.AdamW(trainable_parameters, lr=lr, betas=(0.9, 0.99), weight_decay=1e-3)]
schedulers = []
else:
optimizer = instantiate_from_config(self.optimizer_cfg.optimizer, params=trainable_parameters)
scheduler_func = instantiate_from_config(
self.optimizer_cfg.scheduler,
max_decay_steps=self.trainer.max_steps,
lr_max=lr
)
scheduler = {
"scheduler": lr_scheduler.LambdaLR(optimizer, lr_lambda=scheduler_func.schedule),
"interval": "step",
"frequency": 1
}
optimizers = [optimizer]
schedulers = [scheduler]
return optimizers, schedulers
def forward(self,
surface: torch.FloatTensor,
image: torch.FloatTensor,
text: torch.FloatTensor,
volume_queries: torch.FloatTensor):
"""
Args:
surface (torch.FloatTensor):
image (torch.FloatTensor):
text (torch.FloatTensor):
volume_queries (torch.FloatTensor):
Returns:
"""
embed_outputs, shape_z = self.model(surface, image, text)
shape_zq, posterior = self.model.shape_model.encode_kl_embed(shape_z)
latents = self.model.shape_model.decode(shape_zq)
logits = self.model.shape_model.query_geometry(volume_queries, latents)
return embed_outputs, logits, posterior
def encode(self, surface: torch.FloatTensor, sample_posterior=True):
pc = surface[..., 0:3]
feats = surface[..., 3:6]
shape_embed, shape_zq, posterior = self.model.shape_model.encode(
pc=pc, feats=feats, sample_posterior=sample_posterior
)
return shape_zq
def encode_latents(self, surface: torch.FloatTensor):
pc = surface[..., 0:3]
feats = surface[..., 3:6]
shape_embed, shape_latents = self.model.shape_model.encode_latents(
pc=pc, feats=feats
)
shape_embed = shape_embed.unsqueeze(1)
assert shape_embed.shape[1] == 1 and shape_latents.shape[1] == 256
cat_latents = torch.cat([shape_embed, shape_latents], dim=1)
return cat_latents
def recon(self, surface):
cat_latents = self.encode_latents(surface)
shape_latents = cat_latents[:, 1:]
shape_zq, posterior = self.model.shape_model.encode_kl_embed(shape_latents)
# decoding
latents = self.model.shape_model.decode(shape_zq)
geometric_func = partial(self.model.shape_model.query_geometry, latents=latents)
# reconstruction
mesh_v_f, has_surface = extract_geometry(
geometric_func=geometric_func,
device=surface.device,
batch_size=surface.shape[0],
bounds=(-1.25, -1.25, -1.25, 1.25, 1.25, 1.25),
octree_depth=7,
num_chunks=10000,
)
recon_mesh = trimesh.Trimesh(mesh_v_f[0][0], mesh_v_f[0][1])
return recon_mesh
def to_shape_latents(self, latents):
shape_zq, posterior = self.model.shape_model.encode_kl_embed(latents, sample_posterior = False)
return self.model.shape_model.decode(shape_zq)
def decode(self,
z_q,
bounds: Union[Tuple[float], List[float], float] = 1.1,
octree_depth: int = 7,
num_chunks: int = 10000) -> List[Latent2MeshOutput]:
latents = self.model.shape_model.decode(z_q) # latents: [bs, num_latents, dim]
outputs = self.latent2mesh(latents, bounds=bounds, octree_depth=octree_depth, num_chunks=num_chunks)
return outputs
def training_step(self, batch: Dict[str, torch.FloatTensor],
batch_idx: int, optimizer_idx: int = 0) -> torch.FloatTensor:
"""
Args:
batch (dict): the batch sample, and it contains:
- surface (torch.FloatTensor): [bs, n_surface, (3 + input_dim)]
- image (torch.FloatTensor): [bs, 3, 224, 224]
- text (torch.FloatTensor): [bs, num_templates, 77]
- geo_points (torch.FloatTensor): [bs, n_pts, (3 + 1)]
batch_idx (int):
optimizer_idx (int):
Returns:
loss (torch.FloatTensor):
"""
surface = batch["surface"]
image = batch["image"]
text = batch["text"]
volume_queries = batch["geo_points"][..., 0:3]
shape_labels = batch["geo_points"][..., -1]
embed_outputs, shape_logits, posteriors = self(surface, image, text, volume_queries)
aeloss, log_dict_ae = self.loss(
**embed_outputs,
posteriors=posteriors,
shape_logits=shape_logits,
shape_labels=shape_labels,
split="train"
)
self.log_dict(log_dict_ae, prog_bar=True, logger=True, batch_size=shape_logits.shape[0],
sync_dist=False, rank_zero_only=True)
return aeloss
def validation_step(self, batch: Dict[str, torch.FloatTensor], batch_idx: int) -> torch.FloatTensor:
surface = batch["surface"]
image = batch["image"]
text = batch["text"]
volume_queries = batch["geo_points"][..., 0:3]
shape_labels = batch["geo_points"][..., -1]
embed_outputs, shape_logits, posteriors = self(surface, image, text, volume_queries)
aeloss, log_dict_ae = self.loss(
**embed_outputs,
posteriors=posteriors,
shape_logits=shape_logits,
shape_labels=shape_labels,
split="val"
)
self.log_dict(log_dict_ae, prog_bar=True, logger=True, batch_size=shape_logits.shape[0],
sync_dist=False, rank_zero_only=True)
return aeloss
def visual_alignment(self,
surface: torch.FloatTensor,
image: torch.FloatTensor,
text: torch.FloatTensor,
description: Optional[List[str]] = None,
bounds: Union[Tuple[float], List[float]] = (-1.25, -1.25, -1.25, 1.25, 1.25, 1.25),
octree_depth: int = 7,
num_chunks: int = 10000) -> List[AlignedMeshOutput]:
"""
Args:
surface:
image:
text:
description:
bounds:
octree_depth:
num_chunks:
Returns:
mesh_outputs (List[AlignedMeshOutput]): the mesh outputs list.
"""
outputs = []
device = surface.device
bs = surface.shape[0]
embed_outputs, shape_z = self.model(surface, image, text)
# calculate the similarity
image_embed = embed_outputs["image_embed"]
text_embed = embed_outputs["text_embed"]
shape_embed = embed_outputs["shape_embed"]
# normalized features
shape_embed = F.normalize(shape_embed, dim=-1, p=2)
text_embed = F.normalize(text_embed, dim=-1, p=2)
image_embed = F.normalize(image_embed, dim=-1, p=2)
# B x B
shape_text_similarity = (100.0 * shape_embed @ text_embed.T).softmax(dim=-1)
# B x B
shape_image_similarity = (100.0 * shape_embed @ image_embed.T).softmax(dim=-1)
# shape reconstruction
shape_zq, posterior = self.model.shape_model.encode_kl_embed(shape_z)
latents = self.model.shape_model.decode(shape_zq)
geometric_func = partial(self.model.shape_model.query_geometry, latents=latents)
# 2. decode geometry
mesh_v_f, has_surface = extract_geometry(
geometric_func=geometric_func,
device=device,
batch_size=bs,
bounds=bounds,
octree_depth=octree_depth,
num_chunks=num_chunks,
disable=not self.zero_rank
)
# 3. decode texture
for i, ((mesh_v, mesh_f), is_surface) in enumerate(zip(mesh_v_f, has_surface)):
if not is_surface:
outputs.append(None)
continue
out = AlignedMeshOutput()
out.mesh_v = mesh_v
out.mesh_f = mesh_f
out.surface = surface[i].cpu().numpy()
out.image = image[i].cpu().numpy()
if description is not None:
out.text = description[i]
out.shape_text_similarity = shape_text_similarity[i, i]
out.shape_image_similarity = shape_image_similarity[i, i]
outputs.append(out)
return outputs
def latent2mesh(self,
latents: torch.FloatTensor,
bounds: Union[Tuple[float], List[float], float] = 1.1,
octree_depth: int = 7,
num_chunks: int = 10000) -> List[Latent2MeshOutput]:
"""
Args:
latents: [bs, num_latents, dim]
bounds:
octree_depth:
num_chunks:
Returns:
mesh_outputs (List[MeshOutput]): the mesh outputs list.
"""
outputs = []
geometric_func = partial(self.model.shape_model.query_geometry, latents=latents)
# 2. decode geometry
device = latents.device
mesh_v_f, has_surface = extract_geometry(
geometric_func=geometric_func,
device=device,
batch_size=len(latents),
bounds=bounds,
octree_depth=octree_depth,
num_chunks=num_chunks,
disable=not self.zero_rank
)
# 3. decode texture
for i, ((mesh_v, mesh_f), is_surface) in enumerate(zip(mesh_v_f, has_surface)):
if not is_surface:
outputs.append(None)
continue
out = Latent2MeshOutput()
out.mesh_v = mesh_v
out.mesh_f = mesh_f
outputs.append(out)
return outputs

View File

@ -0,0 +1,118 @@
# -*- coding: utf-8 -*-
import torch
from torch import nn
from einops import rearrange
from transformers import CLIPModel
from MeshAnything.miche.michelangelo.models.tsal.tsal_base import AlignedShapeAsLatentModule
class CLIPAlignedShapeAsLatentModule(AlignedShapeAsLatentModule):
def __init__(self, *,
shape_model,
clip_model_version: str = "openai/clip-vit-large-patch14"):
super().__init__()
# self.clip_model: CLIPModel = CLIPModel.from_pretrained(clip_model_version)
# for params in self.clip_model.parameters():
# params.requires_grad = False
self.clip_model = None
self.shape_model = shape_model
self.shape_projection = nn.Parameter(torch.empty(self.shape_model.width, self.shape_model.width))
# nn.init.normal_(self.shape_projection, std=self.shape_model.width ** -0.5)
def set_shape_model_only(self):
self.clip_model = None
def encode_shape_embed(self, surface, return_latents: bool = False):
"""
Args:
surface (torch.FloatTensor): [bs, n, 3 + c]
return_latents (bool):
Returns:
x (torch.FloatTensor): [bs, projection_dim]
shape_latents (torch.FloatTensor): [bs, m, d]
"""
pc = surface[..., 0:3]
feats = surface[..., 3:]
shape_embed, shape_latents = self.shape_model.encode_latents(pc, feats)
x = shape_embed @ self.shape_projection
if return_latents:
return x, shape_latents
else:
return x
def encode_image_embed(self, image):
"""
Args:
image (torch.FloatTensor): [bs, 3, h, w]
Returns:
x (torch.FloatTensor): [bs, projection_dim]
"""
x = self.clip_model.get_image_features(image)
return x
def encode_text_embed(self, text):
x = self.clip_model.get_text_features(text)
return x
def forward(self, surface, image, text):
"""
Args:
surface (torch.FloatTensor):
image (torch.FloatTensor): [bs, 3, 224, 224]
text (torch.LongTensor): [bs, num_templates, 77]
Returns:
embed_outputs (dict): the embedding outputs, and it contains:
- image_embed (torch.FloatTensor):
- text_embed (torch.FloatTensor):
- shape_embed (torch.FloatTensor):
- logit_scale (float):
"""
# # text embedding
# text_embed_all = []
# for i in range(text.shape[0]):
# text_for_one_sample = text[i]
# text_embed = self.encode_text_embed(text_for_one_sample)
# text_embed = text_embed / text_embed.norm(dim=-1, keepdim=True)
# text_embed = text_embed.mean(dim=0)
# text_embed = text_embed / text_embed.norm(dim=-1, keepdim=True)
# text_embed_all.append(text_embed)
# text_embed_all = torch.stack(text_embed_all)
b = text.shape[0]
text_tokens = rearrange(text, "b t l -> (b t) l")
text_embed = self.encode_text_embed(text_tokens)
text_embed = rearrange(text_embed, "(b t) d -> b t d", b=b)
text_embed = text_embed.mean(dim=1)
text_embed = text_embed / text_embed.norm(dim=-1, keepdim=True)
# image embedding
image_embed = self.encode_image_embed(image)
# shape embedding
shape_embed, shape_latents = self.encode_shape_embed(surface, return_latents=True)
embed_outputs = {
"image_embed": image_embed,
"text_embed": text_embed,
"shape_embed": shape_embed,
# "logit_scale": self.clip_model.logit_scale.exp()
}
return embed_outputs, shape_latents

View File

@ -0,0 +1,80 @@
# -*- coding: utf-8 -*-
import torch
from tqdm import tqdm
from einops import repeat
import numpy as np
from typing import Callable, Tuple, List, Union, Optional
from skimage import measure
from MeshAnything.miche.michelangelo.graphics.primitives import generate_dense_grid_points
@torch.no_grad()
def extract_geometry(geometric_func: Callable,
device: torch.device,
batch_size: int = 1,
bounds: Union[Tuple[float], List[float], float] = (-1.25, -1.25, -1.25, 1.25, 1.25, 1.25),
octree_depth: int = 7,
num_chunks: int = 10000,
disable: bool = True):
"""
Args:
geometric_func:
device:
bounds:
octree_depth:
batch_size:
num_chunks:
disable:
Returns:
"""
if isinstance(bounds, float):
bounds = [-bounds, -bounds, -bounds, bounds, bounds, bounds]
bbox_min = np.array(bounds[0:3])
bbox_max = np.array(bounds[3:6])
bbox_size = bbox_max - bbox_min
xyz_samples, grid_size, length = generate_dense_grid_points(
bbox_min=bbox_min,
bbox_max=bbox_max,
octree_depth=octree_depth,
indexing="ij"
)
xyz_samples = torch.FloatTensor(xyz_samples)
batch_logits = []
for start in tqdm(range(0, xyz_samples.shape[0], num_chunks),
desc="Implicit Function:", disable=disable, leave=False):
queries = xyz_samples[start: start + num_chunks, :].to(device)
batch_queries = repeat(queries, "p c -> b p c", b=batch_size)
logits = geometric_func(batch_queries)
batch_logits.append(logits.cpu())
grid_logits = torch.cat(batch_logits, dim=1).view((batch_size, grid_size[0], grid_size[1], grid_size[2])).numpy()
mesh_v_f = []
has_surface = np.zeros((batch_size,), dtype=np.bool_)
for i in range(batch_size):
try:
vertices, faces, normals, _ = measure.marching_cubes(grid_logits[i], 0, method="lewiner")
vertices = vertices / grid_size * bbox_size + bbox_min
# vertices[:, [0, 1]] = vertices[:, [1, 0]]
mesh_v_f.append((vertices.astype(np.float32), np.ascontiguousarray(faces)))
has_surface[i] = True
except ValueError:
mesh_v_f.append((None, None))
has_surface[i] = False
except RuntimeError:
mesh_v_f.append((None, None))
has_surface[i] = False
return mesh_v_f, has_surface

View File

@ -0,0 +1,303 @@
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Optional, Tuple, Dict
from MeshAnything.miche.michelangelo.models.modules.distributions import DiagonalGaussianDistribution
from MeshAnything.miche.michelangelo.utils.eval import compute_psnr
from MeshAnything.miche.michelangelo.utils import misc
class KLNearFar(nn.Module):
def __init__(self,
near_weight: float = 0.1,
kl_weight: float = 1.0,
num_near_samples: Optional[int] = None):
super().__init__()
self.near_weight = near_weight
self.kl_weight = kl_weight
self.num_near_samples = num_near_samples
self.geo_criterion = nn.BCEWithLogitsLoss()
def forward(self,
posteriors: Optional[DiagonalGaussianDistribution],
logits: torch.FloatTensor,
labels: torch.FloatTensor,
split: Optional[str] = "train", **kwargs) -> Tuple[torch.FloatTensor, Dict[str, float]]:
"""
Args:
posteriors (DiagonalGaussianDistribution or torch.distributions.Normal):
logits (torch.FloatTensor): [B, 2*N], logits[:, 0:N] is the volume points; logits[:, N:2N] is the near points;
labels (torch.FloatTensor): [B, 2*N], labels[:, 0:N] is the volume points; labels[:, N:2N] is the near points;
split (str):
**kwargs:
Returns:
loss (torch.Tensor): (,)
log (dict):
"""
if self.num_near_samples is None:
num_vol = logits.shape[1] // 2
else:
num_vol = logits.shape[1] - self.num_near_samples
vol_logits = logits[:, 0:num_vol]
vol_labels = labels[:, 0:num_vol]
near_logits = logits[:, num_vol:]
near_labels = labels[:, num_vol:]
# occupancy loss
# vol_bce = self.geo_criterion(vol_logits, vol_labels)
# near_bce = self.geo_criterion(near_logits, near_labels)
vol_bce = self.geo_criterion(vol_logits.float(), vol_labels.float())
near_bce = self.geo_criterion(near_logits.float(), near_labels.float())
if posteriors is None:
kl_loss = torch.tensor(0.0, dtype=vol_logits.dtype, device=vol_logits.device)
else:
kl_loss = posteriors.kl(dims=(1, 2))
kl_loss = torch.mean(kl_loss)
loss = vol_bce + near_bce * self.near_weight + kl_loss * self.kl_weight
with torch.no_grad():
preds = logits >= 0
accuracy = (preds == labels).float()
accuracy = accuracy.mean()
pos_ratio = torch.mean(labels)
log = {
"{}/total_loss".format(split): loss.clone().detach(),
"{}/near".format(split): near_bce.detach(),
"{}/far".format(split): vol_bce.detach(),
"{}/kl".format(split): kl_loss.detach(),
"{}/accuracy".format(split): accuracy,
"{}/pos_ratio".format(split): pos_ratio
}
if posteriors is not None:
log[f"{split}/mean"] = posteriors.mean.mean().detach()
log[f"{split}/std_mean"] = posteriors.std.mean().detach()
log[f"{split}/std_max"] = posteriors.std.max().detach()
return loss, log
class KLNearFarColor(nn.Module):
def __init__(self,
near_weight: float = 0.1,
kl_weight: float = 1.0,
color_weight: float = 1.0,
color_criterion: str = "mse",
num_near_samples: Optional[int] = None):
super().__init__()
self.color_weight = color_weight
self.near_weight = near_weight
self.kl_weight = kl_weight
self.num_near_samples = num_near_samples
if color_criterion == "mse":
self.color_criterion = nn.MSELoss()
elif color_criterion == "l1":
self.color_criterion = nn.L1Loss()
else:
raise ValueError(f"{color_criterion} must be [`mse`, `l1`].")
self.geo_criterion = nn.BCEWithLogitsLoss()
def forward(self,
posteriors: Optional[DiagonalGaussianDistribution],
logits: torch.FloatTensor,
labels: torch.FloatTensor,
pred_colors: torch.FloatTensor,
gt_colors: torch.FloatTensor,
split: Optional[str] = "train", **kwargs) -> Tuple[torch.FloatTensor, Dict[str, float]]:
"""
Args:
posteriors (DiagonalGaussianDistribution or torch.distributions.Normal):
logits (torch.FloatTensor): [B, 2*N], logits[:, 0:N] is the volume points; logits[:, N:2N] is the near points;
labels (torch.FloatTensor): [B, 2*N], labels[:, 0:N] is the volume points; labels[:, N:2N] is the near points;
pred_colors (torch.FloatTensor): [B, M, 3]
gt_colors (torch.FloatTensor): [B, M, 3]
split (str):
**kwargs:
Returns:
loss (torch.Tensor): (,)
log (dict):
"""
if self.num_near_samples is None:
num_vol = logits.shape[1] // 2
else:
num_vol = logits.shape[1] - self.num_near_samples
vol_logits = logits[:, 0:num_vol]
vol_labels = labels[:, 0:num_vol]
near_logits = logits[:, num_vol:]
near_labels = labels[:, num_vol:]
# occupancy loss
# vol_bce = self.geo_criterion(vol_logits, vol_labels)
# near_bce = self.geo_criterion(near_logits, near_labels)
vol_bce = self.geo_criterion(vol_logits.float(), vol_labels.float())
near_bce = self.geo_criterion(near_logits.float(), near_labels.float())
# surface color loss
color = self.color_criterion(pred_colors, gt_colors)
if posteriors is None:
kl_loss = torch.tensor(0.0, dtype=pred_colors.dtype, device=pred_colors.device)
else:
kl_loss = posteriors.kl(dims=(1, 2))
kl_loss = torch.mean(kl_loss)
loss = vol_bce + near_bce * self.near_weight + color * self.color_weight + kl_loss * self.kl_weight
with torch.no_grad():
preds = logits >= 0
accuracy = (preds == labels).float()
accuracy = accuracy.mean()
psnr = compute_psnr(pred_colors, gt_colors)
log = {
"{}/total_loss".format(split): loss.clone().detach(),
"{}/near".format(split): near_bce.detach(),
"{}/far".format(split): vol_bce.detach(),
"{}/color".format(split): color.detach(),
"{}/kl".format(split): kl_loss.detach(),
"{}/psnr".format(split): psnr.detach(),
"{}/accuracy".format(split): accuracy
}
return loss, log
class ContrastKLNearFar(nn.Module):
def __init__(self,
contrast_weight: float = 1.0,
near_weight: float = 0.1,
kl_weight: float = 1.0,
num_near_samples: Optional[int] = None):
super().__init__()
self.labels = None
self.last_local_batch_size = None
self.contrast_weight = contrast_weight
self.near_weight = near_weight
self.kl_weight = kl_weight
self.num_near_samples = num_near_samples
self.geo_criterion = nn.BCEWithLogitsLoss()
def forward(self,
shape_embed: torch.FloatTensor,
text_embed: torch.FloatTensor,
image_embed: torch.FloatTensor,
logit_scale: torch.FloatTensor,
posteriors: Optional[DiagonalGaussianDistribution],
shape_logits: torch.FloatTensor,
shape_labels: torch.FloatTensor,
split: Optional[str] = "train", **kwargs):
local_batch_size = shape_embed.size(0)
if local_batch_size != self.last_local_batch_size:
self.labels = local_batch_size * misc.get_rank() + torch.arange(
local_batch_size, device=shape_embed.device
).long()
self.last_local_batch_size = local_batch_size
# normalized features
shape_embed = F.normalize(shape_embed, dim=-1, p=2)
text_embed = F.normalize(text_embed, dim=-1, p=2)
image_embed = F.normalize(image_embed, dim=-1, p=2)
# gather features from all GPUs
shape_embed_all, text_embed_all, image_embed_all = misc.all_gather_batch(
[shape_embed, text_embed, image_embed]
)
# cosine similarity as logits
logits_per_shape_text = logit_scale * shape_embed @ text_embed_all.t()
logits_per_text_shape = logit_scale * text_embed @ shape_embed_all.t()
logits_per_shape_image = logit_scale * shape_embed @ image_embed_all.t()
logits_per_image_shape = logit_scale * image_embed @ shape_embed_all.t()
contrast_loss = (F.cross_entropy(logits_per_shape_text, self.labels) +
F.cross_entropy(logits_per_text_shape, self.labels)) / 2 + \
(F.cross_entropy(logits_per_shape_image, self.labels) +
F.cross_entropy(logits_per_image_shape, self.labels)) / 2
# shape reconstruction
if self.num_near_samples is None:
num_vol = shape_logits.shape[1] // 2
else:
num_vol = shape_logits.shape[1] - self.num_near_samples
vol_logits = shape_logits[:, 0:num_vol]
vol_labels = shape_labels[:, 0:num_vol]
near_logits = shape_logits[:, num_vol:]
near_labels = shape_labels[:, num_vol:]
# occupancy loss
vol_bce = self.geo_criterion(vol_logits.float(), vol_labels.float())
near_bce = self.geo_criterion(near_logits.float(), near_labels.float())
if posteriors is None:
kl_loss = torch.tensor(0.0, dtype=vol_logits.dtype, device=vol_logits.device)
else:
kl_loss = posteriors.kl(dims=(1, 2))
kl_loss = torch.mean(kl_loss)
loss = vol_bce + near_bce * self.near_weight + kl_loss * self.kl_weight + contrast_loss * self.contrast_weight
# compute accuracy
with torch.no_grad():
pred = torch.argmax(logits_per_shape_text, dim=-1)
correct = pred.eq(self.labels).sum()
shape_text_acc = 100 * correct / local_batch_size
pred = torch.argmax(logits_per_shape_image, dim=-1)
correct = pred.eq(self.labels).sum()
shape_image_acc = 100 * correct / local_batch_size
preds = shape_logits >= 0
accuracy = (preds == shape_labels).float()
accuracy = accuracy.mean()
log = {
"{}/contrast".format(split): contrast_loss.clone().detach(),
"{}/near".format(split): near_bce.detach(),
"{}/far".format(split): vol_bce.detach(),
"{}/kl".format(split): kl_loss.detach(),
"{}/shape_text_acc".format(split): shape_text_acc,
"{}/shape_image_acc".format(split): shape_image_acc,
"{}/total_loss".format(split): loss.clone().detach(),
"{}/accuracy".format(split): accuracy,
}
if posteriors is not None:
log[f"{split}/mean"] = posteriors.mean.mean().detach()
log[f"{split}/std_mean"] = posteriors.std.mean().detach()
log[f"{split}/std_max"] = posteriors.std.max().detach()
return loss, log

View File

@ -0,0 +1,423 @@
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
from typing import Optional
from einops import repeat
import math
from MeshAnything.miche.michelangelo.models.modules import checkpoint
from MeshAnything.miche.michelangelo.models.modules.embedder import FourierEmbedder
from MeshAnything.miche.michelangelo.models.modules.distributions import DiagonalGaussianDistribution
from MeshAnything.miche.michelangelo.models.modules.transformer_blocks import (
ResidualCrossAttentionBlock,
Transformer
)
from .tsal_base import ShapeAsLatentModule
class CrossAttentionEncoder(nn.Module):
def __init__(self, *,
device: Optional[torch.device],
dtype: Optional[torch.dtype],
num_latents: int,
fourier_embedder: FourierEmbedder,
point_feats: int,
width: int,
heads: int,
layers: int,
init_scale: float = 0.25,
qkv_bias: bool = True,
flash: bool = False,
use_ln_post: bool = False,
use_checkpoint: bool = False):
super().__init__()
self.use_checkpoint = use_checkpoint
self.num_latents = num_latents
self.query = nn.Parameter(torch.randn((num_latents, width), device=device, dtype=dtype) * 0.02)
self.fourier_embedder = fourier_embedder
self.input_proj = nn.Linear(self.fourier_embedder.out_dim + point_feats, width, device=device, dtype=dtype)
self.cross_attn = ResidualCrossAttentionBlock(
device=device,
dtype=dtype,
width=width,
heads=heads,
init_scale=init_scale,
qkv_bias=qkv_bias,
flash=flash,
)
self.self_attn = Transformer(
device=device,
dtype=dtype,
n_ctx=num_latents,
width=width,
layers=layers,
heads=heads,
init_scale=init_scale,
qkv_bias=qkv_bias,
flash=flash,
use_checkpoint=False
)
if use_ln_post:
self.ln_post = nn.LayerNorm(width, dtype=dtype, device=device)
else:
self.ln_post = None
def _forward(self, pc, feats):
"""
Args:
pc (torch.FloatTensor): [B, N, 3]
feats (torch.FloatTensor or None): [B, N, C]
Returns:
"""
bs = pc.shape[0]
data = self.fourier_embedder(pc)
if feats is not None:
data = torch.cat([data, feats], dim=-1)
data = self.input_proj(data)
query = repeat(self.query, "m c -> b m c", b=bs)
latents = self.cross_attn(query, data)
latents = self.self_attn(latents)
if self.ln_post is not None:
latents = self.ln_post(latents)
return latents, pc
def forward(self, pc: torch.FloatTensor, feats: Optional[torch.FloatTensor] = None):
"""
Args:
pc (torch.FloatTensor): [B, N, 3]
feats (torch.FloatTensor or None): [B, N, C]
Returns:
dict
"""
return checkpoint(self._forward, (pc, feats), self.parameters(), self.use_checkpoint)
class CrossAttentionDecoder(nn.Module):
def __init__(self, *,
device: Optional[torch.device],
dtype: Optional[torch.dtype],
num_latents: int,
out_channels: int,
fourier_embedder: FourierEmbedder,
width: int,
heads: int,
init_scale: float = 0.25,
qkv_bias: bool = True,
flash: bool = False,
use_checkpoint: bool = False):
super().__init__()
self.use_checkpoint = use_checkpoint
self.fourier_embedder = fourier_embedder
self.query_proj = nn.Linear(self.fourier_embedder.out_dim, width, device=device, dtype=dtype)
self.cross_attn_decoder = ResidualCrossAttentionBlock(
device=device,
dtype=dtype,
n_data=num_latents,
width=width,
heads=heads,
init_scale=init_scale,
qkv_bias=qkv_bias,
flash=flash
)
self.ln_post = nn.LayerNorm(width, device=device, dtype=dtype)
self.output_proj = nn.Linear(width, out_channels, device=device, dtype=dtype)
def _forward(self, queries: torch.FloatTensor, latents: torch.FloatTensor):
queries = self.query_proj(self.fourier_embedder(queries))
x = self.cross_attn_decoder(queries, latents)
x = self.ln_post(x)
x = self.output_proj(x)
return x
def forward(self, queries: torch.FloatTensor, latents: torch.FloatTensor):
return checkpoint(self._forward, (queries, latents), self.parameters(), self.use_checkpoint)
class ShapeAsLatentPerceiver(ShapeAsLatentModule):
def __init__(self, *,
device: Optional[torch.device],
dtype: Optional[torch.dtype],
num_latents: int,
point_feats: int = 0,
embed_dim: int = 0,
num_freqs: int = 8,
include_pi: bool = True,
width: int,
heads: int,
num_encoder_layers: int,
num_decoder_layers: int,
init_scale: float = 0.25,
qkv_bias: bool = True,
flash: bool = False,
use_ln_post: bool = False,
use_checkpoint: bool = False):
super().__init__()
self.use_checkpoint = use_checkpoint
self.num_latents = num_latents
self.fourier_embedder = FourierEmbedder(num_freqs=num_freqs, include_pi=include_pi)
init_scale = init_scale * math.sqrt(1.0 / width)
self.encoder = CrossAttentionEncoder(
device=device,
dtype=dtype,
fourier_embedder=self.fourier_embedder,
num_latents=num_latents,
point_feats=point_feats,
width=width,
heads=heads,
layers=num_encoder_layers,
init_scale=init_scale,
qkv_bias=qkv_bias,
flash=flash,
use_ln_post=use_ln_post,
use_checkpoint=use_checkpoint
)
self.embed_dim = embed_dim
if embed_dim > 0:
# VAE embed
self.pre_kl = nn.Linear(width, embed_dim * 2, device=device, dtype=dtype)
self.post_kl = nn.Linear(embed_dim, width, device=device, dtype=dtype)
self.latent_shape = (num_latents, embed_dim)
else:
self.latent_shape = (num_latents, width)
self.transformer = Transformer(
device=device,
dtype=dtype,
n_ctx=num_latents,
width=width,
layers=num_decoder_layers,
heads=heads,
init_scale=init_scale,
qkv_bias=qkv_bias,
flash=flash,
use_checkpoint=use_checkpoint
)
# geometry decoder
self.geo_decoder = CrossAttentionDecoder(
device=device,
dtype=dtype,
fourier_embedder=self.fourier_embedder,
out_channels=1,
num_latents=num_latents,
width=width,
heads=heads,
init_scale=init_scale,
qkv_bias=qkv_bias,
flash=flash,
use_checkpoint=use_checkpoint
)
def encode(self,
pc: torch.FloatTensor,
feats: Optional[torch.FloatTensor] = None,
sample_posterior: bool = True):
"""
Args:
pc (torch.FloatTensor): [B, N, 3]
feats (torch.FloatTensor or None): [B, N, C]
sample_posterior (bool):
Returns:
latents (torch.FloatTensor)
center_pos (torch.FloatTensor or None):
posterior (DiagonalGaussianDistribution or None):
"""
latents, center_pos = self.encoder(pc, feats)
posterior = None
if self.embed_dim > 0:
moments = self.pre_kl(latents)
posterior = DiagonalGaussianDistribution(moments, feat_dim=-1)
if sample_posterior:
latents = posterior.sample()
else:
latents = posterior.mode()
return latents, center_pos, posterior
def decode(self, latents: torch.FloatTensor):
latents = self.post_kl(latents)
return self.transformer(latents)
def query_geometry(self, queries: torch.FloatTensor, latents: torch.FloatTensor):
logits = self.geo_decoder(queries, latents).squeeze(-1)
return logits
def forward(self,
pc: torch.FloatTensor,
feats: torch.FloatTensor,
volume_queries: torch.FloatTensor,
sample_posterior: bool = True):
"""
Args:
pc (torch.FloatTensor): [B, N, 3]
feats (torch.FloatTensor or None): [B, N, C]
volume_queries (torch.FloatTensor): [B, P, 3]
sample_posterior (bool):
Returns:
logits (torch.FloatTensor): [B, P]
center_pos (torch.FloatTensor): [B, M, 3]
posterior (DiagonalGaussianDistribution or None).
"""
latents, center_pos, posterior = self.encode(pc, feats, sample_posterior=sample_posterior)
latents = self.decode(latents)
logits = self.query_geometry(volume_queries, latents)
return logits, center_pos, posterior
class AlignedShapeLatentPerceiver(ShapeAsLatentPerceiver):
def __init__(self, *,
device: Optional[torch.device],
dtype: Optional[torch.dtype],
num_latents: int,
point_feats: int = 0,
embed_dim: int = 0,
num_freqs: int = 8,
include_pi: bool = True,
width: int,
heads: int,
num_encoder_layers: int,
num_decoder_layers: int,
init_scale: float = 0.25,
qkv_bias: bool = True,
flash: bool = False,
use_ln_post: bool = False,
use_checkpoint: bool = False):
super().__init__(
device=device,
dtype=dtype,
num_latents=1 + num_latents,
point_feats=point_feats,
embed_dim=embed_dim,
num_freqs=num_freqs,
include_pi=include_pi,
width=width,
heads=heads,
num_encoder_layers=num_encoder_layers,
num_decoder_layers=num_decoder_layers,
init_scale=init_scale,
qkv_bias=qkv_bias,
flash=flash,
use_ln_post=use_ln_post,
use_checkpoint=use_checkpoint
)
self.width = width
def encode(self,
pc: torch.FloatTensor,
feats: Optional[torch.FloatTensor] = None,
sample_posterior: bool = True):
"""
Args:
pc (torch.FloatTensor): [B, N, 3]
feats (torch.FloatTensor or None): [B, N, c]
sample_posterior (bool):
Returns:
shape_embed (torch.FloatTensor)
kl_embed (torch.FloatTensor):
posterior (DiagonalGaussianDistribution or None):
"""
shape_embed, latents = self.encode_latents(pc, feats)
kl_embed, posterior = self.encode_kl_embed(latents, sample_posterior)
return shape_embed, kl_embed, posterior
def encode_latents(self,
pc: torch.FloatTensor,
feats: Optional[torch.FloatTensor] = None):
x, _ = self.encoder(pc, feats)
shape_embed = x[:, 0]
latents = x[:, 1:]
return shape_embed, latents
def encode_kl_embed(self, latents: torch.FloatTensor, sample_posterior: bool = True):
posterior = None
if self.embed_dim > 0:
moments = self.pre_kl(latents)
posterior = DiagonalGaussianDistribution(moments, feat_dim=-1)
if sample_posterior:
kl_embed = posterior.sample()
else:
kl_embed = posterior.mode()
else:
kl_embed = latents
return kl_embed, posterior
def forward(self,
pc: torch.FloatTensor,
feats: torch.FloatTensor,
volume_queries: torch.FloatTensor,
sample_posterior: bool = True):
"""
Args:
pc (torch.FloatTensor): [B, N, 3]
feats (torch.FloatTensor or None): [B, N, C]
volume_queries (torch.FloatTensor): [B, P, 3]
sample_posterior (bool):
Returns:
shape_embed (torch.FloatTensor): [B, projection_dim]
logits (torch.FloatTensor): [B, M]
posterior (DiagonalGaussianDistribution or None).
"""
shape_embed, kl_embed, posterior = self.encode(pc, feats, sample_posterior=sample_posterior)
latents = self.decode(kl_embed)
logits = self.query_geometry(volume_queries, latents)
return shape_embed, logits, posterior

View File

@ -0,0 +1,290 @@
# -*- coding: utf-8 -*-
from typing import List, Tuple, Dict, Optional
from omegaconf import DictConfig
import torch
from torch.optim import lr_scheduler
import pytorch_lightning as pl
from typing import Union
from functools import partial
from MeshAnything.miche.michelangelo.utils import instantiate_from_config
from .inference_utils import extract_geometry
from .tsal_base import (
ShapeAsLatentModule,
Latent2MeshOutput,
Point2MeshOutput
)
class ShapeAsLatentPLModule(pl.LightningModule):
def __init__(self, *,
module_cfg,
loss_cfg,
optimizer_cfg: Optional[DictConfig] = None,
ckpt_path: Optional[str] = None,
ignore_keys: Union[Tuple[str], List[str]] = ()):
super().__init__()
self.sal: ShapeAsLatentModule = instantiate_from_config(module_cfg, device=None, dtype=None)
self.loss = instantiate_from_config(loss_cfg)
self.optimizer_cfg = optimizer_cfg
if ckpt_path is not None:
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
self.save_hyperparameters()
@property
def latent_shape(self):
return self.sal.latent_shape
@property
def zero_rank(self):
if self._trainer:
zero_rank = self.trainer.local_rank == 0
else:
zero_rank = True
return zero_rank
def init_from_ckpt(self, path, ignore_keys=()):
state_dict = torch.load(path, map_location="cpu")["state_dict"]
keys = list(state_dict.keys())
for k in keys:
for ik in ignore_keys:
if k.startswith(ik):
print("Deleting key {} from state_dict.".format(k))
del state_dict[k]
missing, unexpected = self.load_state_dict(state_dict, strict=False)
print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
if len(missing) > 0:
print(f"Missing Keys: {missing}")
print(f"Unexpected Keys: {unexpected}")
def configure_optimizers(self) -> Tuple[List, List]:
lr = self.learning_rate
# optimizers = [torch.optim.AdamW(self.sal.parameters(), lr=lr, betas=(0.9, 0.99), weight_decay=1e-4)]
# optimizers = [torch.optim.AdamW(self.sal.parameters(), lr=lr, betas=(0.9, 0.99), weight_decay=1e-3)]
if self.optimizer_cfg is None:
optimizers = [torch.optim.AdamW(self.sal.parameters(), lr=lr, betas=(0.9, 0.99), weight_decay=1e-3)]
schedulers = []
else:
optimizer = instantiate_from_config(self.optimizer_cfg.optimizer, params=self.sal.parameters())
scheduler_func = instantiate_from_config(
self.optimizer_cfg.scheduler,
max_decay_steps=self.trainer.max_steps,
lr_max=lr
)
scheduler = {
"scheduler": lr_scheduler.LambdaLR(optimizer, lr_lambda=scheduler_func.schedule),
"interval": "step",
"frequency": 1
}
optimizers = [optimizer]
schedulers = [scheduler]
return optimizers, schedulers
def forward(self,
pc: torch.FloatTensor,
feats: torch.FloatTensor,
volume_queries: torch.FloatTensor):
logits, center_pos, posterior = self.sal(pc, feats, volume_queries)
return posterior, logits
def encode(self, surface: torch.FloatTensor, sample_posterior=True):
pc = surface[..., 0:3]
feats = surface[..., 3:6]
latents, center_pos, posterior = self.sal.encode(
pc=pc, feats=feats, sample_posterior=sample_posterior
)
return latents
def decode(self,
z_q,
bounds: Union[Tuple[float], List[float], float] = 1.1,
octree_depth: int = 7,
num_chunks: int = 10000) -> List[Latent2MeshOutput]:
latents = self.sal.decode(z_q) # latents: [bs, num_latents, dim]
outputs = self.latent2mesh(latents, bounds=bounds, octree_depth=octree_depth, num_chunks=num_chunks)
return outputs
def training_step(self, batch: Dict[str, torch.FloatTensor],
batch_idx: int, optimizer_idx: int = 0) -> torch.FloatTensor:
"""
Args:
batch (dict): the batch sample, and it contains:
- surface (torch.FloatTensor): [bs, n_surface, (3 + input_dim)]
- geo_points (torch.FloatTensor): [bs, n_pts, (3 + 1)]
batch_idx (int):
optimizer_idx (int):
Returns:
loss (torch.FloatTensor):
"""
pc = batch["surface"][..., 0:3]
feats = batch["surface"][..., 3:]
volume_queries = batch["geo_points"][..., 0:3]
volume_labels = batch["geo_points"][..., -1]
posterior, logits = self(
pc=pc, feats=feats, volume_queries=volume_queries
)
aeloss, log_dict_ae = self.loss(posterior, logits, volume_labels, split="train")
self.log_dict(log_dict_ae, prog_bar=True, logger=True, batch_size=logits.shape[0],
sync_dist=False, rank_zero_only=True)
return aeloss
def validation_step(self, batch: Dict[str, torch.FloatTensor], batch_idx: int) -> torch.FloatTensor:
pc = batch["surface"][..., 0:3]
feats = batch["surface"][..., 3:]
volume_queries = batch["geo_points"][..., 0:3]
volume_labels = batch["geo_points"][..., -1]
posterior, logits = self(
pc=pc, feats=feats, volume_queries=volume_queries,
)
aeloss, log_dict_ae = self.loss(posterior, logits, volume_labels, split="val")
self.log_dict(log_dict_ae, prog_bar=True, logger=True, batch_size=logits.shape[0],
sync_dist=False, rank_zero_only=True)
return aeloss
def point2mesh(self,
pc: torch.FloatTensor,
feats: torch.FloatTensor,
bounds: Union[Tuple[float], List[float]] = (-1.25, -1.25, -1.25, 1.25, 1.25, 1.25),
octree_depth: int = 7,
num_chunks: int = 10000) -> List[Point2MeshOutput]:
"""
Args:
pc:
feats:
bounds:
octree_depth:
num_chunks:
Returns:
mesh_outputs (List[MeshOutput]): the mesh outputs list.
"""
outputs = []
device = pc.device
bs = pc.shape[0]
# 1. point encoder + latents transformer
latents, center_pos, posterior = self.sal.encode(pc, feats)
latents = self.sal.decode(latents) # latents: [bs, num_latents, dim]
geometric_func = partial(self.sal.query_geometry, latents=latents)
# 2. decode geometry
mesh_v_f, has_surface = extract_geometry(
geometric_func=geometric_func,
device=device,
batch_size=bs,
bounds=bounds,
octree_depth=octree_depth,
num_chunks=num_chunks,
disable=not self.zero_rank
)
# 3. decode texture
for i, ((mesh_v, mesh_f), is_surface) in enumerate(zip(mesh_v_f, has_surface)):
if not is_surface:
outputs.append(None)
continue
out = Point2MeshOutput()
out.mesh_v = mesh_v
out.mesh_f = mesh_f
out.pc = torch.cat([pc[i], feats[i]], dim=-1).cpu().numpy()
if center_pos is not None:
out.center = center_pos[i].cpu().numpy()
outputs.append(out)
return outputs
def latent2mesh(self,
latents: torch.FloatTensor,
bounds: Union[Tuple[float], List[float], float] = 1.1,
octree_depth: int = 7,
num_chunks: int = 10000) -> List[Latent2MeshOutput]:
"""
Args:
latents: [bs, num_latents, dim]
bounds:
octree_depth:
num_chunks:
Returns:
mesh_outputs (List[MeshOutput]): the mesh outputs list.
"""
outputs = []
geometric_func = partial(self.sal.query_geometry, latents=latents)
# 2. decode geometry
device = latents.device
mesh_v_f, has_surface = extract_geometry(
geometric_func=geometric_func,
device=device,
batch_size=len(latents),
bounds=bounds,
octree_depth=octree_depth,
num_chunks=num_chunks,
disable=not self.zero_rank
)
# 3. decode texture
for i, ((mesh_v, mesh_f), is_surface) in enumerate(zip(mesh_v_f, has_surface)):
if not is_surface:
outputs.append(None)
continue
out = Latent2MeshOutput()
out.mesh_v = mesh_v
out.mesh_f = mesh_f
outputs.append(out)
return outputs

View File

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

View File

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

View File

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

View File

@ -0,0 +1,47 @@
# -*- coding: utf-8 -*-
import os
import io
import tarfile
import json
import numpy as np
import numpy.lib.format
def mkdir(path):
os.makedirs(path, exist_ok=True)
return path
def npy_loads(data):
stream = io.BytesIO(data)
return np.lib.format.read_array(stream)
def npz_loads(data):
return np.load(io.BytesIO(data))
def json_loads(data):
return json.loads(data)
def load_json(filepath):
with open(filepath, "r") as f:
data = json.load(f)
return data
def write_json(filepath, data):
with open(filepath, "w") as f:
json.dump(data, f, indent=2)
def extract_tar(tar_path, tar_cache_folder):
with tarfile.open(tar_path, "r") as tar:
tar.extractall(path=tar_cache_folder)
tar_uids = sorted(os.listdir(tar_cache_folder))
print(f"extract tar: {tar_path} to {tar_cache_folder}")
return tar_uids

View File

@ -0,0 +1,83 @@
# -*- coding: utf-8 -*-
import importlib
import torch
import torch.distributed as dist
def get_obj_from_str(string, reload=False):
module, cls = string.rsplit(".", 1)
if reload:
module_imp = importlib.import_module(module)
importlib.reload(module_imp)
return getattr(importlib.import_module(module, package=None), cls)
def get_obj_from_config(config):
if "target" not in config:
raise KeyError("Expected key `target` to instantiate.")
return get_obj_from_str(config["target"])
def instantiate_from_config(config, **kwargs):
if "target" not in config:
raise KeyError("Expected key `target` to instantiate.")
cls = get_obj_from_str(config["target"])
params = config.get("params", dict())
# params.update(kwargs)
# instance = cls(**params)
kwargs.update(params)
instance = cls(**kwargs)
return instance
def is_dist_avail_and_initialized():
if not dist.is_available():
return False
if not dist.is_initialized():
return False
return True
def get_rank():
if not is_dist_avail_and_initialized():
return 0
return dist.get_rank()
def get_world_size():
if not is_dist_avail_and_initialized():
return 1
return dist.get_world_size()
def all_gather_batch(tensors):
"""
Performs all_gather operation on the provided tensors.
"""
# Queue the gathered tensors
world_size = get_world_size()
# There is no need for reduction in the single-proc case
if world_size == 1:
return tensors
tensor_list = []
output_tensor = []
for tensor in tensors:
tensor_all = [torch.ones_like(tensor) for _ in range(world_size)]
dist.all_gather(
tensor_all,
tensor,
async_op=False # performance opt
)
tensor_list.append(tensor_all)
for tensor_all in tensor_list:
output_tensor.append(torch.cat(tensor_all, dim=0))
return output_tensor

View File

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

View File

@ -0,0 +1,43 @@
import numpy as np
import matplotlib.pyplot as plt
# Helper functions
def get_colors(inp, colormap="viridis", normalize=True, vmin=None, vmax=None):
colormap = plt.cm.get_cmap(colormap)
if normalize:
vmin = np.min(inp)
vmax = np.max(inp)
norm = plt.Normalize(vmin, vmax)
return colormap(norm(inp))[:, :3]
def gen_checkers(n_checkers_x, n_checkers_y, width=256, height=256):
# tex dims need to be power of two.
array = np.ones((width, height, 3), dtype='float32')
# width in texels of each checker
checker_w = width / n_checkers_x
checker_h = height / n_checkers_y
for y in range(height):
for x in range(width):
color_key = int(x / checker_w) + int(y / checker_h)
if color_key % 2 == 0:
array[x, y, :] = [1., 0.874, 0.0]
else:
array[x, y, :] = [0., 0., 0.]
return array
def gen_circle(width=256, height=256):
xx, yy = np.mgrid[:width, :height]
circle = (xx - width / 2 + 0.5) ** 2 + (yy - height / 2 + 0.5) ** 2
array = np.ones((width, height, 4), dtype='float32')
array[:, :, 0] = (circle <= width)
array[:, :, 1] = (circle <= width)
array[:, :, 2] = (circle <= width)
array[:, :, 3] = circle <= width
return array

View File

@ -0,0 +1,49 @@
# -*- coding: utf-8 -*-
import io
import base64
import numpy as np
from PIL import Image
def to_html_frame(content):
html_frame = f"""
<html>
<body>
{content}
</body>
</html>
"""
return html_frame
def to_single_row_table(caption: str, content: str):
table_html = f"""
<table border = "1">
<caption>{caption}</caption>
<tr>
<td>{content}</td>
</tr>
</table>
"""
return table_html
def to_image_embed_tag(image: np.ndarray):
# Convert np.ndarray to bytes
img = Image.fromarray(image)
raw_bytes = io.BytesIO()
img.save(raw_bytes, "PNG")
# Encode bytes to base64
image_base64 = base64.b64encode(raw_bytes.getvalue()).decode("utf-8")
image_tag = f"""
<img src="data:image/png;base64,{image_base64}" alt="Embedded Image">
"""
return image_tag

View File

@ -0,0 +1,534 @@
import numpy as np
from ipywidgets import embed
import pythreejs as p3s
import uuid
from .color_util import get_colors, gen_circle, gen_checkers
EMBED_URL = "https://cdn.jsdelivr.net/npm/@jupyter-widgets/html-manager@1.0.1/dist/embed-amd.js"
class PyThreeJSViewer(object):
def __init__(self, settings, render_mode="WEBSITE"):
self.render_mode = render_mode
self.__update_settings(settings)
self._light = p3s.DirectionalLight(color='white', position=[0, 0, 1], intensity=0.6)
self._light2 = p3s.AmbientLight(intensity=0.5)
self._cam = p3s.PerspectiveCamera(position=[0, 0, 1], lookAt=[0, 0, 0], fov=self.__s["fov"],
aspect=self.__s["width"] / self.__s["height"], children=[self._light])
self._orbit = p3s.OrbitControls(controlling=self._cam)
self._scene = p3s.Scene(children=[self._cam, self._light2], background=self.__s["background"]) # "#4c4c80"
self._renderer = p3s.Renderer(camera=self._cam, scene=self._scene, controls=[self._orbit],
width=self.__s["width"], height=self.__s["height"],
antialias=self.__s["antialias"])
self.__objects = {}
self.__cnt = 0
def jupyter_mode(self):
self.render_mode = "JUPYTER"
def offline(self):
self.render_mode = "OFFLINE"
def website(self):
self.render_mode = "WEBSITE"
def __get_shading(self, shading):
shad = {"flat": True, "wireframe": False, "wire_width": 0.03, "wire_color": "black",
"side": 'DoubleSide', "colormap": "viridis", "normalize": [None, None],
"bbox": False, "roughness": 0.5, "metalness": 0.25, "reflectivity": 1.0,
"line_width": 1.0, "line_color": "black",
"point_color": "red", "point_size": 0.01, "point_shape": "circle",
"text_color": "red"
}
for k in shading:
shad[k] = shading[k]
return shad
def __update_settings(self, settings={}):
sett = {"width": 600, "height": 600, "antialias": True, "scale": 1.5, "background": "#ffffff",
"fov": 30}
for k in settings:
sett[k] = settings[k]
self.__s = sett
def __add_object(self, obj, parent=None):
if not parent: # Object is added to global scene and objects dict
self.__objects[self.__cnt] = obj
self.__cnt += 1
self._scene.add(obj["mesh"])
else: # Object is added to parent object and NOT to objects dict
parent.add(obj["mesh"])
self.__update_view()
if self.render_mode == "JUPYTER":
return self.__cnt - 1
elif self.render_mode == "WEBSITE":
return self
def __add_line_geometry(self, lines, shading, obj=None):
lines = lines.astype("float32", copy=False)
mi = np.min(lines, axis=0)
ma = np.max(lines, axis=0)
geometry = p3s.LineSegmentsGeometry(positions=lines.reshape((-1, 2, 3)))
material = p3s.LineMaterial(linewidth=shading["line_width"], color=shading["line_color"])
# , vertexColors='VertexColors'),
lines = p3s.LineSegments2(geometry=geometry, material=material) # type='LinePieces')
line_obj = {"geometry": geometry, "mesh": lines, "material": material,
"max": ma, "min": mi, "type": "Lines", "wireframe": None}
if obj:
return self.__add_object(line_obj, obj), line_obj
else:
return self.__add_object(line_obj)
def __update_view(self):
if len(self.__objects) == 0:
return
ma = np.zeros((len(self.__objects), 3))
mi = np.zeros((len(self.__objects), 3))
for r, obj in enumerate(self.__objects):
ma[r] = self.__objects[obj]["max"]
mi[r] = self.__objects[obj]["min"]
ma = np.max(ma, axis=0)
mi = np.min(mi, axis=0)
diag = np.linalg.norm(ma - mi)
mean = ((ma - mi) / 2 + mi).tolist()
scale = self.__s["scale"] * (diag)
self._orbit.target = mean
self._cam.lookAt(mean)
self._cam.position = [mean[0], mean[1], mean[2] + scale]
self._light.position = [mean[0], mean[1], mean[2] + scale]
self._orbit.exec_three_obj_method('update')
self._cam.exec_three_obj_method('updateProjectionMatrix')
def __get_bbox(self, v):
m = np.min(v, axis=0)
M = np.max(v, axis=0)
# Corners of the bounding box
v_box = np.array([[m[0], m[1], m[2]], [M[0], m[1], m[2]], [M[0], M[1], m[2]], [m[0], M[1], m[2]],
[m[0], m[1], M[2]], [M[0], m[1], M[2]], [M[0], M[1], M[2]], [m[0], M[1], M[2]]])
f_box = np.array([[0, 1], [1, 2], [2, 3], [3, 0], [4, 5], [5, 6], [6, 7], [7, 4],
[0, 4], [1, 5], [2, 6], [7, 3]], dtype=np.uint32)
return v_box, f_box
def __get_colors(self, v, f, c, sh):
coloring = "VertexColors"
if type(c) == np.ndarray and c.size == 3: # Single color
colors = np.ones_like(v)
colors[:, 0] = c[0]
colors[:, 1] = c[1]
colors[:, 2] = c[2]
# print("Single colors")
elif type(c) == np.ndarray and len(c.shape) == 2 and c.shape[1] == 3: # Color values for
if c.shape[0] == f.shape[0]: # faces
colors = np.hstack([c, c, c]).reshape((-1, 3))
coloring = "FaceColors"
# print("Face color values")
elif c.shape[0] == v.shape[0]: # vertices
colors = c
# print("Vertex color values")
else: # Wrong size, fallback
print("Invalid color array given! Supported are numpy arrays.", type(c))
colors = np.ones_like(v)
colors[:, 0] = 1.0
colors[:, 1] = 0.874
colors[:, 2] = 0.0
elif type(c) == np.ndarray and c.size == f.shape[0]: # Function values for faces
normalize = sh["normalize"][0] != None and sh["normalize"][1] != None
cc = get_colors(c, sh["colormap"], normalize=normalize,
vmin=sh["normalize"][0], vmax=sh["normalize"][1])
# print(cc.shape)
colors = np.hstack([cc, cc, cc]).reshape((-1, 3))
coloring = "FaceColors"
# print("Face function values")
elif type(c) == np.ndarray and c.size == v.shape[0]: # Function values for vertices
normalize = sh["normalize"][0] != None and sh["normalize"][1] != None
colors = get_colors(c, sh["colormap"], normalize=normalize,
vmin=sh["normalize"][0], vmax=sh["normalize"][1])
# print("Vertex function values")
else:
colors = np.ones_like(v)
colors[:, 0] = 1.0
colors[:, 1] = 0.874
colors[:, 2] = 0.0
# No color
if c is not None:
print("Invalid color array given! Supported are numpy arrays.", type(c))
return colors, coloring
def __get_point_colors(self, v, c, sh):
v_color = True
if c is None: # No color given, use global color
# conv = mpl.colors.ColorConverter()
colors = sh["point_color"] # np.array(conv.to_rgb(sh["point_color"]))
v_color = False
elif isinstance(c, str): # No color given, use global color
# conv = mpl.colors.ColorConverter()
colors = c # np.array(conv.to_rgb(c))
v_color = False
elif type(c) == np.ndarray and len(c.shape) == 2 and c.shape[0] == v.shape[0] and c.shape[1] == 3:
# Point color
colors = c.astype("float32", copy=False)
elif isinstance(c, np.ndarray) and len(c.shape) == 2 and c.shape[0] == v.shape[0] and c.shape[1] != 3:
# Function values for vertices, but the colors are features
c_norm = np.linalg.norm(c, ord=2, axis=-1)
normalize = sh["normalize"][0] != None and sh["normalize"][1] != None
colors = get_colors(c_norm, sh["colormap"], normalize=normalize,
vmin=sh["normalize"][0], vmax=sh["normalize"][1])
colors = colors.astype("float32", copy=False)
elif type(c) == np.ndarray and c.size == v.shape[0]: # Function color
normalize = sh["normalize"][0] != None and sh["normalize"][1] != None
colors = get_colors(c, sh["colormap"], normalize=normalize,
vmin=sh["normalize"][0], vmax=sh["normalize"][1])
colors = colors.astype("float32", copy=False)
# print("Vertex function values")
else:
print("Invalid color array given! Supported are numpy arrays.", type(c))
colors = sh["point_color"]
v_color = False
return colors, v_color
def add_mesh(self, v, f, c=None, uv=None, n=None, shading={}, texture_data=None, **kwargs):
shading.update(kwargs)
sh = self.__get_shading(shading)
mesh_obj = {}
# it is a tet
if v.shape[1] == 3 and f.shape[1] == 4:
f_tmp = np.ndarray([f.shape[0] * 4, 3], dtype=f.dtype)
for i in range(f.shape[0]):
f_tmp[i * 4 + 0] = np.array([f[i][1], f[i][0], f[i][2]])
f_tmp[i * 4 + 1] = np.array([f[i][0], f[i][1], f[i][3]])
f_tmp[i * 4 + 2] = np.array([f[i][1], f[i][2], f[i][3]])
f_tmp[i * 4 + 3] = np.array([f[i][2], f[i][0], f[i][3]])
f = f_tmp
if v.shape[1] == 2:
v = np.append(v, np.zeros([v.shape[0], 1]), 1)
# Type adjustment vertices
v = v.astype("float32", copy=False)
# Color setup
colors, coloring = self.__get_colors(v, f, c, sh)
# Type adjustment faces and colors
c = colors.astype("float32", copy=False)
# Material and geometry setup
ba_dict = {"color": p3s.BufferAttribute(c)}
if coloring == "FaceColors":
verts = np.zeros((f.shape[0] * 3, 3), dtype="float32")
for ii in range(f.shape[0]):
# print(ii*3, f[ii])
verts[ii * 3] = v[f[ii, 0]]
verts[ii * 3 + 1] = v[f[ii, 1]]
verts[ii * 3 + 2] = v[f[ii, 2]]
v = verts
else:
f = f.astype("uint32", copy=False).ravel()
ba_dict["index"] = p3s.BufferAttribute(f, normalized=False)
ba_dict["position"] = p3s.BufferAttribute(v, normalized=False)
if uv is not None:
uv = (uv - np.min(uv)) / (np.max(uv) - np.min(uv))
if texture_data is None:
texture_data = gen_checkers(20, 20)
tex = p3s.DataTexture(data=texture_data, format="RGBFormat", type="FloatType")
material = p3s.MeshStandardMaterial(map=tex, reflectivity=sh["reflectivity"], side=sh["side"],
roughness=sh["roughness"], metalness=sh["metalness"],
flatShading=sh["flat"],
polygonOffset=True, polygonOffsetFactor=1, polygonOffsetUnits=5)
ba_dict["uv"] = p3s.BufferAttribute(uv.astype("float32", copy=False))
else:
material = p3s.MeshStandardMaterial(vertexColors=coloring, reflectivity=sh["reflectivity"],
side=sh["side"], roughness=sh["roughness"], metalness=sh["metalness"],
flatShading=sh["flat"],
polygonOffset=True, polygonOffsetFactor=1, polygonOffsetUnits=5)
if type(n) != type(None) and coloring == "VertexColors": # TODO: properly handle normals for FaceColors as well
ba_dict["normal"] = p3s.BufferAttribute(n.astype("float32", copy=False), normalized=True)
geometry = p3s.BufferGeometry(attributes=ba_dict)
if coloring == "VertexColors" and type(n) == type(None):
geometry.exec_three_obj_method('computeVertexNormals')
elif coloring == "FaceColors" and type(n) == type(None):
geometry.exec_three_obj_method('computeFaceNormals')
# Mesh setup
mesh = p3s.Mesh(geometry=geometry, material=material)
# Wireframe setup
mesh_obj["wireframe"] = None
if sh["wireframe"]:
wf_geometry = p3s.WireframeGeometry(mesh.geometry) # WireframeGeometry
wf_material = p3s.LineBasicMaterial(color=sh["wire_color"], linewidth=sh["wire_width"])
wireframe = p3s.LineSegments(wf_geometry, wf_material)
mesh.add(wireframe)
mesh_obj["wireframe"] = wireframe
# Bounding box setup
if sh["bbox"]:
v_box, f_box = self.__get_bbox(v)
_, bbox = self.add_edges(v_box, f_box, sh, mesh)
mesh_obj["bbox"] = [bbox, v_box, f_box]
# Object setup
mesh_obj["max"] = np.max(v, axis=0)
mesh_obj["min"] = np.min(v, axis=0)
mesh_obj["geometry"] = geometry
mesh_obj["mesh"] = mesh
mesh_obj["material"] = material
mesh_obj["type"] = "Mesh"
mesh_obj["shading"] = sh
mesh_obj["coloring"] = coloring
mesh_obj["arrays"] = [v, f, c] # TODO replays with proper storage or remove if not needed
return self.__add_object(mesh_obj)
def add_lines(self, beginning, ending, shading={}, obj=None, **kwargs):
shading.update(kwargs)
if len(beginning.shape) == 1:
if len(beginning) == 2:
beginning = np.array([[beginning[0], beginning[1], 0]])
else:
if beginning.shape[1] == 2:
beginning = np.append(
beginning, np.zeros([beginning.shape[0], 1]), 1)
if len(ending.shape) == 1:
if len(ending) == 2:
ending = np.array([[ending[0], ending[1], 0]])
else:
if ending.shape[1] == 2:
ending = np.append(
ending, np.zeros([ending.shape[0], 1]), 1)
sh = self.__get_shading(shading)
lines = np.hstack([beginning, ending])
lines = lines.reshape((-1, 3))
return self.__add_line_geometry(lines, sh, obj)
def add_edges(self, vertices, edges, shading={}, obj=None, **kwargs):
shading.update(kwargs)
if vertices.shape[1] == 2:
vertices = np.append(
vertices, np.zeros([vertices.shape[0], 1]), 1)
sh = self.__get_shading(shading)
lines = np.zeros((edges.size, 3))
cnt = 0
for e in edges:
lines[cnt, :] = vertices[e[0]]
lines[cnt + 1, :] = vertices[e[1]]
cnt += 2
return self.__add_line_geometry(lines, sh, obj)
def add_points(self, points, c=None, shading={}, obj=None, **kwargs):
shading.update(kwargs)
if len(points.shape) == 1:
if len(points) == 2:
points = np.array([[points[0], points[1], 0]])
else:
if points.shape[1] == 2:
points = np.append(
points, np.zeros([points.shape[0], 1]), 1)
sh = self.__get_shading(shading)
points = points.astype("float32", copy=False)
mi = np.min(points, axis=0)
ma = np.max(points, axis=0)
g_attributes = {"position": p3s.BufferAttribute(points, normalized=False)}
m_attributes = {"size": sh["point_size"]}
if sh["point_shape"] == "circle": # Plot circles
tex = p3s.DataTexture(data=gen_circle(16, 16), format="RGBAFormat", type="FloatType")
m_attributes["map"] = tex
m_attributes["alphaTest"] = 0.5
m_attributes["transparency"] = True
else: # Plot squares
pass
colors, v_colors = self.__get_point_colors(points, c, sh)
if v_colors: # Colors per point
m_attributes["vertexColors"] = 'VertexColors'
g_attributes["color"] = p3s.BufferAttribute(colors, normalized=False)
else: # Colors for all points
m_attributes["color"] = colors
material = p3s.PointsMaterial(**m_attributes)
geometry = p3s.BufferGeometry(attributes=g_attributes)
points = p3s.Points(geometry=geometry, material=material)
point_obj = {"geometry": geometry, "mesh": points, "material": material,
"max": ma, "min": mi, "type": "Points", "wireframe": None}
if obj:
return self.__add_object(point_obj, obj), point_obj
else:
return self.__add_object(point_obj)
def remove_object(self, obj_id):
if obj_id not in self.__objects:
print("Invalid object id. Valid ids are: ", list(self.__objects.keys()))
return
self._scene.remove(self.__objects[obj_id]["mesh"])
del self.__objects[obj_id]
self.__update_view()
def reset(self):
for obj_id in list(self.__objects.keys()).copy():
self._scene.remove(self.__objects[obj_id]["mesh"])
del self.__objects[obj_id]
self.__update_view()
def update_object(self, oid=0, vertices=None, colors=None, faces=None):
obj = self.__objects[oid]
if type(vertices) != type(None):
if obj["coloring"] == "FaceColors":
f = obj["arrays"][1]
verts = np.zeros((f.shape[0] * 3, 3), dtype="float32")
for ii in range(f.shape[0]):
# print(ii*3, f[ii])
verts[ii * 3] = vertices[f[ii, 0]]
verts[ii * 3 + 1] = vertices[f[ii, 1]]
verts[ii * 3 + 2] = vertices[f[ii, 2]]
v = verts
else:
v = vertices.astype("float32", copy=False)
obj["geometry"].attributes["position"].array = v
# self.wireframe.attributes["position"].array = v # Wireframe updates?
obj["geometry"].attributes["position"].needsUpdate = True
# obj["geometry"].exec_three_obj_method('computeVertexNormals')
if type(colors) != type(None):
colors, coloring = self.__get_colors(obj["arrays"][0], obj["arrays"][1], colors, obj["shading"])
colors = colors.astype("float32", copy=False)
obj["geometry"].attributes["color"].array = colors
obj["geometry"].attributes["color"].needsUpdate = True
if type(faces) != type(None):
if obj["coloring"] == "FaceColors":
print("Face updates are currently only possible in vertex color mode.")
return
f = faces.astype("uint32", copy=False).ravel()
print(obj["geometry"].attributes)
obj["geometry"].attributes["index"].array = f
# self.wireframe.attributes["position"].array = v # Wireframe updates?
obj["geometry"].attributes["index"].needsUpdate = True
# obj["geometry"].exec_three_obj_method('computeVertexNormals')
# self.mesh.geometry.verticesNeedUpdate = True
# self.mesh.geometry.elementsNeedUpdate = True
# self.update()
if self.render_mode == "WEBSITE":
return self
# def update(self):
# self.mesh.exec_three_obj_method('update')
# self.orbit.exec_three_obj_method('update')
# self.cam.exec_three_obj_method('updateProjectionMatrix')
# self.scene.exec_three_obj_method('update')
def add_text(self, text, shading={}, **kwargs):
shading.update(kwargs)
sh = self.__get_shading(shading)
tt = p3s.TextTexture(string=text, color=sh["text_color"])
sm = p3s.SpriteMaterial(map=tt)
text = p3s.Sprite(material=sm, scaleToTexture=True)
self._scene.add(text)
# def add_widget(self, widget, callback):
# self.widgets.append(widget)
# widget.observe(callback, names='value')
# def add_dropdown(self, options, default, desc, cb):
# widget = widgets.Dropdown(options=options, value=default, description=desc)
# self.__widgets.append(widget)
# widget.observe(cb, names="value")
# display(widget)
# def add_button(self, text, cb):
# button = widgets.Button(description=text)
# self.__widgets.append(button)
# button.on_click(cb)
# display(button)
def to_html(self, imports=True, html_frame=True):
# Bake positions (fixes centering bug in offline rendering)
if len(self.__objects) == 0:
return
ma = np.zeros((len(self.__objects), 3))
mi = np.zeros((len(self.__objects), 3))
for r, obj in enumerate(self.__objects):
ma[r] = self.__objects[obj]["max"]
mi[r] = self.__objects[obj]["min"]
ma = np.max(ma, axis=0)
mi = np.min(mi, axis=0)
diag = np.linalg.norm(ma - mi)
mean = (ma - mi) / 2 + mi
for r, obj in enumerate(self.__objects):
v = self.__objects[obj]["geometry"].attributes["position"].array
v -= mean
v += np.array([0.0, .9, 0.0]) #! to move the obj to the center of window
scale = self.__s["scale"] * (diag)
self._orbit.target = [0.0, 0.0, 0.0]
self._cam.lookAt([0.0, 0.0, 0.0])
# self._cam.position = [0.0, 0.0, scale]
self._cam.position = [0.0, 0.5, scale * 1.3] #! show four complete meshes in the window
self._light.position = [0.0, 0.0, scale]
state = embed.dependency_state(self._renderer)
# Somehow these entries are missing when the state is exported in python.
# Exporting from the GUI works, so we are inserting the missing entries.
for k in state:
if state[k]["model_name"] == "OrbitControlsModel":
state[k]["state"]["maxAzimuthAngle"] = "inf"
state[k]["state"]["maxDistance"] = "inf"
state[k]["state"]["maxZoom"] = "inf"
state[k]["state"]["minAzimuthAngle"] = "-inf"
tpl = embed.load_requirejs_template
if not imports:
embed.load_requirejs_template = ""
s = embed.embed_snippet(self._renderer, state=state, embed_url=EMBED_URL)
# s = embed.embed_snippet(self.__w, state=state)
embed.load_requirejs_template = tpl
if html_frame:
s = "<html>\n<body>\n" + s + "\n</body>\n</html>"
# Revert changes
for r, obj in enumerate(self.__objects):
v = self.__objects[obj]["geometry"].attributes["position"].array
v += mean
self.__update_view()
return s
def save(self, filename=""):
if filename == "":
uid = str(uuid.uuid4()) + ".html"
else:
filename = filename.replace(".html", "")
uid = filename + '.html'
with open(uid, "w") as f:
f.write(self.to_html())
print("Plot saved to file %s." % uid)

View File

@ -0,0 +1,46 @@
model:
target: MeshAnything.miche.michelangelo.models.tsal.asl_pl_module.AlignedShapeAsLatentPLModule
params:
shape_module_cfg:
target: MeshAnything.miche.michelangelo.models.tsal.sal_perceiver.AlignedShapeLatentPerceiver
params:
num_latents: 256
embed_dim: 64
point_feats: 3 # normal
num_freqs: 8
include_pi: false
heads: 12
width: 768
num_encoder_layers: 8
num_decoder_layers: 16
use_ln_post: true
init_scale: 0.25
qkv_bias: false
use_checkpoint: true
aligned_module_cfg:
target: MeshAnything.miche.michelangelo.models.tsal.clip_asl_module.CLIPAlignedShapeAsLatentModule
params:
clip_model_version: "./checkpoints/clip/clip-vit-large-patch14"
loss_cfg:
target: MeshAnything.miche.michelangelo.models.tsal.loss.ContrastKLNearFar
params:
contrast_weight: 0.1
near_weight: 0.1
kl_weight: 0.001
optimizer_cfg:
optimizer:
target: torch.optim.AdamW
params:
betas: [0.9, 0.99]
eps: 1.e-6
weight_decay: 1.e-2
scheduler:
target: MeshAnything.miche.michelangelo.utils.trainings.lr_scheduler.LambdaWarmUpCosineFactorScheduler
params:
warm_up_steps: 5000
f_start: 1.e-6
f_min: 1.e-3
f_max: 1.0

View File

@ -0,0 +1,223 @@
import torch
from torch import nn, Tensor
from transformers import AutoModelForCausalLM, AutoConfig, AutoModel
from MeshAnything.miche.encode import load_model
from MeshAnything.models.shape_opt import ShapeOPTConfig
from einops.layers.torch import Rearrange
from einops import rearrange, repeat, reduce, pack, unpack
import torch.nn.functional as F
class NoiseResistantDecoder(nn.Module):
def __init__(self, args):
super().__init__()
self.args = args
self.pad_id = -1
self.num_quantizers = 3
self.discrete_num = 128
self.codebook_size = args.codebook_size
self.codebook_dim = args.codebook_dim
config = AutoConfig.from_pretrained("bert-base-uncased")
config.num_hidden_layers = 6
self.decoder= AutoModel.from_config(config=config).to_bettertransformer().encoder
self.n_embd = self.decoder.config.hidden_size
self.pos_embedding = nn.Embedding(18000, self.n_embd)
self.layernorm = nn.LayerNorm(self.n_embd)
self.point_layernorm = nn.LayerNorm(self.n_embd)
self.cond_length = 257
self.cond_dim = 768
self.point_pe = nn.Embedding(self.cond_length, self.n_embd)
self.cond_proj = nn.Linear(self.cond_dim, self.n_embd)
self.cond_head_proj = nn.Linear(self.cond_dim, self.n_embd)
self.project_down_codebook = nn.Linear(self.codebook_dim * 3, self.n_embd)
self.to_coor_logits = nn.Sequential(
nn.Linear(self.n_embd, self.discrete_num * 9),
Rearrange('... (v c) -> ... v c', v = 9)
)
def process_point_feature(self, encode_feature):
point_feature = torch.zeros(encode_feature.shape[0], self.cond_length, self.n_embd, device=self.cond_head_proj.weight.device, dtype=self.cond_head_proj.weight.dtype)
point_feature[:, 0] = self.cond_head_proj(encode_feature[:, 0])
point_feature[:, 1:] = self.cond_proj(encode_feature[:, 1:])
point_feature = self.point_layernorm(point_feature + self.point_pe.weight[None, :point_feature.shape[1]])
return point_feature
def forward(self, input_ids, input_embeds, point_feature = None):
input_ids = input_ids.reshape(input_ids.shape[0], -1)
point_feature = self.process_point_feature(point_feature)
face_embeds = rearrange(input_embeds, 'b (nf nv) d -> b nf (nv d)', nv = 3)
face_embeds = self.project_down_codebook(face_embeds)
face_mask = reduce(input_ids != self.pad_id, 'b (nf nv q) -> b nf', 'all', nv = 3, q = self.num_quantizers)
face_embeds[~face_mask] = 0
face_embeds = self.layernorm(face_embeds + self.pos_embedding.weight[None, :face_embeds.shape[1]])
outputs = self.decoder(
hidden_states=torch.concatenate([point_feature, face_embeds], dim=1),
)
decoded = outputs.last_hidden_state[:, self.cond_length:] # batch x nfaces x dim
decoded = decoded.masked_fill(~face_mask.unsqueeze(-1), 0.)
# batch x nfaces x 9 -> batch x nfaces x 3 x 3
pred_face_logits = self.to_coor_logits(decoded) # batch x nfaces x 9 x ndiscrete
pred_face_coords = rearrange(pred_face_logits.argmax(dim = -1), '... (v c) -> ... v c', v = 3)
continuous_coors = undiscretize(
pred_face_coords,
num_discrete = self.discrete_num,
low = -0.5,
high = 0.5
)
continuous_coors = continuous_coors.masked_fill(~rearrange(face_mask, 'b nf -> b nf 1 1'), float('nan'))
return continuous_coors
class MeshAnything(nn.Module):
def __init__(self, args):
super().__init__()
self.args = args
self.point_encoder = load_model(ckpt_path=None)
self.tokenizer = NoiseResistantDecoder(args)
self.num_quantizers = 3
self.face_per_token = self.num_quantizers * 3
self.cond_length = 257
self.cond_dim = 768
self.max_length = args.n_max_triangles * self.face_per_token + 2 + self.cond_length
self.config = ShapeOPTConfig.from_pretrained(
args.llm,
n_positions=18259,
max_position_embeddings=18259,
vocab_size=self.tokenizer.codebook_size + 3,
_attn_implementation="flash_attention_2"
)
self.bos_token_id = 0
self.eos_token_id = 1
self.pad_token_id = 2
self.config.bos_token_id = self.bos_token_id
self.config.eos_token_id = self.eos_token_id
self.config.pad_token_id = self.pad_token_id
self.config.quantize_codebook_dim = self.tokenizer.codebook_dim
self.config.face_per_token = self.face_per_token
self.config._attn_implementation="flash_attention_2"
self.config.cond_length = self.cond_length
if self.config.word_embed_proj_dim != self.config.hidden_size:
self.config.word_embed_proj_dim = self.config.hidden_size
self.transformer = AutoModelForCausalLM.from_config(
config=self.config, use_flash_attention_2 = True
)
self.transformer.to_bettertransformer()
self.transformer.model.decoder.quantize_codebooks = nn.Parameter(torch.zeros(1, self.tokenizer.codebook_size, self.tokenizer.codebook_dim))
self.cond_head_proj = nn.Linear(self.cond_dim, self.config.word_embed_proj_dim)
self.cond_proj = nn.Linear(self.cond_dim * 2, self.config.word_embed_proj_dim)
self.eval()
def process_point_feature(self, point_feature):
encode_feature = torch.zeros(point_feature.shape[0], self.cond_length, self.config.word_embed_proj_dim,
device=self.cond_head_proj.weight.device, dtype=self.cond_head_proj.weight.dtype)
encode_feature[:, 0] = self.cond_head_proj(point_feature[:, 0])
shape_latents = self.point_encoder.to_shape_latents(point_feature[:, 1:])
encode_feature[:, 1:] = self.cond_proj(torch.cat([point_feature[:, 1:], shape_latents], dim=-1))
return encode_feature
@torch.no_grad()
def forward(self, pc_normal, sampling=False) -> dict:
batch_size = pc_normal.shape[0]
point_feature = self.point_encoder.encode_latents(pc_normal)
processed_point_feature = self.process_point_feature(point_feature)
generate_length = self.max_length - self.cond_length
net_device = next(self.parameters()).device
outputs = torch.ones(batch_size, generate_length).long().to(net_device) * self.eos_token_id
if not sampling:
results = self.transformer.generate(
inputs_embeds=processed_point_feature,
max_new_tokens=generate_length, # all faces plus two
num_beams=1,
bos_token_id=self.bos_token_id,
eos_token_id=self.eos_token_id,
pad_token_id=self.pad_token_id,
)
else:
results = self.transformer.generate(
inputs_embeds = processed_point_feature,
max_new_tokens=generate_length, # all faces plus two
do_sample=True,
top_k=50,
top_p=0.95,
bos_token_id = self.bos_token_id,
eos_token_id = self.eos_token_id,
pad_token_id = self.pad_token_id,
)
assert results.shape[1] <= generate_length # B x ID bos is not included since it's predicted
outputs[:, :results.shape[1]] = results
# batch x ntokens ====> batch x ntokens x D
outputs = outputs[:, 1: -1]
outputs[outputs == self.bos_token_id] = self.tokenizer.pad_id
outputs[outputs == self.eos_token_id] = self.tokenizer.pad_id
outputs[outputs == self.pad_token_id] = self.tokenizer.pad_id
outputs[outputs != self.tokenizer.pad_id] -= 3
code_embed = self.get_codes(outputs)
decoder_output = self.tokenizer(outputs, code_embed, point_feature=point_feature)
return decoder_output
def get_codes(self, indices):
indices = indices.reshape(indices.shape[0], -1)
indices = rearrange(indices, 'b (n q) -> b n q', q=self.num_quantizers)
batch, quantize_dim = indices.shape[0], indices.shape[-1]
# may also receive indices in the shape of 'b h w q' (accept_image_fmap)
indices, ps = pack([indices], 'b * q')
# because of quantize dropout, one can pass in indices that are coarse
# and the network should be able to reconstruct
if quantize_dim < self.num_quantizers:
indices = F.pad(indices, (0, self.num_quantizers - quantize_dim), value = -1)
# take care of quantizer dropout
mask = indices == -1.
indices = indices.masked_fill(mask, 0) # have it fetch a dummy code to be masked out later
# dummy implementation for shared codebook
all_codes = self.transformer.model.decoder.quantize_codebooks[0][indices]
all_codes = all_codes.permute(2, 0, 1, 3)
# mask out any codes that were dropout-ed
all_codes = all_codes.masked_fill(rearrange(mask, 'b n q -> q b n 1'), 0.)
# if (accept_image_fmap = True) then return shape (quantize, batch, height, width, dimension)
codes, = unpack(all_codes, ps, 'q b * d')
codes_summed = reduce(codes, 'q ... -> ...', 'sum')
return codes_summed
def undiscretize(
t,
low,
high,
num_discrete
) -> Tensor:
t = t.float()
t /= num_discrete
return t * (high - low) + low

View File

@ -0,0 +1,464 @@
from transformers import AutoModelForCausalLM, AutoConfig, OPTConfig
from transformers.models.opt.modeling_opt import OPTForCausalLM, OPTModel, OPTDecoder, OPTLearnedPositionalEmbedding, OPTDecoderLayer
from typing import List, Optional, Tuple, Union
from einops import repeat
from transformers.modeling_outputs import (
CausalLMOutputWithPast,
)
import torch
from torch import nn
from torch.nn import CrossEntropyLoss
from transformers.utils import replace_return_docstrings, logging
from transformers.modeling_outputs import BaseModelOutputWithPast
# from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
class ShapeOPTConfig(OPTConfig):
model_type = "shape_opt"
class ShapeOPT(OPTForCausalLM):
config_class = ShapeOPTConfig
def __init__(self, config: ShapeOPTConfig):
super(OPTForCausalLM, self).__init__(config)
self.model = ShapeOPTModel(config)
self.lm_head = nn.Linear(config.word_embed_proj_dim, config.vocab_size, bias=False)
# Initialize weights and apply final processing
self.post_init()
def tie_weights(self):
"""
Tie the weights between the input embeddings and the output embeddings.
If the `torchscript` flag is set in the configuration, can't handle parameter sharing so we are cloning the
weights instead.
"""
if getattr(self.config, "is_encoder_decoder", False) and getattr(self.config, "tie_encoder_decoder", False):
if hasattr(self, self.base_model_prefix):
self = getattr(self, self.base_model_prefix)
self._tie_encoder_decoder_weights(self.encoder, self.decoder, self.base_model_prefix)
for module in self.modules():
if hasattr(module, "_tie_weights"):
module._tie_weights()
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class="OPTConfig")
def forward(
self,
input_ids: torch.LongTensor = None,
face_ids: torch.LongTensor = None,
attention_mask: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
past_key_values: Optional[List[torch.FloatTensor]] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple, CausalLMOutputWithPast]:
r"""
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
provide it.
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
head_mask (`torch.Tensor` of shape `(num_hidden_layers, num_attention_heads)`, *optional*):
Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
- 1 indicates the head is **not masked**,
- 0 indicates the head is **masked**.
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional
tensors are only required when the model is used as a decoder in a Sequence to Sequence model.
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
than the model's internal embedding lookup matrix.
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
use_cache (`bool`, *optional*):
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
(see `past_key_values`).
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
returned tensors for more detail.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
for more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
Returns:
Example:
```python
>>> from transformers import AutoTokenizer, OPTForCausalLM
>>> model = OPTForCausalLM.from_pretrained("facebook/opt-350m")
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m")
>>> prompt = "Hey, are you conscious? Can you talk to me?"
>>> inputs = tokenizer(prompt, return_tensors="pt")
>>> # Generate
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"Hey, are you conscious? Can you talk to me?\nI'm not conscious. I'm just a little bit of a weirdo."
```"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
outputs = self.model.decoder(
input_ids=input_ids,
face_ids = face_ids,
attention_mask=attention_mask,
head_mask=head_mask,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
logits = self.lm_head(outputs[0]).contiguous()
loss = None
if labels is not None:
# move labels to correct device to enable model parallelism
labels = labels.to(logits.device)
# Shift so that tokens < n predict n
shift_logits = logits[..., :-1, :].contiguous()
shift_labels = labels[..., 1:].contiguous()
# Flatten the tokens
loss_fct = CrossEntropyLoss()
loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1))
if not return_dict:
output = (logits,) + outputs[1:]
return (loss,) + output if loss is not None else output
return CausalLMOutputWithPast(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
class ShapeOPTModel(OPTModel):
config_class = ShapeOPTConfig
def __init__(self, config: ShapeOPTConfig):
super(OPTModel,self).__init__(config)
self.decoder = ShapeOPTDecoder(config)
# Initialize weights and apply final processing
self.post_init()
class ShapeOPTDecoder(OPTDecoder):
config_class = ShapeOPTConfig
def __init__(self, config: ShapeOPTConfig):
super(OPTDecoder,self).__init__(config)
self.config = config
self.dropout = config.dropout
self.layerdrop = config.layerdrop
self.padding_idx = config.pad_token_id
self.max_target_positions = config.max_position_embeddings
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size, config.word_embed_proj_dim, self.padding_idx) # not used
self.hidden_size = config.hidden_size
self.word_embed_proj_dim = config.word_embed_proj_dim
self.extra_embeds = nn.Embedding(3, config.word_embed_proj_dim) #padding_idx=self.padding_idx)
self.input_layer = nn.Linear(config.quantize_codebook_dim, config.word_embed_proj_dim)
self.embed_positions = OPTLearnedPositionalEmbedding(config.max_position_embeddings, config.hidden_size)
self.token_embed_positions = OPTFacePositionalEmbedding(config.face_per_token + 3, config.word_embed_proj_dim) #padding_idx=self.padding_idx)
self.face_per_token = config.face_per_token
self.cond_length = config.cond_length
self.cond_embed = nn.Embedding(2, config.word_embed_proj_dim)
if config.word_embed_proj_dim != config.hidden_size:
self.project_out = nn.Linear(config.hidden_size, config.word_embed_proj_dim, bias=False)
else:
self.project_out = None
if config.word_embed_proj_dim != config.hidden_size:
self.project_in = nn.Linear(config.word_embed_proj_dim, config.hidden_size, bias=False)
else:
self.project_in = None
# Note that the only purpose of `config._remove_final_layer_norm` is to keep backward compatibility
# with checkpoints that have been fine-tuned before transformers v4.20.1
# see https://github.com/facebookresearch/metaseq/pull/164
if config.do_layer_norm_before and not config._remove_final_layer_norm:
self.final_layer_norm = nn.LayerNorm(
config.hidden_size, elementwise_affine=config.layer_norm_elementwise_affine
)
else:
self.final_layer_norm = None
self.layers = nn.ModuleList([OPTDecoderLayer(config) for _ in range(config.num_hidden_layers)])
self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
self.gradient_checkpointing = False
# Initialize weights and apply final processing
self.post_init()
def embed_with_vae(self, input_ids):
inputs_embeds = repeat(torch.zeros(input_ids.shape, device=input_ids.device), 'b n -> b n d',
d=self.word_embed_proj_dim).clone().detach()
idx_in_extra = torch.isin(input_ids, torch.LongTensor([0, 1, 2]).to(input_ids.device))
inputs_embeds[idx_in_extra] += self.extra_embeds(input_ids[idx_in_extra])
self.quantize_codebooks = self.quantize_codebooks.to(input_ids.device)
inputs_embeds[~idx_in_extra] += self.input_layer(self.quantize_codebooks[0][input_ids[~idx_in_extra] - 3])
return inputs_embeds
def forward(
self,
input_ids: torch.LongTensor = None,
face_ids: torch.LongTensor = None,
attention_mask: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
past_key_values: Optional[List[torch.FloatTensor]] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple, BaseModelOutputWithPast]:
r"""
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
provide it.
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
head_mask (`torch.Tensor` of shape `(num_hidden_layers, num_attention_heads)`, *optional*):
Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
- 1 indicates the head is **not masked**,
- 0 indicates the head is **masked**.
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
than the model's internal embedding lookup matrix.
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
returned tensors for more detail.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
for more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""
# OPT Decoder
# print("used my Trans")
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
use_cache = use_cache if use_cache is not None else self.config.use_cache
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
# Transformer Decoder
if input_ids is not None:
input_shape = input_ids.size()
input_ids = input_ids.view(-1, input_shape[-1])
inputs_embeds = self.embed_with_vae(input_ids) # nothing to do with position
face_embeds = self.token_embed_positions(attention_mask[:, self.cond_length:], face_ids, input_ids,
self.face_per_token)
inputs_embeds += face_embeds
cond_embed_query = torch.ones((inputs_embeds.shape[0], inputs_embeds.shape[1]), device=inputs_embeds.device,
dtype=inputs_embeds.dtype).long()
inputs_embeds = inputs_embeds + self.cond_embed(cond_embed_query)
elif inputs_embeds is not None:
# assert self.cond and not self.training
total_length = inputs_embeds.shape[1] # B x length x embeding
cond_embed_query = torch.zeros((inputs_embeds.shape[0], total_length), device=inputs_embeds.device,
dtype=inputs_embeds.dtype).long()
inputs_embeds = inputs_embeds + self.cond_embed(cond_embed_query)
else:
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
batch_size, seq_length = inputs_embeds.shape[:2] # seq_length not used since mask_seq_length is not used
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
# required mask seq length can be calculated via length of past
mask_seq_length = past_key_values_length + seq_length # not used since attention mask is input
# embed positions
if self._use_flash_attention_2:
# 2d mask is passed through the layers
assert attention_mask is not None
causal_attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
attention_mask = (
torch.ones(batch_size, mask_seq_length, device=inputs_embeds.device)
if attention_mask is None
else attention_mask
)
else:
raise ValueError("Only flash_attention_2 is supported in MeshAnything")
pos_embeds = self.embed_positions(attention_mask, past_key_values_length)
if self.project_in is not None:
inputs_embeds = self.project_in(inputs_embeds)
hidden_states = inputs_embeds + pos_embeds
# decoder layers
all_hidden_states = () if output_hidden_states else None
all_self_attns = () if output_attentions else None
next_decoder_cache = () if use_cache else None
# check if head_mask has a correct number of layers specified if desired
for attn_mask, mask_name in zip([head_mask], ["head_mask"]):
if attn_mask is not None:
if attn_mask.size()[0] != (len(self.layers)):
raise ValueError(
f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
f" {head_mask.size()[0]}."
)
for idx, decoder_layer in enumerate(self.layers):
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
if output_hidden_states:
all_hidden_states += (hidden_states,)
if self.training:
dropout_probability = torch.rand([])
if dropout_probability < self.layerdrop:
continue
past_key_value = past_key_values[idx] if past_key_values is not None else None
if self.gradient_checkpointing and self.training:
layer_outputs = self._gradient_checkpointing_func(
decoder_layer.__call__,
hidden_states,
causal_attention_mask,
head_mask[idx] if head_mask is not None else None,
None,
output_attentions,
use_cache,
)
else:
layer_outputs = decoder_layer(
hidden_states,
attention_mask=causal_attention_mask,
layer_head_mask=(head_mask[idx] if head_mask is not None else None),
past_key_value=past_key_value,
output_attentions=output_attentions,
use_cache=use_cache,
)
hidden_states = layer_outputs[0]
if use_cache:
next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
if output_attentions:
all_self_attns += (layer_outputs[1],)
if self.final_layer_norm is not None:
hidden_states = self.final_layer_norm(hidden_states)
if self.project_out is not None:
hidden_states = self.project_out(hidden_states)
# add hidden states from the last decoder layer
if output_hidden_states:
all_hidden_states += (hidden_states,)
next_cache = next_decoder_cache if use_cache else None
if not return_dict:
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
return BaseModelOutputWithPast(
last_hidden_state=hidden_states,
past_key_values=next_cache,
hidden_states=all_hidden_states,
attentions=all_self_attns,
)
class OPTFacePositionalEmbedding(nn.Embedding):
"""
This module learns positional embeddings up to a fixed maximum size.
"""
def __init__(self, num_embeddings: int, embedding_dim: int):
super().__init__(num_embeddings, embedding_dim)
def forward(self, attention_mask=None, face_ids = None, input_ids = None, face_per_token = None):
"""`input_ids_shape` is expected to be [bsz x seqlen]."""
if face_ids is not None:
return super().forward(face_ids)
assert input_ids.shape[1] == 1
idx_in_extra = torch.isin(input_ids, torch.LongTensor([0, 1, 2]).to(input_ids.device))
cur_ids = input_ids.clone().detach()
cur_index = (attention_mask.sum(dim=1, keepdim=True) - 2) % face_per_token + 3
cur_ids[~idx_in_extra]=cur_index[~idx_in_extra]
return super().forward(cur_ids)
AutoConfig.register("shape_opt", ShapeOPTConfig)
AutoModelForCausalLM.register(ShapeOPTConfig, ShapeOPT)

123
README.md Normal file
View File

@ -0,0 +1,123 @@
<p align="center">
<h3 align="center"><strong>MeshAnything:<br> Artist-Created Mesh Generation<br> with Autoregressive Transformers</strong></h3>
<p align="center">
<a href="https://buaacyw.github.io/">Yiwen Chen</a><sup>1,2*</sup>,
<a href="https://tonghe90.github.io/">Tong He</a><sup>2†</sup>,
<a href="https://dihuang.me/">Di Huang</a><sup>2</sup>,
<a href="https://ywcmaike.github.io/">Weicai Ye</a><sup>2</sup>,
<a href="https://ch3cook-fdu.github.io/">Sijin Chen</a><sup>3</sup>,
<a href="https://me.kiui.moe/">Jiaxiang Tang</a><sup>4</sup><br>
<a href="https://chenxin.tech/">Xin Chen</a><sup>5</sup>,
<a href="https://caizhongang.github.io/">Zhongang Cai</a><sup>6</sup>,
<a href="https://scholar.google.com.hk/citations?user=jZH2IPYAAAAJ&hl=en">Lei Yang</a><sup>6</sup>,
<a href="https://www.skicyyu.org/">Gang Yu</a><sup>7</sup>,
<a href="https://guosheng.github.io/">Guosheng Lin</a><sup>1†</sup>,
<a href="https://icoz69.github.io/">Chi Zhang</a><sup>8†</sup>
<br>
<sup>*</sup>Work done during a research internship at Shanghai AI Lab.
<br>
<sup></sup>Corresponding authors.
<br>
<sup>1</sup>S-Lab, Nanyang Technological University,
<sup>2</sup>Shanghai AI Lab,
<br>
<sup>3</sup>Fudan University,
<sup>4</sup>Peking University,
<sup>5</sup>University of Chinese Academy of Sciences,
<br>
<sup>6</sup>SenseTime Research,
<sup>7</sup>Stepfun,
<sup>8</sup>Westlake University
</p>
<div align="center">
<a href='https://arxiv.org/abs/2311.14521'><img src='https://img.shields.io/badge/arXiv-2311.14521-b31b1b.svg'></a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<a href='https://buaacyw.github.io/mesh-anything/'><img src='https://img.shields.io/badge/Project-Page-Green'></a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<a href='https://github.com/buaacyw/MeshAnything/blob/master/LICENSE.txt'><img src='https://img.shields.io/badge/License-SLab-blue'></a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<a href="https://huggingface.co/spaces/Yiwen-ntu/MeshAnything"><img src="https://img.shields.io/badge/%F0%9F%A4%97%20Gradio%20Demo-Huggingface-orange"></a>;
</div>
<p align="center">
<img src="demo/demo_video.gif" alt="Demo GIF" width="1000px" />
</p>
## Release
- [6/17] 🔥🔥 We released the 350m version of **MeshAnything**.
## Contents
- [Release](#release)
- [Contents](#contents)
- [Installation](#installation)
- [Usage](#usage)
- [Important Notes](#important-notes)
- [TODO](#todo)
## Installation
Our environment has been tested on Ubuntu 22, CUDA 11.8 with A100, A800 and A6000.
1. Clone our repo and create conda environment
```
git clone https://github.com/buaacyw/MeshAnything.git && cd MeshAnything
conda create -n MeshAnything python==3.10.13
conda activate MeshAnything
pip install torch==2.1.1 torchvision==0.16.1 torchaudio==2.1.1 --index-url https://download.pytorch.org/whl/cu118
pip install -r requirements.txt
pip install flash-attn --no-build-isolation
```
## Usage
```
# Gradio Demo
python app.py
# Command line inference
# For mesh
# inference for folder
python main.py --input_dir examples --out_dir mesh_output --input_type mesh
# inference for single file
python main.py --input_dir examples/wand.ply --out_dir mesh_output --input_type mesh
# Preprocess with Marching Cubes first
python main.py --input_dir examples --out_dir mesh_output --input_type mesh --mc
# For point cloud
# Note: if you want to use your own point cloud, please make sure the normal is included.
# The file format should be a .npy file with shape (N, 6), where N is the number of points. The first 3 columns are the coordinates, and the last 3 columns are the normal.
# inference for folder
python main.py --input_dir pc_examples --out_dir pc_output --input_type pc_normal
# inference for single file
python main.py --input_dir pc_examples/mouse.npy --out_dir pc_output --input_type pc_normal
```
## Important Notes
- The input mesh will be normalized to a unit bounding box. The up vector of the input mesh should be +Y for better results.
- Limited by computational resources, MeshAnything is trained on meshes with fewer than 800 faces and cannot generate meshes with more than 800 faces. The shape of the input mesh should be sharp enough; otherwise, it will be challenging to represent it with only 800 faces. Thus, feed-forward image-to-3D methods may often produce bad results due to insufficient shape quality.
- It takes about 7GB and 30s to generate a mesh on an A6000 GPU.
- Please refer to https://huggingface.co/spaces/Yiwen-ntu/MeshAnything/tree/main/examples for more examples.
## TODO
The repo is still being under construction, thanks for your patience.
- [ ] Release of training code.
- [ ] Release of larger model.
## Acknowledgement
Our code is based on these wonderful repos:
* [MeshGPT](https://nihalsid.github.io/mesh-gpt/)
* [meshgpt-pytorch](https://github.com/lucidrains/meshgpt-pytorch)
* [Michelangelo](https://github.com/NeuralCarver/Michelangelo)
* [transformers](https://github.com/huggingface/transformers)
* [vector-quantize-pytorch](https://github.com/lucidrains/vector-quantize-pytorch)

262
app.py Normal file
View File

@ -0,0 +1,262 @@
import os
import torch
import trimesh
from accelerate.utils import set_seed
from accelerate import Accelerator
import numpy as np
import gradio as gr
from main import get_args, load_model
from mesh_to_pc import process_mesh_to_pc
import time
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from PIL import Image
import io
args = get_args()
model = load_model(args)
device = torch.device('cuda')
accelerator = Accelerator(
mixed_precision="fp16",
)
model = accelerator.prepare(model)
model.eval()
print("Model loaded to device")
def wireframe_render(mesh):
views = [
(90, 20), (270, 20)
]
mesh.vertices = mesh.vertices[:, [0, 2, 1]]
bounding_box = mesh.bounds
center = mesh.centroid
scale = np.ptp(bounding_box, axis=0).max()
fig = plt.figure(figsize=(10, 10))
# Function to render and return each view as an image
def render_view(mesh, azimuth, elevation):
ax = fig.add_subplot(111, projection='3d')
ax.set_axis_off()
# Extract vertices and faces for plotting
vertices = mesh.vertices
faces = mesh.faces
# Plot faces
ax.add_collection3d(Poly3DCollection(
vertices[faces],
facecolors=(0.8, 0.5, 0.2, 1.0), # Brownish yellow
edgecolors='k',
linewidths=0.5,
))
# Set limits and center the view on the object
ax.set_xlim(center[0] - scale / 2, center[0] + scale / 2)
ax.set_ylim(center[1] - scale / 2, center[1] + scale / 2)
ax.set_zlim(center[2] - scale / 2, center[2] + scale / 2)
# Set view angle
ax.view_init(elev=elevation, azim=azimuth)
# Save the figure to a buffer
buf = io.BytesIO()
plt.savefig(buf, format='png', bbox_inches='tight', pad_inches=0, dpi=300)
plt.clf()
buf.seek(0)
return Image.open(buf)
# Render each view and store in a list
images = [render_view(mesh, az, el) for az, el in views]
# Combine images horizontally
widths, heights = zip(*(i.size for i in images))
total_width = sum(widths)
max_height = max(heights)
combined_image = Image.new('RGBA', (total_width, max_height))
x_offset = 0
for img in images:
combined_image.paste(img, (x_offset, 0))
x_offset += img.width
# Save the combined image
save_path = f"combined_mesh_view_{int(time.time())}.png"
combined_image.save(save_path)
plt.close(fig)
return save_path
@torch.no_grad()
def do_inference(input_3d, sample_seed=0, do_sampling=False, do_marching_cubes=False):
set_seed(sample_seed)
print("Seed value:", sample_seed)
input_mesh = trimesh.load(input_3d)
pc_list, mesh_list = process_mesh_to_pc([input_mesh], marching_cubes = do_marching_cubes)
mesh = mesh_list[0]
mesh.merge_vertices()
mesh.update_faces(mesh.unique_faces())
mesh.fix_normals()
if mesh.visual.vertex_colors is not None:
orange_color = np.array([255, 165, 0, 255], dtype=np.uint8)
mesh.visual.vertex_colors = np.tile(orange_color, (mesh.vertices.shape[0], 1))
else:
orange_color = np.array([255, 165, 0, 255], dtype=np.uint8)
mesh.visual.vertex_colors = np.tile(orange_color, (mesh.vertices.shape[0], 1))
input_save_name = f"processed_input_{int(time.time())}.obj"
mesh.export(input_save_name)
input_render_res = wireframe_render(mesh)
pc_normal = pc_list[0] # 4096, 6
pc_coor = pc_normal[:, :3]
normals = pc_normal[:, 3:]
bounds = np.array([pc_coor.min(axis=0), pc_coor.max(axis=0)])
pc_coor = pc_coor - (bounds[0] + bounds[1])[None, :] / 2
pc_coor = pc_coor / np.abs(pc_coor).max() * 0.9995
assert (np.linalg.norm(normals, axis=-1) > 0.99).all(), "normals should be unit vectors, something wrong"
normalized_pc_normal = np.concatenate([pc_coor, normals], axis=-1, dtype=np.float16)
input = torch.tensor(normalized_pc_normal, dtype=torch.float16, device=device)[None]
print("Data loaded")
# with accelerator.autocast():
with accelerator.autocast():
outputs = model(input, do_sampling)
print("Model inference done")
recon_mesh = outputs[0]
recon_mesh = recon_mesh[~torch.isnan(recon_mesh[:, 0, 0])] # nvalid_face x 3 x 3
vertices = recon_mesh.reshape(-1, 3).cpu()
vertices_index = np.arange(len(vertices)) # 0, 1, ..., 3 x face
triangles = vertices_index.reshape(-1, 3)
artist_mesh = trimesh.Trimesh(vertices=vertices, faces=triangles, force="mesh",
merge_primitives=True)
artist_mesh.merge_vertices()
artist_mesh.update_faces(artist_mesh.unique_faces())
artist_mesh.fix_normals()
if artist_mesh.visual.vertex_colors is not None:
orange_color = np.array([255, 165, 0, 255], dtype=np.uint8)
artist_mesh.visual.vertex_colors = np.tile(orange_color, (artist_mesh.vertices.shape[0], 1))
else:
orange_color = np.array([255, 165, 0, 255], dtype=np.uint8)
artist_mesh.visual.vertex_colors = np.tile(orange_color, (artist_mesh.vertices.shape[0], 1))
num_faces = len(artist_mesh.faces)
brown_color = np.array([165, 42, 42, 255], dtype=np.uint8)
face_colors = np.tile(brown_color, (num_faces, 1))
artist_mesh.visual.face_colors = face_colors
# add time stamp to avoid cache
save_name = f"output_{int(time.time())}.obj"
artist_mesh.export(save_name)
output_render = wireframe_render(artist_mesh)
return input_save_name, input_render_res, save_name, output_render
_HEADER_ = '''
<h2><b>Official ? Gradio Demo</b></h2><h2><a href='https://github.com/buaacyw/MeshAnything' target='_blank'><b>MeshAnything: Artist-Created Mesh Generation with Autoregressive Transformers</b></a></h2>
**MeshAnything** converts any 3D representation into meshes created by human artists, i.e., Artist-Created Meshes (AMs).
Code: <a href='https://github.com/buaacyw/MeshAnything' target='_blank'>GitHub</a>. Arxiv Paper: <a href='https://buaacyw.github.io/mesh-anything/' target='_blank'>ArXiv</a>.
??????**Important Notes:**
- Gradio doesn't support interactive wireframe rendering currently. For interactive mesh visualization, please use download the obj file and open it with MeshLab or https://3dviewer.net/.
- The input mesh will be normalized to a unit bounding box. The up vector of the input mesh should be +Y for better results. Click **Preprocess with Marching Cubes** if the input mesh is a manually created mesh.
- Limited by computational resources, MeshAnything is trained on meshes with fewer than 800 faces and cannot generate meshes with more than 800 faces. The shape of the input mesh should be sharp enough; otherwise, it will be challenging to represent it with only 800 faces. Thus, feed-forward image-to-3D methods may often produce bad results due to insufficient shape quality.
- For point cloud input, please refer to our github repo <a href='https://github.com/buaacyw/MeshAnything' target='_blank'>GitHub</a>.
'''
_CITE_ = r"""
If MeshAnything is helpful, please help to ? the <a href='https://github.com/buaacyw/MeshAnything' target='_blank'>Github Repo</a>. Thanks!
---
? **License**
S-Lab-1.0 LICENSE. Please refer to the [LICENSE file](https://github.com/buaacyw/GaussianEditor/blob/master/LICENSE.txt) for details.
? **Contact**
If you have any questions, feel free to open a discussion or contact us at <b>yiwen002@e.ntu.edu.sg</b>.
"""
output_model_obj = gr.Model3D(
label="Processed Input Mesh (OBJ Format)",
clear_color=[1, 1, 1, 1],
)
preprocess_model_obj = gr.Model3D(
label="Generated Mesh (OBJ Format)",
clear_color=[1, 1, 1, 1],
)
input_image_render = gr.Image(
label="Wireframe Render of Processed Input Mesh",
)
output_image_render = gr.Image(
label="Wireframe Render of Generated Mesh",
)
with (gr.Blocks() as demo):
gr.Markdown(_HEADER_)
with gr.Row(variant="panel"):
with gr.Column():
with gr.Row():
input_3d = gr.Model3D(
label="Input Mesh",
clear_color=[1,1,1,1],
)
with gr.Row():
with gr.Group():
do_marching_cubes = gr.Checkbox(label="Preprocess with Marching Cubes", value=False)
do_sampling = gr.Checkbox(label="Random Sampling", value=False)
sample_seed = gr.Number(value=0, label="Seed Value", precision=0)
with gr.Row():
submit = gr.Button("Generate", elem_id="generate", variant="primary")
with gr.Row(variant="panel"):
mesh_examples = gr.Examples(
examples=[
os.path.join("examples", img_name) for img_name in sorted(os.listdir("examples"))
],
inputs=input_3d,
outputs=[preprocess_model_obj, input_image_render, output_model_obj, output_image_render],
fn=do_inference,
cache_examples = False,
examples_per_page=10
)
with gr.Column():
with gr.Row():
input_image_render.render()
with gr.Row():
with gr.Tab("OBJ"):
preprocess_model_obj.render()
with gr.Row():
output_image_render.render()
with gr.Row():
with gr.Tab("OBJ"):
output_model_obj.render()
with gr.Row():
gr.Markdown('''Try click random sampling and different <b>Seed Value</b> if the result is unsatisfying''')
gr.Markdown(_CITE_)
mv_images = gr.State()
submit.click(
fn=do_inference,
inputs=[input_3d, sample_seed, do_sampling, do_marching_cubes],
outputs=[preprocess_model_obj, input_image_render, output_model_obj, output_image_render],
)
demo.launch(share=True)

BIN
demo/demo_video.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 MiB

26718
examples/screwdriver.obj Normal file

File diff suppressed because it is too large Load Diff

29645
examples/wand.obj Normal file

File diff suppressed because it is too large Load Diff

177
main.py Normal file
View File

@ -0,0 +1,177 @@
import os, argparse, importlib
import torch
import time
import trimesh
import numpy as np
from MeshAnything.models.meshanything import MeshAnything
import datetime
from accelerate import Accelerator
from accelerate.utils import set_seed
from accelerate.utils import DistributedDataParallelKwargs
from safetensors import safe_open
from mesh_to_pc import process_mesh_to_pc
from huggingface_hub import hf_hub_download
class Dataset:
def __init__(self, input_type, input_list, mc=False):
super().__init__()
self.data = []
if input_type == 'pc_normal':
for input_path in input_list:
# load npy
cur_data = np.load(input_path)
# sample 4096
assert cur_data.shape[0] >= 4096, "input pc_normal should have at least 4096 points"
idx = np.random.choice(cur_data.shape[0], 4096, replace=False)
cur_data = cur_data[idx]
self.data.append({'pc_normal': cur_data, 'uid': input_path.split('/')[-1].split('.')[0]})
elif input_type == 'mesh':
mesh_list = []
for input_path in input_list:
# load ply
cur_data = trimesh.load(input_path)
mesh_list.append(cur_data)
if mc:
print("First Marching Cubes and then sample point cloud, need several minutes...")
pc_list, _ = process_mesh_to_pc(mesh_list, marching_cubes=mc)
for input_path, cur_data in zip(input_list, pc_list):
self.data.append({'pc_normal': cur_data, 'uid': input_path.split('/')[-1].split('.')[0]})
print(f"dataset total data samples: {len(self.data)}")
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
data_dict = {}
data_dict['pc_normal'] = self.data[idx]['pc_normal']
# normalize pc coor
pc_coor = data_dict['pc_normal'][:, :3]
normals = data_dict['pc_normal'][:, 3:]
bounds = np.array([pc_coor.min(axis=0), pc_coor.max(axis=0)])
pc_coor = pc_coor - (bounds[0] + bounds[1])[None, :] / 2
pc_coor = pc_coor / np.abs(pc_coor).max() * 0.9995
assert (np.linalg.norm(normals, axis=-1) > 0.99).all(), "normals should be unit vectors, something wrong"
data_dict['pc_normal'] = np.concatenate([pc_coor, normals], axis=-1, dtype=np.float16)
data_dict['uid'] = self.data[idx]['uid']
return data_dict
def get_args():
parser = argparse.ArgumentParser("MeshAnything", add_help=False)
parser.add_argument('--llm', default="facebook/opt-350m", type=str)
parser.add_argument('--input_dir', default=None, type=str)
parser.add_argument('--input_path', default=None, type=str)
parser.add_argument('--out_dir', default="inference_out", type=str)
parser.add_argument('--pretrained_weights', default="MeshAnything_350m.pth", type=str)
parser.add_argument(
'--input_type',
choices=['mesh','pc_normal'],
default='pc',
help="Type of the asset to process (default: pc)"
)
parser.add_argument("--codebook_size", default=8192, type=int)
parser.add_argument("--codebook_dim", default=1024, type=int)
parser.add_argument("--n_max_triangles", default=800, type=int)
parser.add_argument("--batchsize_per_gpu", default=1, type=int)
parser.add_argument("--seed", default=0, type=int)
parser.add_argument("--mc", default=False, action="store_true")
parser.add_argument("--sampling", default=False, action="store_true")
args = parser.parse_args()
return args
def load_model(args):
model = MeshAnything(args)
print("load model over!!!")
ckpt_path = hf_hub_download(
repo_id="Yiwen-ntu/MeshAnything",
filename="MeshAnything_350m.pth",
)
tensors = {}
with safe_open(ckpt_path, framework="pt", device=0) as f:
for k in f.keys():
tensors[k] = f.get_tensor(k)
model.load_state_dict(tensors, strict=True)
print("load weights over!!!")
return model
if __name__ == "__main__":
args = get_args()
cur_time = datetime.datetime.now().strftime("%d_%H-%M-%S")
checkpoint_dir = os.path.join(args.out_dir, cur_time)
os.makedirs(checkpoint_dir, exist_ok=True)
kwargs = DistributedDataParallelKwargs(find_unused_parameters=True)
accelerator = Accelerator(
mixed_precision="fp16",
project_dir=checkpoint_dir,
kwargs_handlers=[kwargs]
)
model = load_model(args)
# create dataset
if args.input_dir is not None:
input_list = sorted(os.listdir(args.input_dir))
# only ply, obj or npy
if args.input_type == 'pc_normal':
input_list = [os.path.join(args.input_dir, x) for x in input_list if x.endswith('.npy')]
else:
input_list = [os.path.join(args.input_dir, x) for x in input_list if x.endswith('.ply') or x.endswith('.obj') or x.endswith('.npy')]
set_seed(args.seed)
dataset = Dataset(args.input_type, input_list, args.mc)
elif args.input_path is not None:
set_seed(args.seed)
dataset = Dataset(args.input_type, [args.input_path], args.mc)
else:
raise ValueError("input_dir or input_path must be provided.")
dataloader = torch.utils.data.DataLoader(
dataset,
batch_size=args.batchsize_per_gpu,
drop_last = False,
shuffle = False,
)
if accelerator.state.num_processes > 1:
model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model)
dataloader, model = accelerator.prepare(dataloader, model)
begin_time = time.time()
print("Generation Start!!!")
with accelerator.autocast():
for curr_iter, batch_data_label in enumerate(dataloader):
curr_time = time.time()
outputs = model(batch_data_label['pc_normal'], sampling=args.sampling)
batch_size = outputs.shape[0]
device = outputs.device
for batch_id in range(batch_size):
recon_mesh = outputs[batch_id]
recon_mesh = recon_mesh[~torch.isnan(recon_mesh[:, 0, 0])] # nvalid_face x 3 x 3
vertices = recon_mesh.reshape(-1, 3).cpu()
vertices_index = np.arange(len(vertices)) # 0, 1, ..., 3 x face
triangles = vertices_index.reshape(-1, 3)
scene_mesh = trimesh.Trimesh(vertices=vertices, faces=triangles, force="mesh",
merge_primitives=True)
scene_mesh.merge_vertices()
scene_mesh.update_faces(scene_mesh.unique_faces())
scene_mesh.fix_normals()
save_path = os.path.join(checkpoint_dir, f'{batch_data_label["uid"][batch_id]}_gen.obj')
num_faces = len(scene_mesh.faces)
brown_color = np.array([255, 165, 0, 255], dtype=np.uint8)
face_colors = np.tile(brown_color, (num_faces, 1))
scene_mesh.visual.face_colors = face_colors
scene_mesh.export(save_path)
print(f"{save_path} Over!!")
end_time = time.time()
print(f"Total time: {end_time - begin_time}")

58
mesh_to_pc.py Normal file
View File

@ -0,0 +1,58 @@
import mesh2sdf.core
import numpy as np
import skimage.measure
import trimesh
def normalize_vertices(vertices, scale=0.9):
bbmin, bbmax = vertices.min(0), vertices.max(0)
center = (bbmin + bbmax) * 0.5
scale = 2.0 * scale / (bbmax - bbmin).max()
vertices = (vertices - center) * scale
return vertices, center, scale
def export_to_watertight(normalized_mesh, octree_depth: int = 7):
"""
Convert the non-watertight mesh to watertight.
Args:
input_path (str): normalized path
octree_depth (int):
Returns:
mesh(trimesh.Trimesh): watertight mesh
"""
size = 2 ** octree_depth
level = 2 / size
scaled_vertices, to_orig_center, to_orig_scale = normalize_vertices(normalized_mesh.vertices)
sdf = mesh2sdf.core.compute(scaled_vertices, normalized_mesh.faces, size=size)
vertices, faces, normals, _ = skimage.measure.marching_cubes(np.abs(sdf), level)
# watertight mesh
vertices = vertices / size * 2 - 1 # -1 to 1
vertices = vertices / to_orig_scale + to_orig_center
# vertices = vertices / to_orig_scale + to_orig_center
mesh = trimesh.Trimesh(vertices, faces, normals=normals)
return mesh
def process_mesh_to_pc(mesh_list, marching_cubes = False, sample_num = 4096):
# mesh_list : list of trimesh
pc_normal_list = []
return_mesh_list = []
for mesh in mesh_list:
if marching_cubes:
mesh = export_to_watertight(mesh)
print("MC over!")
return_mesh_list.append(mesh)
points, face_idx = mesh.sample(sample_num, return_index=True)
normals = mesh.face_normals[face_idx]
pc_normal = np.concatenate([points, normals], axis=-1, dtype=np.float16)
pc_normal_list.append(pc_normal)
print("process mesh success")
return pc_normal_list, return_mesh_list

BIN
pc_examples/mouse.npy Normal file

Binary file not shown.

13
requirements.txt Normal file
View File

@ -0,0 +1,13 @@
trimesh==4.2.3
accelerate==0.28.0
mesh2sdf==1.1.0
einops==0.7.0
einx==0.1.3
optimum==1.18.0
omegaconf==2.3.0
opencv-python==4.9.0.80
transformers==4.39.3
huggingface_hub
matplotlib
gradio
spaces