Commit ecc1df99 authored by facebook-github-bot's avatar facebook-github-bot
Browse files

Initial commit

fbshipit-source-id: afc575e8e7d8e2796a3f77d8b1c6c4fcb999558d
parents
[flake8]
select = B,C,E,F,P,W,B9
max-line-length = 100
### DEFAULT IGNORES FOR 4-space INDENTED PROJECTS ###
# Main Explanation Docs: https://lintlyci.github.io/Flake8Rules/
#
# E127, E128 are hard to silence in certain nested formatting situations.
# E203 doesn't work for slicing
# E265, E266 talk about comment formatting which is too opinionated.
# E402 warns on imports coming after statements. There are important use cases
# like demandimport (https://fburl.com/demandimport) that require statements
# before imports.
# E501 is not flexible enough, we're using B950 instead.
# E722 is a duplicate of B001.
# F811 looks for duplicate imports + noise for overload typing
# P207 is a duplicate of B003.
# P208 is a duplicate of C403.
# W503 talks about operator formatting which is too opinionated.
ignore = E127, E128, E203, E265, E266, E402, E501, E722, F811, P207, P208, W503
### DEFAULT IGNORES FOR 2-space INDENTED PROJECTS (uncomment) ###
# ignore = E111, E114, E121, E127, E128, E265, E266, E402, E501, P207, P208, W503
exclude =
.git,
.hg,
__pycache__,
_bin/*,
_build/*,
_ig_fbcode_wheel/*,
buck-out/*,
third-party-buck/*,
third-party2/*
# Calculate max-complexity by changing the value below to 1, then surveying fbcode
# to see the distribution of complexity:
# find ./[a-z0-9]* -name 'buck-*' -prune -o -name 'third*party*' -prune -o \
# -name '*.py' -print |\
# parallel flake8 --config ./.flake8 |\
# perl -ne 'if (/C901/) { s/.*\((\d+)\)/$1/; print; }' | stats
# NOTE: This will take a while to run (near an hour IME) so you probably want a
# second working dir to run it in.
# Pick a reasonable point from there (e.g. p95 or "95%")
# As of 2016-05-18 the rough distribution is:
#
# count: 134807
# min: 2
# max: 206
# avg: 4.361
# median: 3
# sum: 587882
# stddev: 4.317
# variance: 18.635
#
# percentiles:
# 75%: 5
# 90%: 8
# 95%: 11
# 99%: 20
# 99.9%: 48
# 99.99%: 107
# 99.999%: 160
max-complexity = 12
# Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to make participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies within all project spaces, and it also applies when
an individual is representing the project or its community in public spaces.
Examples of representing a project or community include using an official
project e-mail address, posting via an official social media account, or acting
as an appointed representative at an online or offline event. Representation of
a project may be further defined and clarified by project maintainers.
This Code of Conduct also applies outside the project spaces when there is a
reasonable belief that an individual's behavior may have a negative impact on
the project or its community.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at <opensource-conduct@meta.com>. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
# Contributing to Meta Open Source Projects
We want to make contributing to this project as easy and transparent as
possible.
## Pull Requests
We actively welcome your pull requests.
Note: pull requests are not imported into the GitHub directory in the usual way. There is an internal Meta repository that is the "source of truth" for the project. The GitHub repository is generated *from* the internal Meta repository. So we don't merge GitHub PRs directly to the GitHub repository -- they must first be imported into internal Meta repository. When Meta employees look at the GitHub PR, there is a special button visible only to them that executes that import. The changes are then automatically reflected from the internal Meta repository back to GitHub. This is why you won't see your PR having being directly merged, but you still see your changes in the repository once it reflects the imported changes.
1. Fork the repo and create your branch from `main`.
2. If you've added code that should be tested, add tests.
3. If you've changed APIs, update the documentation.
4. Ensure the test suite passes.
5. Make sure your code lints.
6. If you haven't already, complete the Contributor License Agreement ("CLA").
## Contributor License Agreement ("CLA")
In order to accept your pull request, we need you to submit a CLA. You only need
to do this once to work on any of Meta's open source projects.
Complete your CLA here: <https://code.facebook.com/cla>
## Issues
We use GitHub issues to track public bugs. Please ensure your description is
clear and has sufficient instructions to be able to reproduce the issue.
Meta has a [bounty program](https://www.facebook.com/whitehat/) for the safe
disclosure of security bugs. In those cases, please go through the process
outlined on that page and do not file a public issue.
## License
By contributing to this project, you agree that your contributions will be licensed
under the LICENSE file in the root directory of this source tree.
Attribution-NonCommercial 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public
licenses, a licensor grants the public permission to use the
licensed material under specified terms and conditions. If
the licensor's permission is not necessary for any reason--for
example, because of any applicable exception or limitation to
copyright--then that use is not regulated by the license. Our
licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of
the licensed material may still be restricted for other
reasons, including because others have copyright or other
rights in the material. A licensor may make special requests,
such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More_considerations
for the public:
wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution-NonCommercial 4.0 International Public
License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution-NonCommercial 4.0 International Public License ("Public
License"). To the extent this Public License may be interpreted as a
contract, You are granted the Licensed Rights in consideration of Your
acceptance of these terms and conditions, and the Licensor grants You
such rights in consideration of benefits the Licensor receives from
making the Licensed Material available under these terms and
conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright
and Similar Rights in Your contributions to Adapted Material in
accordance with the terms and conditions of this Public License.
c. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or
categorized. For purposes of this Public License, the rights
specified in Section 2(b)(1)-(2) are not Copyright and Similar
Rights.
d. Effective Technological Measures means those measures that, in the
absence of proper authority, may not be circumvented under laws
fulfilling obligations under Article 11 of the WIPO Copyright
Treaty adopted on December 20, 1996, and/or similar international
agreements.
e. Exceptions and Limitations means fair use, fair dealing, and/or
any other exception or limitation to Copyright and Similar Rights
that applies to Your use of the Licensed Material.
f. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
g. Licensed Rights means the rights granted to You subject to the
terms and conditions of this Public License, which are limited to
all Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
h. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
i. NonCommercial means not primarily intended for or directed towards
commercial advantage or monetary compensation. For purposes of
this Public License, the exchange of the Licensed Material for
other material subject to Copyright and Similar Rights by digital
file-sharing or similar means is NonCommercial provided there is
no payment of monetary compensation in connection with the
exchange.
j. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
k. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.
l. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or
in part, for NonCommercial purposes only; and
b. produce, reproduce, and Share Adapted Material for
NonCommercial purposes only.
2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
License does not apply, and You do not need to comply with
its terms and conditions.
3. Term. The term of this Public License is specified in Section
6(a).
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
b. No downstream restrictions. You may not offer or impose
any additional or different terms or conditions on, or
apply any Effective Technological Measures to, the
Licensed Material if doing so restricts exercise of the
Licensed Rights by any recipient of the Licensed
Material.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to
the extent possible, the Licensor waives and/or agrees not to
assert any such rights held by the Licensor to the limited
extent necessary to allow You to exercise the Licensed
Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this
Public License.
3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties, including when
the Licensed Material is used other than for NonCommercial
purposes.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the
following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified
form), You must:
a. retain the following if it is supplied by the Licensor
with the Licensed Material:
i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if
designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of
warranties;
v. a URI or hyperlink to the Licensed Material to the
extent reasonably practicable;
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may be
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
4. If You Share Adapted Material You produce, the Adapter's
License You apply must not prevent recipients of the Adapted
Material from complying with this Public License.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database for NonCommercial purposes
only;
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material; and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply with
this Public License, then Your rights under this Public License
terminate automatically.
b. Where Your right to use the Licensed Material has terminated under
Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided
it is cured within 30 days of Your discovery of the
violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is
deemed unenforceable, it shall be automatically reformed to the
minimum extent necessary to make it enforceable. If the provision
cannot be reformed, it shall be severed from this Public License
without affecting the enforceability of the remaining terms and
conditions.
c. No term or condition of this Public License will be waived and no
failure to comply consented to unless expressly agreed to by the
Licensor.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.
Creative Commons may be contacted at creativecommons.org.
# DRTK - Differentiable Rendering Toolkit
This package is a PyTorch library that provides functionality for differentiable rasterization.
It consists of five main components
* **transform**
* **rasterize**
* **render**
* **interpolate**
* **edge_grad**
There are also optional components such as **msi** and **mipmap_grid_sampler**. New components may be added in the future.
Typical flow looks like this:
**transform** -> **rasterize** -> **render** -> **interpolate** -> **CUSTOM SHADING** -> **edge_grad**
where:
- **transform**: projects the vertex positions from camera space to image space
- **rasterize**: performs rasterization, where pixels in the output image are associated with triangles
- **render**: computes depth and baricentric image
- **interpolate**: interpolates arbitrary vertex attributes
- **CUSTOM SHADING**: user implemented shading.
- **edge_grad**: special module that computes gradients for the **rasterize** step which is not differentiable on its own. For details please see [**Rasterized Edge Gradients: Handling Discontinuities Differentiably**](https://arxiv.org/abs/2405.02508)
## Hellow Triangle
The "Hellow Triangle" with DRTK would look like this:
```python
import drtk
import torch as th
from torchvision.utils import save_image # to save images
# create vertex buffer of shape [1 x n_vertices x 3], here for triangle `n_vertices` == 3
v = th.as_tensor([[[0, 511, 1], [255, 0, 1], [511, 511, 1]]]).float().cuda()
# create index buffer
vi = th.as_tensor([[0, 1, 2]]).int().cuda()
# rasterize
index_img = drtk.rasterize(v, vi, height=512, width=512)
# compute baricentrics
_, bary = drtk.render(v, vi, index_img)
# we won't do shading, we'll just save the baricentrics and filter out the empty region
# which is marked with `-1` in `index_img`
img = bary * (index_img != -1)
save_image(img, "render.png")
```
![hellow triangle](doc/hellow_triangle.png)
## Dependencies
* PyTorch >= 2.1.0
## Building
To build a wheel and install it:
```
pip install wheel
python setup.py bdist_wheel
pip install dist/drtk-<wheel_name>.whl
```
To build inplace, which is useful for package development:
```
python setup.py build_ext --inplace -j 1
```
## Contributing
See the [CONTRIBUTING](CONTRIBUTING.md) file for how to help out.
## License
DRTK is CC-BY-NC 4.0 licensed, as found in the LICENSE file.
## Citation
```
@article{pidhorskyi2024rasterized,
title={Rasterized Edge Gradients: Handling Discontinuities Differentiably},
author={Pidhorskyi, Stanislav and Simon, Tomas and Schwartz, Gabriel and Wen, He and Sheikh, Yaser and Saragih, Jason},
journal={arXiv preprint arXiv:2405.02508},
year={2024}
}
```
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from . import utils # noqa # noqa
from .edge_grad_estimator import edge_grad_estimator, edge_grad_estimator_ref # noqa
from .interpolate import interpolate, interpolate_ref # noqa
from .mipmap_grid_sample import mipmap_grid_sample, mipmap_grid_sample_ref # noqa
from .msi import msi # noqa
from .rasterize import rasterize # noqa
from .render import render, render_ref # noqa
from .transform import transform # noqa
__version__ = "0.1.0" # noqa
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, Optional, Tuple
import torch as th
import torch.nn.functional as thf
from drtk import edge_grad_ext
from drtk.interpolate import interpolate
from drtk.utils import index
th.ops.load_library(edge_grad_ext.__file__)
def edge_grad_estimator(
v_pix: th.Tensor,
vi: th.Tensor,
bary_img: th.Tensor,
img: th.Tensor,
index_img: th.Tensor,
v_pix_img_hook: Optional[Callable[[th.Tensor], None]] = None,
) -> th.Tensor:
"""
Args:
v_pix: Pixel-space vertex coordinates with preserved camera-space Z-values.
N x V x 3
vi: face vertex index list tensor
V x 3
bary_img: 3D barycentric coordinate image tensor
N x 3 x H x W
img: The rendered image
N x C x H x W
index_img: index image tensor
N x H x W
v_pix_img_hook: a backward hook that will be registered to v_pix_img. Useful for examining
generated image space. Default None
Returns:
returns the img argument unchanged. Optionally also returns computed
v_pix_img. Your loss should use the returned img, even though it is
unchanged.
Note:
It is important to not spatially modify the rasterized image before passing it to edge_grad_estimator.
Any operation as long as it is differentiable is ok after the edge_grad_estimator.
Examples of opeartions that can be done before edge_grad_estimator:
- Pixel-wise MLP
- Color mapping
- Color correction, gamma correction
If the operation is significantly non-linear, then it is recommended to do it before
edge_grad_estimator. All sorts of clipping and clamping (e.g. `x.clamp(min=0.0, max=1.0)`), must be
done before edge_grad_estimator.
Examples of operations that are not allowed before edge_grad_estimator:
- Gaussian blur
- Warping, deformation
- Masking, cropping, making holes.
Usage::
from drtk.renderlayer import edge_grad_estimator
...
out = renderlayer(v, tex, campos, camrot, focal, princpt,
output_filters=["index_img", "render", "mask", "bary_img", "v_pix"])
img = out["render"] * out["mask"]
img = edge_grad_estimator(
v_pix=out["v_pix"],
vi=rl.vi,
bary_img=out["bary_img"],
img=img,
index_img=out["index_img"]
)
optim.zero_grad()
image_loss = loss_func(img, img_gt)
image_loss.backward()
optim.step()
"""
# Could use v_pix_img output from DRTK, but bary_img needs to be detached.
v_pix_img = interpolate(v_pix, vi, index_img, bary_img.detach())
img = th.ops.edge_grad_ext.edge_grad_estimator(v_pix, v_pix_img, vi, img, index_img)
if v_pix_img_hook is not None:
v_pix_img.register_hook(v_pix_img_hook)
return img
def edge_grad_estimator_ref(
v_pix: th.Tensor,
vi: th.Tensor,
bary_img: th.Tensor,
img: th.Tensor,
index_img: th.Tensor,
v_pix_img_hook: Optional[Callable[[th.Tensor], None]] = None,
) -> th.Tensor:
"""
Python reference implementation for
:func:`drtk.edge_grad_estimator.edge_grad_estimator`.
"""
# could use v_pix_img output from DRTK, but bary_img needs to be detached.
v_pix_img = interpolate(v_pix, vi, index_img, bary_img.detach())
# pyre-fixme[16]: `EdgeGradEstimatorFunction` has no attribute `apply`.
img = EdgeGradEstimatorFunction.apply(v_pix, v_pix_img, vi, img, index_img)
if v_pix_img_hook is not None:
v_pix_img.register_hook(v_pix_img_hook)
return img
class EdgeGradEstimatorFunction(th.autograd.Function):
@staticmethod
@th.cuda.amp.custom_fwd(cast_inputs=th.float32)
# pyre-fixme[14]: `forward` overrides method defined in `Function` inconsistently.
def forward(
ctx,
v_pix: th.Tensor,
v_pix_img: th.Tensor,
vi: th.Tensor,
img: th.Tensor,
index_img: th.Tensor,
) -> th.Tensor:
ctx.save_for_backward(v_pix, img, index_img, vi)
return img
@staticmethod
@th.cuda.amp.custom_bwd
# pyre-fixme[14]: `backward` overrides method defined in `Function` inconsistently.
def backward(ctx, grad_output: th.Tensor) -> Tuple[
Optional[th.Tensor],
Optional[th.Tensor],
Optional[th.Tensor],
Optional[th.Tensor],
Optional[th.Tensor],
]:
# early exit in case geometry is not optimized.
if not ctx.needs_input_grad[1]:
return None, None, None, grad_output, None
v_pix, img, index_img, vi = ctx.saved_tensors
x_grad = img[:, :, :, 1:] - img[:, :, :, :-1]
y_grad = img[:, :, 1:, :] - img[:, :, :-1, :]
l_index = index_img[:, None, :, :-1]
r_index = index_img[:, None, :, 1:]
t_index = index_img[:, None, :-1, :]
b_index = index_img[:, None, 1:, :]
x_mask = r_index != l_index
y_mask = b_index != t_index
x_both_triangles = (r_index != -1) & (l_index != -1)
y_both_triangles = (b_index != -1) & (t_index != -1)
iimg_clamped = index_img.clamp(min=0).long()
# compute barycentric coordinates
b = v_pix.shape[0]
vi_img = index(vi, iimg_clamped, 0).long()
p0 = th.cat(
[index(v_pix[i], vi_img[i, ..., 0].data, 0)[None, ...] for i in range(b)],
dim=0,
)
p1 = th.cat(
[index(v_pix[i], vi_img[i, ..., 1].data, 0)[None, ...] for i in range(b)],
dim=0,
)
p2 = th.cat(
[index(v_pix[i], vi_img[i, ..., 2].data, 0)[None, ...] for i in range(b)],
dim=0,
)
v10 = p1 - p0
v02 = p0 - p2
n = th.cross(v02, v10)
px, py = th.meshgrid(
th.arange(img.shape[-2], device=v_pix.device),
th.arange(img.shape[-1], device=v_pix.device),
)
def epsclamp(x: th.Tensor) -> th.Tensor:
return th.where(x < 0, x.clamp(max=-1e-8), x.clamp(min=1e-8))
# pyre-fixme[53]: Captured variable `n` is not annotated.
# pyre-fixme[53]: Captured variable `p0` is not annotated.
# pyre-fixme[53]: Captured variable `px` is not annotated.
# pyre-fixme[53]: Captured variable `py` is not annotated.
# pyre-fixme[53]: Captured variable `v02` is not annotated.
# pyre-fixme[53]: Captured variable `v10` is not annotated.
def check_if_point_inside_triangle(offset_x: int, offset_y: int) -> th.Tensor:
_px = px + offset_x
_py = py + offset_y
vp0p = th.stack([p0[..., 0] - _px, p0[..., 1] - _py], dim=-1) / epsclamp(
n[..., 2:3]
)
bary_1 = v02[..., 0] * -vp0p[..., 1] + v02[..., 1] * vp0p[..., 0]
bary_2 = v10[..., 0] * -vp0p[..., 1] + v10[..., 1] * vp0p[..., 0]
return ((bary_1 > 0) & (bary_2 > 0) & ((bary_1 + bary_2) < 1))[:, None]
left_pnt_inside_right_triangle = (
check_if_point_inside_triangle(-1, 0)[..., :, 1:]
& x_mask
& x_both_triangles
)
right_pnt_inside_left_triangle = (
check_if_point_inside_triangle(1, 0)[..., :, :-1]
& x_mask
& x_both_triangles
)
down_pnt_inside_up_triangle = (
check_if_point_inside_triangle(0, 1)[..., :-1, :]
& y_mask
& y_both_triangles
)
up_pnt_inside_down_triangle = (
check_if_point_inside_triangle(0, -1)[..., 1:, :]
& y_mask
& y_both_triangles
)
horizontal_intersection = (
right_pnt_inside_left_triangle & left_pnt_inside_right_triangle
)
vertical_intersection = (
down_pnt_inside_up_triangle & up_pnt_inside_down_triangle
)
left_hangs_over_right = left_pnt_inside_right_triangle & (
~right_pnt_inside_left_triangle
)
right_hangs_over_left = right_pnt_inside_left_triangle & (
~left_pnt_inside_right_triangle
)
up_hangs_over_down = up_pnt_inside_down_triangle & (
~down_pnt_inside_up_triangle
)
down_hangs_over_up = down_pnt_inside_up_triangle & (
~up_pnt_inside_down_triangle
)
x_grad *= x_mask
y_grad *= y_mask
grad_output_x = 0.5 * (grad_output[:, :, :, 1:] + grad_output[:, :, :, :-1])
grad_output_y = 0.5 * (grad_output[:, :, 1:, :] + grad_output[:, :, :-1, :])
x_grad = (x_grad * grad_output_x).sum(dim=1)
y_grad = (y_grad * grad_output_y).sum(dim=1)
x_grad_no_int = x_grad * (~horizontal_intersection[:, 0])
y_grad_no_int = y_grad * (~vertical_intersection[:, 0])
x_grad_spread = th.zeros(
*x_grad_no_int.shape[:1],
x_grad_no_int.shape[1],
y_grad_no_int.shape[2],
dtype=x_grad_no_int.dtype,
device=x_grad_no_int.device,
)
x_grad_spread[:, :, :-1] = x_grad_no_int * (~right_hangs_over_left[:, 0])
x_grad_spread[:, :, 1:] += x_grad_no_int * (~left_hangs_over_right[:, 0])
y_grad_spread = th.zeros_like(x_grad_spread)
y_grad_spread[:, :-1, :] = y_grad_no_int * (~down_hangs_over_up[:, 0])
y_grad_spread[:, 1:, :] += y_grad_no_int * (~up_hangs_over_down[:, 0])
# Intersections. Compute border sliding gradients
#################################################
z_grad_spread = th.zeros_like(x_grad_spread)
x_grad_int = x_grad * horizontal_intersection[:, 0]
y_grad_int = y_grad * vertical_intersection[:, 0]
n = thf.normalize(n, dim=-1)
n = n.permute(0, 3, 1, 2)
n_left = n[..., :, :-1]
n_right = n[..., :, 1:]
n_up = n[..., :-1, :]
n_down = n[..., 1:, :]
def get_dp_db(v_varying: th.Tensor, v_fixed: th.Tensor) -> th.Tensor:
"""
Computes derivative of the point position with respect to edge displacement
See drtk/src/edge_grad/edge_grad_kernel.cu
Please refer to the paper "Rasterized Edge Gradients: Handling Discontinuities Differentiably"
for details.
"""
v_varying = thf.normalize(v_varying, dim=1)
v_fixed = thf.normalize(v_fixed, dim=1)
b = th.stack([-v_fixed[:, 1], v_fixed[:, 0]], dim=1)
b_dot_varying = (b * v_varying).sum(dim=1, keepdim=True)
return b[:, 0:1] / epsclamp(b_dot_varying) * v_varying
# We compute partial derivatives by fixing one triangle and moving the
# other, and then vice versa.
# Left triangle moves, right fixed
dp_dbx = get_dp_db(n_left[:, [0, 2]], -n_right[:, [0, 2]])
x_grad_spread[:, :, :-1] += x_grad_int * dp_dbx[:, 0]
z_grad_spread[:, :, :-1] += x_grad_int * dp_dbx[:, 1]
# Left triangle fixed, right moves
dp_dbx = get_dp_db(n_right[:, [0, 2]], n_left[:, [0, 2]])
x_grad_spread[:, :, 1:] += x_grad_int * dp_dbx[:, 0]
z_grad_spread[:, :, 1:] += x_grad_int * dp_dbx[:, 1]
# Upper triangle moves, lower fixed
dp_dby = get_dp_db(n_up[:, [1, 2]], -n_down[:, [1, 2]])
y_grad_spread[:, :-1, :] += y_grad_int * dp_dby[:, 0]
z_grad_spread[:, :-1, :] += y_grad_int * dp_dby[:, 1]
# Lower triangle moves, upper fixed
dp_dby = get_dp_db(n_down[:, [1, 2]], n_up[:, [1, 2]])
y_grad_spread[:, 1:, :] += y_grad_int * dp_dby[:, 0]
z_grad_spread[:, 1:, :] += y_grad_int * dp_dby[:, 1]
m = index_img == -1
x_grad_spread[m] = 0.0
y_grad_spread[m] = 0.0
grad_v_pix = -th.stack([x_grad_spread, y_grad_spread, z_grad_spread], dim=3)
return None, grad_v_pix, None, grad_output, None
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from torch import Tensor
def edge_grad_estimator(
v_pix: Tensor,
v_pix_img: Tensor,
vi: Tensor,
img: Tensor,
index_img: Tensor,
) -> Tensor: ...
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch as th
from drtk import interpolate_ext
th.ops.load_library(interpolate_ext.__file__)
def interpolate(
vert_attributes: th.Tensor,
vi: th.Tensor,
index_img: th.Tensor,
bary_img: th.Tensor,
) -> th.Tensor:
"""
Performs a linear interpolation of the vertex attributes given the barycentric coordinates
Args:
vert_attributes (th.Tensor): vertex attribute tensor
N x V x C
vi (th.Tensor): face vertex index list tensor
V x 3
index_img (th.Tensor): index image tensor
N x H x W
bary_img (th.Tensor): 3D barycentric coordinate image tensor
N x 3 x H x W
Returns:
A tensor with interpolated vertex attributes with a shape [N, C, H, W]
Note:
1. The default of `channels_last` is set to true to make this function backward compatible.
Please consider using the argument `channels_last` instead of permuting the result afterward.
2. By default, the output is not contiguous. Make sure you cal .contiguous() if that is a requirement.
"""
return th.ops.interpolate_ext.interpolate(vert_attributes, vi, index_img, bary_img)
def interpolate_ref(
vert_attributes: th.Tensor,
vi: th.Tensor,
index_img: th.Tensor,
bary_img: th.Tensor,
) -> th.Tensor:
"""
A reference implementation for `interpolate`. See the doc string from `interpolate`
"""
# Run reference implementation in double precision to get as good reference as possible
orig_dtype = vert_attributes.dtype
vert_attributes = vert_attributes.double()
bary_img = bary_img.double()
b = vert_attributes.shape[0]
iimg_clamped = index_img.clamp(min=0).long()
vi_img = vi[iimg_clamped].long()
v_img = th.gather(
vert_attributes,
1,
vi_img.view(b, -1, 1).expand(-1, -1, vert_attributes.shape[-1]),
)
v_img = (
v_img.view(*vi_img.shape[:3], 3, vert_attributes.shape[-1])
.permute(0, 3, 1, 2, 4)
.contiguous()
)
v_img = (v_img * bary_img[..., None]).sum(dim=1)
# Do the sweep of value in the range -1..1 for the `index_img == -1` region, like
# in is done in the CUDA kernel.
undefined_region = th.stack(
[
(
th.arange(0, index_img.shape[-1], device=vert_attributes.device)[
None, ...
]
.repeat(index_img.shape[-2], 1)
.double()
* 2.0
+ 1.0
)
/ index_img.shape[-1]
- 1.0,
(
th.arange(0, index_img.shape[-2], device=vert_attributes.device)[
..., None
]
.repeat(1, index_img.shape[-1])
.double()
* 2.0
+ 1.0
)
/ index_img.shape[-2]
- 1.0,
],
dim=2,
)
undefined_region = th.tile(
undefined_region[None], dims=[1, 1, 1, (vert_attributes.shape[-1] + 1) // 2]
)[:, :, :, : vert_attributes.shape[-1]]
v_img[index_img == -1] = undefined_region.expand(index_img.shape[0], -1, -1, -1)[
index_img == -1, :
]
return v_img.permute(0, 3, 1, 2).to(orig_dtype)
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from torch import Tensor
def interpolate(
vert_attributes: Tensor,
vi: Tensor,
index_img: Tensor,
bary_img: Tensor,
) -> Tensor: ...
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from typing import List, Optional, Tuple
import torch as th
import torch.nn.functional as thf
from drtk import mipmap_grid_sampler_ext
th.ops.load_library(mipmap_grid_sampler_ext.__file__)
def mipmap_grid_sample(
input: List[th.Tensor],
grid: th.Tensor,
vt_dxdy_img: th.Tensor,
max_aniso: int,
mode: str = "bilinear",
padding_mode: str = "zeros",
align_corners: Optional[bool] = None,
force_max_aniso: Optional[bool] = False,
clip_grad: Optional[bool] = False,
) -> th.Tensor:
"""
Similar to torch.nn.functional.grid_sample, but supports mipmapping and anisotropic filtering which mimics
graphics hardware behaviour.
Currently, only spatial (4-D) inputs are supported.
No nearest filtering.
Args:
input (List[th.Tensor]): A list of tensors which represents a mipmap pyramid of a texture. List should
contain highest resolution texture at index 0.
All subsequent elements of the list should contain miplayers that are twice smaller, but is not a
hard requirement. Also there is no hard requirement for all mip levels to be present.
List of tensors of shape [N x C x H_in x W_in], [N x C x H_in / 2 x W_in / 2] ... [N x C x 1 x 1]
grid (th.Tensor): uv coordinates field according to which the inputs are sampled.
N x H_out x W_out x 2
vt_dxdy_img (th.Tensor): Jacobian of uv coordinates field with respect to pixel position.
N x H_out x W_out x 2 x 2
max_aniso (int): Maximum number of samples for anisotropic filtering.
mode (str): Interpolation mode to calculate output values. Same as grid_sample, but without 'nearest'.
'bilinear' | 'bicubic'. Default: 'bilinear'
padding_mode (str): padding mode for outside grid values
'zeros' | 'border' | 'reflection'. Default: 'zeros'
align_corners (bool, optional): Same as in grid_sample. Default: False.
force_max_aniso (bool, optional): Contols number of samples for anisotropic filtering.
When it is False, the extension will work similarly to the graphics hardware implementation,
e.i. it does only needed number of samples, which could be anything from 1 to max_aniso depending
on the ratio of max and min uv gradient. When force_max_aniso is True, the extension always
produces max_aniso number of samples. However this mode is only intended for
debugging/tesing/comparing with reference implementation and it is not intended for the real
usage. Default: False.
clip_grad (bool, optional): Controls behaviour when mipmap layer is missing.
This mipmap implementation allows using not full mipmap pyramid, e.g. you can have only 2, 3 or 4
layers for a texture of size 1024 instead of all 10. Hardware require all of the layers of the
pyramid to be present. Such relaxed requirement leads to ambiguity when it needs to sample from
the missing layer. The flag clip_grad only impacts the cases when needed layers from the mipmap
pyramid are missing. In this scenario:
- when False: it will sample from the last available layer. This will lead to aliasing and
sparsely placed taps. The downside is that it may sample from arbitrary far regions of
the texture.
- when True: it will sample from the last available layer, but it will adjust the step size
to match the sampling rate of the available layer. This will lead to aliasing but densely
placed taps. Which in turn forbids it to sample from arbitrary far regions of the texture.
Returns:
output (Tensor): Result of sampling from inputs given the grid.
N x C x H_out x W_out
"""
if mode != "bilinear" and mode != "bicubic":
raise ValueError(
"mipmap_grid_sample(): only 'bilinear' and 'bicubic' modes are supported "
"but got: '{}'".format(mode)
)
if (
padding_mode != "zeros"
and padding_mode != "border"
and padding_mode != "reflection"
):
raise ValueError(
"mipmap_grid_sample(): expected padding_mode "
"to be 'zeros', 'border', or 'reflection', "
"but got: '{}'".format(padding_mode)
)
if mode == "bilinear":
mode_enum = 0
elif mode == "nearest": # not supported
mode_enum = 1
else: # mode == 'bicubic'
mode_enum = 2
if padding_mode == "zeros":
padding_mode_enum = 0
elif padding_mode == "border":
padding_mode_enum = 1
else: # padding_mode == 'reflection'
padding_mode_enum = 2
if align_corners is None:
align_corners = False
return th.ops.mipmap_grid_sampler_ext.mipmap_grid_sampler_2d(
input,
grid,
vt_dxdy_img,
max_aniso,
padding_mode_enum,
mode_enum,
align_corners,
force_max_aniso,
clip_grad,
)
def mipmap_grid_sample_ref(
input: List[th.Tensor],
grid: th.Tensor,
vt_dxdy_img: th.Tensor,
max_aniso: int,
mode: str = "bilinear",
padding_mode: str = "border",
align_corners: Optional[bool] = False,
high_quality: bool = False,
) -> th.Tensor:
"""
A reference implementation for `mipmap_grid_sample`. See the doc string from `mipmap_grid_sample`
The CUDA version of `mipmap_grid_sample` should behave the same as this referense implementation when:
- `force_max_aniso` argument of `mipmap_grid_sample` is set to True
- `clip_grad` argument of `mipmap_grid_sample` is set to False
- `high_quality` argument of `mipmap_grid_sample_ref` is set to False
"""
q = len(input)
base_level_size = list(input[0].shape[2:])
with th.no_grad():
# vt_dxdy_img has assumes uv in range 0..1.
# For the comutations below we need to convert from normalized units to pixels
size = th.as_tensor(
[base_level_size[0], base_level_size[1]],
dtype=th.float32,
device=vt_dxdy_img.device,
)
vt_dxdy_img_pixel = vt_dxdy_img * size[None, None, None, :]
# x and y gradients magnitudes. We then need to find direction of maximum gradient and
# minimum gradients direction (principal axis)
px, py = _compute_grad_magnitude(vt_dxdy_img_pixel)
if not high_quality:
# This is what hardware implements.
# We assume that maximum and minimum direction is either x or y.
# This assumption is a quite grude approximation
p_max = th.max(px, py)
p_min = th.min(px, py) if max_aniso != 1 else None
else:
# Instead, a more correct way would be to find principal axis using SVD
# Note this is not practical as it is very slow
u, s, v = th.linalg.svd(vt_dxdy_img_pixel)
p_max = s[..., 0]
p_min = s[..., 1]
# Given the max and min gradients, select mipmap levels (assumes linear interpolation
# between mipmaps)
d1, a = _mipmap_selection(q, p_max, p_min, max_aniso)
if max_aniso != 1:
if not high_quality:
uv_step_x = vt_dxdy_img[..., 0, :]
uv_step_y = vt_dxdy_img[..., 1, :]
with th.enable_grad():
uv_ext_x = th.cat(
[
grid + uv_step_x * ((j + 1) / (max_aniso + 1) * 2.0 - 1.0)
for j in range(max_aniso)
],
dim=0,
)
uv_ext_y = th.cat(
[
grid + uv_step_y * ((j + 1) / (max_aniso + 1) * 2.0 - 1.0)
for j in range(max_aniso)
],
dim=0,
)
uv_ext = th.where(
(px > py)[..., None].tile(max_aniso, 1, 1, 2),
uv_ext_x,
uv_ext_y,
)
else:
# From SVD we have direction of the maximum gradient in the uv space.
# We ntegrate along this direction using `max_aniso` samples
uv_step = (v[..., 0, :] * s[..., 0:1]) / size[None, None, None, :]
with th.enable_grad():
uv_ext = th.cat(
[
grid + uv_step * ((j + 1) / (max_aniso + 1) * 2.0 - 1.0)
for j in range(max_aniso)
],
dim=0,
)
result = []
if max_aniso == 1:
for level in input:
r = thf.grid_sample(
level,
grid,
mode=mode,
padding_mode=padding_mode,
align_corners=align_corners,
)
result.append(r)
else:
for level in input:
r = thf.grid_sample(
th.tile(level, (max_aniso, 1, 1, 1)),
uv_ext,
mode=mode,
padding_mode=padding_mode,
align_corners=align_corners,
)
r = r.view(max_aniso, r.shape[0] // max_aniso, *r.shape[1:]).mean(dim=0)
result.append(r)
return _combine_sampled_mipmaps(result, d1, a)
def _mipmap_selection(
q: int,
p_max: th.Tensor,
p_min: Optional[th.Tensor],
max_aniso: int = 1,
) -> Tuple[th.Tensor, th.Tensor]:
if max_aniso != 1:
# See p.255 of OpenGL Core Profile
# N = min(ceil(Pmax/Pmin),maxAniso)
N = th.clamp(th.ceil(p_max / p_min), max=max_aniso)
N[th.isnan(N)] = 1
# Lambda' = log2(Pmax/N)
lambda_ = th.log2(p_max / N)
else:
lambda_ = th.log2(p_max)
lambda_[th.isinf(lambda_)] = 0
# See eq. 8.15, 8.16
# Substract small number (1e-6) so that `lambda_` is always < q - 1
lambda_ = th.clamp(lambda_, min=0, max=q - 1 - 1e-6)
d1 = th.floor(lambda_).long()
a = lambda_ - d1.float()
return d1, a
def _compute_grad_magnitude(vt_dxdy_img: th.Tensor) -> Tuple[th.Tensor, th.Tensor]:
# See p.255 of OpenGL Core Profile
# Px = sqrt(dudx^2 + dvdx^2)
# Py = sqrt(dudy^2 + dvdy^2)
px = th.norm(vt_dxdy_img[..., 0, :], dim=-1)
py = th.norm(vt_dxdy_img[..., 1, :], dim=-1)
return px, py
def _combine_sampled_mipmaps(
sampled_mipmaps: List[th.Tensor], d1: th.Tensor, a: th.Tensor
) -> th.Tensor:
if len(sampled_mipmaps) == 1:
return sampled_mipmaps[0]
sampled_mipmaps = th.stack(sampled_mipmaps, dim=0)
indices = th.cat([d1[None, :, None], d1[None, :, None] + 1], dim=0)
samples = th.gather(
sampled_mipmaps,
dim=0,
index=indices.expand(-1, *sampled_mipmaps.shape[1:3], -1, -1),
)
# Interpolate two nearest mipmaps. See p.266
return th.lerp(samples[0], samples[1], a[:, None])
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from typing import List
from torch import Tensor
def mipmap_grid_sample_2d(
x: List[Tensor],
grid: Tensor,
vt_dxdy_img: Tensor,
max_aniso: int,
padding_mode: int,
interpolation_mode: int,
align_corners: bool,
force_max_ansio: bool,
clip_grad: bool,
) -> Tensor: ...
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch as th
from drtk import msi_ext
th.ops.load_library(msi_ext.__file__)
def msi(
ray_o: th.Tensor,
ray_d: th.Tensor,
texture: th.Tensor,
sub_step_count: int = 2,
min_inv_r: float = 1.0,
max_inv_r: float = 0.0,
stop_thresh: float = 1e-7,
) -> th.Tensor:
"""
Renders a Multi-Sphere Image which is similar to the one described in "NeRF++: Analyzing and Improving
Neural Radiance Fields"
The implementation performs bilinear sampling in the spatial dimensions of each layer and cubic between
the layers.
Args:
ray_o (th.Tensor): Ray origins [N x 3]
ray_d (th.Tensor): Ray directions [N x 3]
texture (th.Tensor): The MSI texture [L x 4 x H x W], where L - number of layers.
The first 3 channels are the color channels, and the fourth one is the sigma (transmittance)
channel (negative log of alpha).
sub_step_count (int, optional): Rate of the subsampling of the layers. Default is 2.
min_inv_r (float, optional): Inverse of the minimum sphere radius. Default is 1 for unit radius.
max_inv_r (float, optional): Inverse of the maximum sphere radius. Default is 0 for infinite radius.
stop_thresh (bool, optional): The threshold for early ray termination when the accumulated
transmittance goes beyond the specified value.
Returns:
output (Tensor): Result of the sampled MSI. First three channels are the color channels, and the 4th
one is sigma (transmittance). [N x 4]
"""
return th.ops.msi_ext.msi(
ray_o, ray_d, texture, sub_step_count, min_inv_r, max_inv_r, stop_thresh
)
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from torch import Tensor
def msi(
ray_o: th.Tensor,
ray_d: th.Tensor,
texture: th.Tensor,
sub_step_count: int,
min_inv_r: float,
max_inv_r: float,
stop_thresh: float,
) -> th.Tensor: ...
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from typing import Tuple
import torch as th
from drtk import rasterize_ext
th.ops.load_library(rasterize_ext.__file__)
def rasterize(
v: th.Tensor,
vi: th.Tensor,
height: int,
width: int,
wireframe: bool = False,
) -> th.Tensor:
"""
Rasterizes a mesh defined by v and vi.
Args:
v (th.Tensor): vertex positions. The first two components are the projected vertex's location (x, y)
on the image plane. The coordinates of the top left corner are (-0.5, -0.5), and the coordinates of
the bottom right corner are (width - 0.5, height - 0.5). The z component is expected to be in the
camera space coordinate frame (before projection).
N x V x 3
vi (th.Tensor): face vertex index list tensor. The most significant nibble of vi is reserved for
controlling visibility of the edges in wireframe mode. In non-wireframe mode, content of the most
significant nibble of vi will be ignored.
V x 3
height (int): height of the image in pixels.
width (int): width of the image in pixels.
wireframe (bool): If False (default), rasterizes triangles. If True, rasterizes lines, where the most
significant nibble of vi is reinterpreted as a bit field controlling the visibility of the edges. The
least significant bit controls the visibility of the first edge, the second bit controls the
visibility of the second edge, and the third bit controls the visibility of the third edge. This
limits the maximum number of vertices to 268435455.
Returns:
The rasterized image of triangle indices which is represented with an index tensor of a shape
[N, H, W] of type int32 that stores a triangle ID for each pixel. If a triangle covers a pixel and is
the closest triangle to the camera, then the pixel will have the ID of that triangle. If no triangles
cover a pixel, then its ID is -1.
Note:
This function is not differentiable. The gradients should be computed with `edge_grad_estimator`
instead.
"""
_, index_img = th.ops.rasterize_ext.rasterize(v, vi, height, width, wireframe)
return index_img
def rasterize_with_depth(
v: th.Tensor,
vi: th.Tensor,
height: int,
width: int,
wireframe: bool = False,
) -> Tuple[th.Tensor, th.Tensor]:
"""
Same as `rasterize` function, additionally returns depth image. Internally it uses the same implementation
as the rasterize function which still computes depth but does not return depth.
Notes:
The function is not differentiable, including the depth output.
The split is done intentionally to hide the depth image from the user as it is not differentiable which
may cause errors if assumed otherwise. Instead, the`barycentrics` function should be used instead to
compute the differentiable version of depth.
However, we still provide `rasterize_with_depth` which returns non-differentiable depth which could allow
to avoid call to `barycentrics` function when differentiability is not required.
Returns:
The rasterized image of triangle indices of shape [N, H, W] and a depth image of shape [N, H, W].
Values in of pixels in the depth image not covered by any pixel are 0.
"""
depth_img, index_img = th.ops.rasterize_ext.rasterize(
v, vi, height, width, wireframe
)
return depth_img, index_img
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from typing import List
from torch import Tensor
def rasterize(
v: Tensor,
vi: Tensor,
height: int,
width: int,
) -> List[Tensor]: ...
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from functools import lru_cache
from typing import Tuple
import torch as th
from drtk import render_ext
th.ops.load_library(render_ext.__file__)
def render(
v: th.Tensor,
vi: th.Tensor,
index_img: th.Tensor,
) -> Tuple[th.Tensor, th.Tensor]:
depth_img, bary_img = th.ops.render_ext.render(v, vi, index_img)
return depth_img, bary_img
def index(x, I, dim):
target_shape = [*x.shape]
del target_shape[dim]
target_shape[dim:dim] = [*I.shape]
return x.index_select(dim, I.view(-1)).reshape(target_shape)
@lru_cache
def _get_grid(width: int, height: int, device: th.device):
return th.stack(
th.meshgrid(th.arange(height, device=device), th.arange(width, device=device))[
::-1
],
dim=2,
)
def render_ref(
v: th.Tensor, vi: th.Tensor, index_img: th.Tensor
) -> Tuple[th.Tensor, th.Tensor]:
# Run reference implementation in double precision to get as good reference as possible
orig_dtype = v.dtype
v = v.double()
b = v.shape[0]
mask = th.ne(index_img, -1)
float_mask = mask.float()[:, None]
index_img_clamped = index_img.clamp(min=0).long()
grid = _get_grid(index_img.shape[-1], index_img.shape[-2], device=v.device)
# compute barycentric coordinates
vi_img = index(vi, index_img_clamped, 0).long()
v_img0 = th.cat(
[index(v[i], vi_img[i, ..., 0].data, 0)[None, ...] for i in range(b)], dim=0
)
v_img1 = th.cat(
[index(v[i], vi_img[i, ..., 1].data, 0)[None, ...] for i in range(b)], dim=0
)
v_img2 = th.cat(
[index(v[i], vi_img[i, ..., 2].data, 0)[None, ...] for i in range(b)], dim=0
)
vec01 = v_img1 - v_img0
vec02 = v_img2 - v_img0
vec12 = v_img2 - v_img1
def epsclamp(x: th.Tensor) -> th.Tensor:
return th.where(x < 0, x.clamp(max=-1e-16), x.clamp(min=1e-16))
det = vec01[..., 0] * vec02[..., 1] - vec01[..., 1] * vec02[..., 0]
denominator = epsclamp(det)
vp0 = grid[None, ...] - v_img0[..., :2]
vp1 = grid[None, ...] - v_img1[..., :2]
lambda_0 = (vp1[..., 1] * vec12[..., 0] - vp1[..., 0] * vec12[..., 1]) / denominator
lambda_1 = (vp0[..., 0] * vec02[..., 1] - vp0[..., 1] * vec02[..., 0]) / denominator
lambda_2 = (vp0[..., 1] * vec01[..., 0] - vp0[..., 0] * vec01[..., 1]) / denominator
assert th.allclose(lambda_0 + lambda_1 + lambda_2, th.ones_like(lambda_0))
lambda_0_mul_w0 = lambda_0 / epsclamp(v_img0[:, :, :, 2])
lambda_1_mul_w1 = lambda_1 / epsclamp(v_img1[:, :, :, 2])
lambda_2_mul_w2 = lambda_2 / epsclamp(v_img2[:, :, :, 2])
zi = 1.0 / epsclamp(lambda_0_mul_w0 + lambda_1_mul_w1 + lambda_2_mul_w2)
bary_0 = lambda_0_mul_w0 * zi
bary_1 = lambda_1_mul_w1 * zi
bary_2 = lambda_2_mul_w2 * zi
bary_img = (
th.cat(
(bary_0[:, None, :, :], bary_1[:, None, :, :], bary_2[:, None, :, :]),
dim=1,
)
* float_mask
)
depth_img = zi * float_mask[:, 0]
return depth_img.to(orig_dtype), bary_img.to(orig_dtype)
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from typing import List
from torch import Tensor
def render(
v: Tensor,
vi: Tensor,
index_img: Tensor,
) -> List[Tensor]: ...
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from typing import Optional, Sequence
import torch as th
from drtk.interpolate import interpolate
from drtk.utils import face_dpdt, project_points_grad
def screen_space_uv_derivative(
v: th.Tensor,
vt: th.Tensor,
vi: th.Tensor,
vti: th.Tensor,
index_img: th.Tensor,
bary_img: th.Tensor,
mask: th.Tensor,
campos: th.Tensor,
camrot: th.Tensor,
focal: th.Tensor,
dist_mode: Optional[Sequence[str]] = None,
dist_coeff: Optional[th.Tensor] = None,
) -> th.Tensor:
"""
Computes per-pixel uv derivative - vt_dxdy_img with respect to the pixel-space position.
vt_dxdy_img is an image of 2x2 Jacobian matrices of the form: [[du/dx, dv/dx],
[du/dy, dv/dy]]
Shape: N x H x W x 2 x 2
"""
dpdt_t, vf = face_dpdt(v, vt, vi.long(), vti.long())
# make three of this for each vertex of the face
dpdt_t = dpdt_t[:, :, None]
dpdt_t = dpdt_t.expand(-1, -1, 3, -1, -1)
# UV grads are not quite well interpolated with barycentrics
# We computes uv grads at per-pixel basis. For faster compute it is better to use CUDA kernel
# make new index list, because gradients have discontinuities and we do not want to interpolate them
vi_dis = th.arange(0, 3 * vi.shape[0], dtype=th.int32, device=v.device).view(-1, 3)
dpdt_t_img = interpolate(
dpdt_t.reshape(dpdt_t.shape[0], dpdt_t.shape[1] * dpdt_t.shape[2], -1),
vi_dis,
index_img,
bary_img,
).permute(0, 2, 3, 1)
dpdt_t_img = dpdt_t_img.view(*dpdt_t_img.shape[:3], 2, 3)
vf_img = interpolate(
vf.reshape(vf.shape[0], vf.shape[1] * vf.shape[2], -1),
vi_dis,
index_img,
bary_img,
).permute(0, 2, 3, 1)
# duplicate vertex position vector for u and v
vf_img = vf_img[:, :, :, None].expand(-1, -1, -1, 2, -1)
# Compute 2D pixel-space gradients (d p_pix / dt)^T.
dp_pix_dt_t_img = project_points_grad(
dpdt_t_img.reshape(v.shape[0], -1, 3),
vf_img.reshape(v.shape[0], -1, 3),
campos,
camrot,
focal,
dist_mode,
dist_coeff,
)
# Uncollapse dimension. The result is (d p_pix / dt)^T
# Where: dp_pix_dt[..., i, j] = d p_pix[j] / dt[i]
dp_pix_dt_t_img = dp_pix_dt_t_img.view(*dpdt_t_img.shape[:3], 2, 2)
# Inverse Jacobian: (dt / d p_pix)^T = ((d p_pix / dt)^T)^-1
# Where: dt_dp_pix_t[..., i, j] = dt[j] / dp_pix[i]
vt_dxdy_img, _ = th.linalg.inv_ex(dp_pix_dt_t_img)
# pyre-fixme[16] Undefined attribute: `th.Tensor` has no attribute `__invert__`.
vt_dxdy_img[~mask, :, :] = 0
return vt_dxdy_img
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment