diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/.github/CODE_OF_CONDUCT.md b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/.github/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000000000000000000000000000000..f049d4c53173cc44e0d0755b874d108891a5bfc5 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/.github/CODE_OF_CONDUCT.md @@ -0,0 +1,76 @@ +# 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. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at . 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 diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/.github/CONTRIBUTING.md b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/.github/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..b43d2141dcb817182e060190e18fb62cebf19e29 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/.github/CONTRIBUTING.md @@ -0,0 +1,53 @@ +# Contributing to PyTorch3D +We want to make contributing to this project as easy and transparent as +possible. + +## Pull Requests +We actively welcome your pull requests. + +However, if you're adding any significant features, please make sure to have a corresponding issue to outline your proposal and motivation and allow time for us to give feedback, *before* you send a PR. +We do not always accept new features, and we take the following factors into consideration: + +- Whether the same feature can be achieved without modifying PyTorch3D directly. If any aspect of the API is not extensible, please highlight this in an issue so we can work on making this more extensible. +- Whether the feature is potentially useful to a large audience, or only to a small portion of users. +- Whether the proposed solution has a good design and interface. +- Whether the proposed solution adds extra mental/practical overhead to users who don't need such feature. +- Whether the proposed solution breaks existing APIs. + +When sending a PR, please ensure you complete the following steps: + +1. Fork the repo and create your branch from `main`. Follow the instructions + in [INSTALL.md](../INSTALL.md) to build the repo. +2. If you've added code that should be tested, add tests. +3. If you've changed any APIs, please update the documentation. +4. Ensure the test suite passes, by running this from the project root: + ``` + python -m unittest discover -v -s tests -t . + ``` +5. Make sure your code lints by running `dev/linter.sh` from the project root. +6. If a PR contains multiple orthogonal changes, split it into multiple separate PRs. +7. 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 Facebook's open source projects. + +Complete your CLA here: + +## 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. + +Facebook 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. + +## Coding Style +We follow these [python](http://google.github.io/styleguide/pyguide.html) and [C++](https://google.github.io/styleguide/cppguide.html) style guides. + +For the linter to work, you will need to install `black`, `flake`, `usort` and `clang-format`, and +they need to be fairly up to date. + +## License +By contributing to PyTorch3D, you agree that your contributions will be licensed +under the LICENSE file in the root directory of this source tree. diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/.github/ISSUE_TEMPLATE/bugs.md b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/.github/ISSUE_TEMPLATE/bugs.md new file mode 100644 index 0000000000000000000000000000000000000000..bbba16affdb8efa3dee61ede84e5d406350a613a --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/.github/ISSUE_TEMPLATE/bugs.md @@ -0,0 +1,30 @@ +--- +name: "🐛 Bugs / Unexpected behaviors" +about: Please report unexpected behaviors or bugs in PyTorch3D. + +--- + +If you do not know the root cause of the problem / bug, and wish someone to help you, please +post according to this template: + +## 🐛 Bugs / Unexpected behaviors + + +NOTE: Please look at the existing list of Issues tagged with the label ['bug`](https://github.com/facebookresearch/pytorch3d/issues?q=label%3Abug). **Only open a new issue if this bug has not already been reported. If an issue already exists, please comment there instead.**. + +## Instructions To Reproduce the Issue: + +Please include the following (depending on what the issue is): + +1. Any changes you made (`git diff`) or code you wrote +``` + +``` +2. The exact command(s) you ran: +3. What you observed (including the full logs): +``` + +``` + +Please also simplify the steps as much as possible so they do not require additional resources to + run, such as a private dataset. diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/.github/ISSUE_TEMPLATE/config.yml b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000000000000000000000000000000000000..3ba13e0cec6cbbfd462e9ebf529dd2093148cd69 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1 @@ +blank_issues_enabled: false diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/.github/ISSUE_TEMPLATE/feature_request.md b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000000000000000000000000000000000000..6eaf025dfdb1bdd0944c65f1ab25b34f438a05de --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,21 @@ +--- +name: "\U0001F680 Feature Request" +about: Submit a proposal/request for a new PyTorch3D feature + +--- + +## 🚀 Feature + + +NOTE: Please look at the existing list of Issues tagged with the label ['enhancement`](https://github.com/facebookresearch/pytorch3d/issues?q=label%3Aenhancement). **Only open a new issue if you do not see your feature request there**. + +## Motivation + + + +## Pitch + + + +NOTE: we only consider adding new features if they are useful for many users. diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/.github/ISSUE_TEMPLATE/questions-help.md b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/.github/ISSUE_TEMPLATE/questions-help.md new file mode 100644 index 0000000000000000000000000000000000000000..639d0ff823abd7555d987fd586797b457ff43f3b --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/.github/ISSUE_TEMPLATE/questions-help.md @@ -0,0 +1,21 @@ +--- +name: "❓ Questions" +about: How do I do X with PyTorch3D? How does PyTorch3D do X? + +--- + +## ❓ Questions on how to use PyTorch3D + + + + +NOTE: Please look at the existing list of Issues tagged with the label ['question`](https://github.com/facebookresearch/pytorch3d/issues?q=label%3Aquestion) or ['how-to`](https://github.com/facebookresearch/pytorch3d/issues?q=label%3A%22how+to%22). **Only open a new issue if you cannot find an answer there**. + +Also note the following: + +1. If you encountered any errors or unexpected issues while using PyTorch3D and need help resolving them, + please use the "Bugs / Unexpected behaviors" issue template. + +2. We do not answer general machine learning / computer vision questions that are not specific to + PyTorch3D, such as how a model works or what algorithm/methods can be + used to achieve X. diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/.github/workflows/build.yml b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/.github/workflows/build.yml new file mode 100644 index 0000000000000000000000000000000000000000..618e3f22e34d35c58134c2373cfb63ebabb6df7b --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/.github/workflows/build.yml @@ -0,0 +1,23 @@ +name: facebookresearch/pytorch3d/build_and_test +on: + pull_request: + branches: + - main + push: + branches: + - main +jobs: + binary_linux_conda_cuda: + runs-on: 4-core-ubuntu-gpu-t4 + env: + PYTHON_VERSION: "3.12" + BUILD_VERSION: "${{ github.run_number }}" + PYTORCH_VERSION: "2.4.1" + CU_VERSION: "cu121" + JUST_TESTRUN: 1 + steps: + - uses: actions/checkout@v4 + - name: Build and run tests + run: |- + conda create --name env --yes --quiet conda-build + conda run --no-capture-output --name env python3 ./packaging/build_conda.py --use-conda-cuda diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/dev/linter.sh b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/dev/linter.sh new file mode 100644 index 0000000000000000000000000000000000000000..b7496dba28a894268fd7e6ceceef87cbca2a99c5 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/dev/linter.sh @@ -0,0 +1,40 @@ +#!/bin/bash -e +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +# Run this script at project root by "./dev/linter.sh" before you commit + +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" +DIR=$(dirname "${DIR}") + +if [[ -f "${DIR}/BUCK" ]] +then + pyfmt "${DIR}" +else +# run usort externally only + echo "Running usort..." + usort "${DIR}" +fi + +echo "Running black..." +black "${DIR}" + +echo "Running flake..." +flake8 "${DIR}" || true + +echo "Running clang-format ..." +clangformat=$(command -v clang-format-8 || echo clang-format) +find "${DIR}" -regex ".*\.\(cpp\|c\|cc\|cu\|cuh\|cxx\|h\|hh\|hpp\|hxx\|tcc\|mm\|m\)" -print0 | xargs -0 "${clangformat}" -i + +# Run arc and pyre internally only. +if [[ -f "${DIR}/TARGETS" ]] +then + (cd "${DIR}"; command -v arc > /dev/null && arc lint) || true + + echo "Running pyre..." + echo "To restart/kill pyre server, run 'pyre restart' or 'pyre kill' in fbcode/" + ( cd ~/fbsource/fbcode; arc pyre check //vision/fair/pytorch3d/... ) +fi diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/dev/run_tutorials.sh b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/dev/run_tutorials.sh new file mode 100644 index 0000000000000000000000000000000000000000..7517ea8c74131ab7d6be3c7bf074034a601b9fb3 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/dev/run_tutorials.sh @@ -0,0 +1,56 @@ +#!/usr/bin/bash +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +# This script is for running some of the tutorials using the nightly build in +# an isolated environment. It is designed to be run in docker. + +# If you run this script in this directory with +# sudo docker run --runtime=nvidia -it --rm -v $PWD/../docs/tutorials:/notebooks -v $PWD:/loc pytorch/conda-cuda bash /loc/run_tutorials.sh | tee log.txt +# it should execute some tutorials with the nightly build and resave them, and +# save a log in the current directory. + +# We use nbconvert. runipy would be an alternative but it currently doesn't +# work well with plotly. + +set -e + +conda init bash +# shellcheck source=/dev/null +source ~/.bashrc +conda create -y -n myenv python=3.8 matplotlib ipython ipywidgets nbconvert +conda activate myenv +conda install -y -c iopath iopath +conda install -y -c pytorch pytorch=1.6.0 cudatoolkit=10.1 torchvision +conda install -y -c pytorch3d-nightly pytorch3d +pip install plotly scikit-image + +for notebook in /notebooks/*.ipynb +do + name=$(basename "$notebook") + + if [[ "$name" == "dataloaders_ShapeNetCore_R2N2.ipynb" ]] + then + #skip as data not easily available + continue + fi + if [[ "$name" == "render_densepose.ipynb" ]] + then + #skip as data not easily available + continue + fi + + #comment the lines which install torch, torchvision and pytorch3d + sed -Ei '/(torchvision)|(pytorch3d)/ s/!pip/!#pip/' "$notebook" + #Don't let tqdm use widgets + sed -i 's/from tqdm.notebook import tqdm/from tqdm import tqdm/' "$notebook" + + echo + echo "### ### ###" + echo "starting $name" + time jupyter nbconvert --to notebook --inplace --ExecutePreprocessor.kernel_name=python3 --execute "$notebook" || true + echo "ending $name" +done diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/dev/test_list.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/dev/test_list.py new file mode 100644 index 0000000000000000000000000000000000000000..f00facd8ddae2414c431cbae9ba5f9a810a0e15a --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/dev/test_list.py @@ -0,0 +1,65 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import ast +from pathlib import Path +from typing import List + + +""" +This module outputs a list of tests for completion. +It has no dependencies. +""" + + +def get_test_files() -> List[Path]: + root = Path(__file__).parent.parent + dirs = ["tests", "projects/implicitron_trainer"] + return [i for dir in dirs for i in (root / dir).glob("**/test*.py")] + + +def tests_from_file(path: Path, base: str) -> List[str]: + """ + Returns all the tests in the given file, in format + expected as arguments when running the tests. + e.g. + file_stem + file_stem.TestFunctionality + file_stem.TestFunctionality.test_f + file_stem.TestFunctionality.test_g + """ + with open(path) as f: + node = ast.parse(f.read()) + out = [base] + for cls in node.body: + if not isinstance(cls, ast.ClassDef): + continue + if not cls.name.startswith("Test"): + continue + class_base = base + "." + cls.name + out.append(class_base) + for method in cls.body: + if not isinstance(method, ast.FunctionDef): + continue + if not method.name.startswith("test"): + continue + out.append(class_base + "." + method.name) + return out + + +def main() -> None: + files = get_test_files() + test_root = Path(__file__).parent.parent + all_tests = [] + for f in files: + file_base = str(f.relative_to(test_root))[:-3].replace("/", ".") + all_tests.extend(tests_from_file(f, file_base)) + for test in sorted(all_tests): + print(test) + + +if __name__ == "__main__": + main() diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/feature_extractor/feature_extractor.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/feature_extractor/feature_extractor.rst new file mode 100644 index 0000000000000000000000000000000000000000..1121a2014ad25d2b4beffee748307472940ac098 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/feature_extractor/feature_extractor.rst @@ -0,0 +1,9 @@ +pytorch3d.implicitron.models.feature_extractor.feature_extractor +================================================================ + +feature_extractor + +.. automodule:: pytorch3d.implicitron.models.feature_extractor.feature_extractor + :members: + :undoc-members: + :show-inheritance: diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/feature_extractor/index.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/feature_extractor/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..51a22ac07e6b8cb309ac8090f91999ac06708bb6 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/feature_extractor/index.rst @@ -0,0 +1,7 @@ +pytorch3d.implicitron.models.feature_extractor +============================================== + +.. toctree:: + + feature_extractor + resnet_feature_extractor diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/feature_extractor/resnet_feature_extractor.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/feature_extractor/resnet_feature_extractor.rst new file mode 100644 index 0000000000000000000000000000000000000000..13d37ed4ea8c827a9c46fdc5f51f1435ad75b7fe --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/feature_extractor/resnet_feature_extractor.rst @@ -0,0 +1,9 @@ +pytorch3d.implicitron.models.feature_extractor.resnet_feature_extractor +======================================================================= + +resnet_feature_extractor + +.. automodule:: pytorch3d.implicitron.models.feature_extractor.resnet_feature_extractor + :members: + :undoc-members: + :show-inheritance: diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/global_encoder/autodecoder.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/global_encoder/autodecoder.rst new file mode 100644 index 0000000000000000000000000000000000000000..ee7e36c95d0ddd3148bdf4aeae570fbd60ccc8da --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/global_encoder/autodecoder.rst @@ -0,0 +1,9 @@ +pytorch3d.implicitron.models.global_encoder.autodecoder +======================================================= + +autodecoder + +.. automodule:: pytorch3d.implicitron.models.global_encoder.autodecoder + :members: + :undoc-members: + :show-inheritance: diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/global_encoder/index.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/global_encoder/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..b861de01b36ade75b10b78cb721072ec3ca6cd81 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/global_encoder/index.rst @@ -0,0 +1,7 @@ +pytorch3d.implicitron.models.global_encoder +=========================================== + +.. toctree:: + + autodecoder + global_encoder diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/implicit_function/base.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/implicit_function/base.rst new file mode 100644 index 0000000000000000000000000000000000000000..1161b18157d9eb03cef8c4c28a72f6342fe8df8a --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/implicit_function/base.rst @@ -0,0 +1,9 @@ +pytorch3d.implicitron.models.implicit_function.base +=================================================== + +base + +.. automodule:: pytorch3d.implicitron.models.implicit_function.base + :members: + :undoc-members: + :show-inheritance: diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/implicit_function/decoding_functions.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/implicit_function/decoding_functions.rst new file mode 100644 index 0000000000000000000000000000000000000000..7a1f135fd894906a0cd05f1fe484c1b20a764e53 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/implicit_function/decoding_functions.rst @@ -0,0 +1,9 @@ +pytorch3d.implicitron.models.implicit_function.decoding_functions +================================================================= + +decoding_functions + +.. automodule:: pytorch3d.implicitron.models.implicit_function.decoding_functions + :members: + :undoc-members: + :show-inheritance: diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/implicit_function/idr_feature_field.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/implicit_function/idr_feature_field.rst new file mode 100644 index 0000000000000000000000000000000000000000..8a6d9b5b3c1bfb923b86a3999625b42e955b5dd2 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/implicit_function/idr_feature_field.rst @@ -0,0 +1,9 @@ +pytorch3d.implicitron.models.implicit_function.idr_feature_field +================================================================ + +idr_feature_field + +.. automodule:: pytorch3d.implicitron.models.implicit_function.idr_feature_field + :members: + :undoc-members: + :show-inheritance: diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/implicit_function/index.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/implicit_function/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..60fdcd7add50ede8a831479212ae2d340f37194f --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/implicit_function/index.rst @@ -0,0 +1,13 @@ +pytorch3d.implicitron.models.implicit_function +============================================== + +.. toctree:: + + base + decoding_functions + idr_feature_field + neural_radiance_field + scene_representation_networks + utils + voxel_grid + voxel_grid_implicit_function diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/implicit_function/neural_radiance_field.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/implicit_function/neural_radiance_field.rst new file mode 100644 index 0000000000000000000000000000000000000000..7d81e4f81b75f53c14a15950da9c7259fb634024 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/implicit_function/neural_radiance_field.rst @@ -0,0 +1,9 @@ +pytorch3d.implicitron.models.implicit_function.neural_radiance_field +==================================================================== + +neural_radiance_field + +.. automodule:: pytorch3d.implicitron.models.implicit_function.neural_radiance_field + :members: + :undoc-members: + :show-inheritance: diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/implicit_function/scene_representation_networks.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/implicit_function/scene_representation_networks.rst new file mode 100644 index 0000000000000000000000000000000000000000..8c9eba8018a50ab3b5ca8b0e3357f1c486f88d86 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/implicit_function/scene_representation_networks.rst @@ -0,0 +1,9 @@ +pytorch3d.implicitron.models.implicit_function.scene_representation_networks +============================================================================ + +scene_representation_networks + +.. automodule:: pytorch3d.implicitron.models.implicit_function.scene_representation_networks + :members: + :undoc-members: + :show-inheritance: diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/implicit_function/utils.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/implicit_function/utils.rst new file mode 100644 index 0000000000000000000000000000000000000000..5c8dddb9c4321d798d0261056b9b7996a351a685 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/implicit_function/utils.rst @@ -0,0 +1,9 @@ +pytorch3d.implicitron.models.implicit_function.utils +==================================================== + +utils + +.. automodule:: pytorch3d.implicitron.models.implicit_function.utils + :members: + :undoc-members: + :show-inheritance: diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/implicit_function/voxel_grid.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/implicit_function/voxel_grid.rst new file mode 100644 index 0000000000000000000000000000000000000000..137dea9cf4c5b3c473a06bc961db2a836ff6ec92 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/implicit_function/voxel_grid.rst @@ -0,0 +1,9 @@ +pytorch3d.implicitron.models.implicit_function.voxel_grid +========================================================= + +voxel_grid + +.. automodule:: pytorch3d.implicitron.models.implicit_function.voxel_grid + :members: + :undoc-members: + :show-inheritance: diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/implicit_function/voxel_grid_implicit_function.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/implicit_function/voxel_grid_implicit_function.rst new file mode 100644 index 0000000000000000000000000000000000000000..5687bc401d83e2e3ed72c02673a6c4e62cbedae3 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/implicit_function/voxel_grid_implicit_function.rst @@ -0,0 +1,9 @@ +pytorch3d.implicitron.models.implicit_function.voxel_grid_implicit_function +=========================================================================== + +voxel_grid_implicit_function + +.. automodule:: pytorch3d.implicitron.models.implicit_function.voxel_grid_implicit_function + :members: + :undoc-members: + :show-inheritance: diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/base.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/base.rst new file mode 100644 index 0000000000000000000000000000000000000000..67ad3661ee5253d2d19c22cf46c149af0de10764 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/base.rst @@ -0,0 +1,9 @@ +pytorch3d.implicitron.models.renderer.base +========================================== + +base + +.. automodule:: pytorch3d.implicitron.models.renderer.base + :members: + :undoc-members: + :show-inheritance: diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/index.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..24e7dde7a356123711bf53ce92da87c905d4254e --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/index.rst @@ -0,0 +1,14 @@ +pytorch3d.implicitron.models.renderer +===================================== + +.. toctree:: + + base + lstm_renderer + multipass_ea + ray_point_refiner + ray_sampler + ray_tracing + raymarcher + rgb_net + sdf_renderer diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/lstm_renderer.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/lstm_renderer.rst new file mode 100644 index 0000000000000000000000000000000000000000..f23d985c48e968c275184e289b7483fe4b84ed4d --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/lstm_renderer.rst @@ -0,0 +1,9 @@ +pytorch3d.implicitron.models.renderer.lstm_renderer +=================================================== + +lstm_renderer + +.. automodule:: pytorch3d.implicitron.models.renderer.lstm_renderer + :members: + :undoc-members: + :show-inheritance: diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/multipass_ea.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/multipass_ea.rst new file mode 100644 index 0000000000000000000000000000000000000000..745c3249e389e96a45133b1aab5e41cb30654dc5 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/multipass_ea.rst @@ -0,0 +1,9 @@ +pytorch3d.implicitron.models.renderer.multipass_ea +================================================== + +multipass_ea + +.. automodule:: pytorch3d.implicitron.models.renderer.multipass_ea + :members: + :undoc-members: + :show-inheritance: diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/ray_point_refiner.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/ray_point_refiner.rst new file mode 100644 index 0000000000000000000000000000000000000000..f5387ce8ff0d18970c483e56b4a8d340017b9cfb --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/ray_point_refiner.rst @@ -0,0 +1,9 @@ +pytorch3d.implicitron.models.renderer.ray_point_refiner +======================================================= + +ray_point_refiner + +.. automodule:: pytorch3d.implicitron.models.renderer.ray_point_refiner + :members: + :undoc-members: + :show-inheritance: diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/ray_sampler.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/ray_sampler.rst new file mode 100644 index 0000000000000000000000000000000000000000..5c638abe0e82ad5d6b5b76b6f5353c057bd2bd00 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/ray_sampler.rst @@ -0,0 +1,9 @@ +pytorch3d.implicitron.models.renderer.ray_sampler +================================================= + +ray_sampler + +.. automodule:: pytorch3d.implicitron.models.renderer.ray_sampler + :members: + :undoc-members: + :show-inheritance: diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/ray_tracing.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/ray_tracing.rst new file mode 100644 index 0000000000000000000000000000000000000000..fe2033df3199bf6af429d3c6f60f3126f0d31b55 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/ray_tracing.rst @@ -0,0 +1,9 @@ +pytorch3d.implicitron.models.renderer.ray_tracing +================================================= + +ray_tracing + +.. automodule:: pytorch3d.implicitron.models.renderer.ray_tracing + :members: + :undoc-members: + :show-inheritance: diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/raymarcher.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/raymarcher.rst new file mode 100644 index 0000000000000000000000000000000000000000..687202e98b5d4cfe1a5ec4351cf808af4feba636 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/raymarcher.rst @@ -0,0 +1,9 @@ +pytorch3d.implicitron.models.renderer.raymarcher +================================================ + +raymarcher + +.. automodule:: pytorch3d.implicitron.models.renderer.raymarcher + :members: + :undoc-members: + :show-inheritance: diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/rgb_net.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/rgb_net.rst new file mode 100644 index 0000000000000000000000000000000000000000..dc40dc0799f31d6a22be60d7682d03d13cc37b65 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/rgb_net.rst @@ -0,0 +1,9 @@ +pytorch3d.implicitron.models.renderer.rgb_net +============================================= + +rgb_net + +.. automodule:: pytorch3d.implicitron.models.renderer.rgb_net + :members: + :undoc-members: + :show-inheritance: diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/sdf_renderer.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/sdf_renderer.rst new file mode 100644 index 0000000000000000000000000000000000000000..ca0e48df8cfe982f2d304aa6fdb3c6f29e5ded02 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/renderer/sdf_renderer.rst @@ -0,0 +1,9 @@ +pytorch3d.implicitron.models.renderer.sdf_renderer +================================================== + +sdf_renderer + +.. automodule:: pytorch3d.implicitron.models.renderer.sdf_renderer + :members: + :undoc-members: + :show-inheritance: diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/visualization/index.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/visualization/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..ebc041f29773580c929665cb904afef416f53d7c --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/visualization/index.rst @@ -0,0 +1,6 @@ +pytorch3d.implicitron.models.visualization +========================================== + +.. toctree:: + + render_flyaround diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/visualization/render_flyaround.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/visualization/render_flyaround.rst new file mode 100644 index 0000000000000000000000000000000000000000..49779a125357af228e83ebce2bd4d4edd3718fdc --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/modules/implicitron/models/visualization/render_flyaround.rst @@ -0,0 +1,9 @@ +pytorch3d.implicitron.models.visualization.render_flyaround +=========================================================== + +render_flyaround + +.. automodule:: pytorch3d.implicitron.models.visualization.render_flyaround + :members: + :undoc-members: + :show-inheritance: diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/batching.md b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/batching.md new file mode 100644 index 0000000000000000000000000000000000000000..9aa9943e4408d952a466f653b4342c46161f01b7 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/batching.md @@ -0,0 +1,32 @@ +--- +hide_title: true +sidebar_label: Batching +--- + +# Batching + +In deep learning, every optimization step operates on multiple input examples for robust training. Thus, efficient batching is crucial. For image inputs, batching is straightforward; N images are resized to the same height and width and stacked as a 4 dimensional tensor of shape `N x 3 x H x W`. For meshes, batching is less straightforward. + +batch_intro + +## Batch modes for meshes + +Assume you want to construct a batch containing two meshes, with `mesh1 = (v1: V1 x 3, f1: F1 x 3)` containing `V1` vertices and `F1` faces, and `mesh2 = (v2: V2 x 3, f2: F2 x 3)` with `V2 (!= V1)` vertices and `F2 (!= F1)` faces. The [Meshes][meshes] data structure provides three different ways to batch *heterogeneous* meshes. If `meshes = Meshes(verts = [v1, v2], faces = [f1, f2])` is an instantiation of the data structure, then + +* List: Returns the examples in the batch as a list of tensors. Specifically, `meshes.verts_list()` returns the list of vertices `[v1, v2]`. Similarly, `meshes.faces_list()` returns the list of faces `[f1, f2]`. +* Padded: The padded representation constructs a tensor by padding the extra values. Specifically, `meshes.verts_padded()` returns a tensor of shape `2 x max(V1, V2) x 3` and pads the extra vertices with `0`s. Similarly, `meshes.faces_padded()` returns a tensor of shape `2 x max(F1, F2) x 3` and pads the extra faces with `-1`s. +* Packed: The packed representation concatenates the examples in the batch into a tensor. In particular, `meshes.verts_packed()` returns a tensor of shape `(V1 + V2) x 3`. Similarly, `meshes.faces_packed()` returns a tensor of shape `(F1 + F2) x 3` for the faces. In the packed mode, auxiliary variables are computed that enable efficient conversion between packed and padded or list modes. + +batch_modes + +## Use cases for batch modes + +The need for different mesh batch modes is inherent to the way PyTorch operators are implemented. To fully utilize the optimized PyTorch ops, the [Meshes][meshes] data structure allows for efficient conversion between the different batch modes. This is crucial when aiming for a fast and efficient training cycle. An example of this is [Mesh R-CNN][meshrcnn]. Here, in the same forward pass different parts of the network assume different inputs, which are computed by converting between the different batch modes. In particular, [vert_align][vert_align] assumes a *padded* input tensor while immediately after [graph_conv][graphconv] assumes a *packed* input tensor. + +meshrcnn + + +[meshes]: https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/structures/meshes.py +[graphconv]: https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/ops/graph_conv.py +[vert_align]: https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/ops/vert_align.py +[meshrcnn]: https://github.com/facebookresearch/meshrcnn diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/cameras.md b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/cameras.md new file mode 100644 index 0000000000000000000000000000000000000000..84e52dba03d16b54251d3fe0e68ed6daa2e62e71 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/cameras.md @@ -0,0 +1,101 @@ +--- +hide_title: true +sidebar_label: Cameras +--- + +# Cameras + +## Camera Coordinate Systems + +When working with 3D data, there are 4 coordinate systems users need to know +* **World coordinate system** +This is the system the object/scene lives - the world. +* **Camera view coordinate system** +This is the system that has its origin on the image plane and the `Z`-axis perpendicular to the image plane. In PyTorch3D, we assume that `+X` points left, and `+Y` points up and `+Z` points out from the image plane. The transformation from world to view happens after applying a rotation (`R`) and translation (`T`). +* **NDC coordinate system** +This is the normalized coordinate system that confines in a volume the rendered part of the object/scene. Also known as view volume. For square images, under the PyTorch3D convention, `(+1, +1, znear)` is the top left near corner, and `(-1, -1, zfar)` is the bottom right far corner of the volume. For non-square images, the side of the volume in `XY` with the smallest length ranges from `[-1, 1]` while the larger side from `[-s, s]`, where `s` is the aspect ratio and `s > 1` (larger divided by smaller side). +The transformation from view to NDC happens after applying the camera projection matrix (`P`). +* **Screen coordinate system** +This is another representation of the view volume with the `XY` coordinates defined in pixel space instead of a normalized space. (0,0) is the top left corner of the top left pixel +and (W,H) is the bottom right corner of the bottom right pixel. + +An illustration of the 4 coordinate systems is shown below +![cameras](https://user-images.githubusercontent.com/669761/145090051-67b506d7-6d73-4826-a677-5873b7cb92ba.png) + +## Defining Cameras in PyTorch3D + +Cameras in PyTorch3D transform an object/scene from world to view by first transforming the object/scene to view (via transforms `R` and `T`) and then projecting the 3D object/scene to a normalized space via the projection matrix `P = K[R | T]`, where `K` is the intrinsic matrix. The camera parameters in `K` define the normalized space. If users define the camera parameters in NDC space, then the transform projects points to NDC. If the camera parameters are defined in screen space, the transformed points are in screen space. + +Note that the base `CamerasBase` class makes no assumptions about the coordinate systems. All the above transforms are geometric transforms defined purely by `R`, `T` and `K`. This means that users can define cameras in any coordinate system and for any transforms. The method `transform_points` will apply `K` , `R` and `T` to the input points as a simple matrix transformation. However, if users wish to use cameras with the PyTorch3D renderer, they need to abide to PyTorch3D's coordinate system assumptions (read below). + +We provide instantiations of common camera types in PyTorch3D and how users can flexibly define the projection space below. + +## Interfacing with the PyTorch3D Renderer + +The PyTorch3D renderer for both meshes and point clouds assumes that the camera transformed points, meaning the points passed as input to the rasterizer, are in PyTorch3D's NDC space. So to get the expected rendering outcome, users need to make sure that their 3D input data and cameras abide by these PyTorch3D coordinate system assumptions. The PyTorch3D coordinate system assumes `+X:left`, `+Y: up` and `+Z: from us to scene` (right-handed) . Confusions regarding coordinate systems are common so we advise that you spend some time understanding your data and the coordinate system they live in and transform them accordingly before using the PyTorch3D renderer. + +Examples of cameras and how they interface with the PyTorch3D renderer can be found in our tutorials. + +### Camera Types + +All cameras inherit from `CamerasBase` which is a base class for all cameras. PyTorch3D provides four different camera types. The `CamerasBase` defines methods that are common to all camera models: +* `get_camera_center` that returns the optical center of the camera in world coordinates +* `get_world_to_view_transform` which returns a 3D transform from world coordinates to the camera view coordinates `(R, T)` +* `get_full_projection_transform` which composes the projection transform (`K`) with the world-to-view transform `(R, T)` +* `transform_points` which takes a set of input points in world coordinates and projects to NDC coordinates ranging from [-1, -1, znear] to [+1, +1, zfar]. +* `get_ndc_camera_transform` which defines the conversion to PyTorch3D's NDC space and is called when interfacing with the PyTorch3D renderer. If the camera is defined in NDC space, then the identity transform is returned. If the cameras is defined in screen space, the conversion from screen to NDC is returned. If users define their own camera in screen space, they need to think of the screen to NDC conversion. We provide examples for the `PerspectiveCameras` and `OrthographicCameras`. +* `transform_points_ndc` which takes a set of points in world coordinates and projects them to PyTorch3D's NDC space +* `transform_points_screen` which takes a set of input points in world coordinates and projects them to the screen coordinates ranging from [0, 0, znear] to [W, H, zfar] + +Users can easily customize their own cameras. For each new camera, users should implement the `get_projection_transform` routine that returns the mapping `P` from camera view coordinates to NDC coordinates. + +#### FoVPerspectiveCameras, FoVOrthographicCameras +These two cameras follow the OpenGL convention for perspective and orthographic cameras respectively. The user provides the near `znear` and far `zfar` field which confines the view volume in the `Z` axis. The view volume in the `XY` plane is defined by field of view angle (`fov`) in the case of `FoVPerspectiveCameras` and by `min_x, min_y, max_x, max_y` in the case of `FoVOrthographicCameras`. +These cameras are by default in NDC space. + +#### PerspectiveCameras, OrthographicCameras +These two cameras follow the Multi-View Geometry convention for cameras. The user provides the focal length (`fx`, `fy`) and the principal point (`px`, `py`). For example, `camera = PerspectiveCameras(focal_length=((fx, fy),), principal_point=((px, py),))` + +The camera projection of a 3D point `(X, Y, Z)` in view coordinates to a point `(x, y, z)` in projection space (either NDC or screen) is + +``` +# for perspective camera +x = fx * X / Z + px +y = fy * Y / Z + py +z = 1 / Z + +# for orthographic camera +x = fx * X + px +y = fy * Y + py +z = Z +``` + +The user can define the camera parameters in NDC or in screen space. Screen space camera parameters are common and for that case the user needs to set `in_ndc` to `False` and also provide the `image_size=(height, width)` of the screen, aka the image. + +The `get_ndc_camera_transform` provides the transform from screen to NDC space in PyTorch3D. Note that the screen space assumes that the principal point is provided in the space with `+X left`, `+Y down` and origin at the top left corner of the image. To convert to NDC we need to account for the scaling of the normalized space as well as the change in `XY` direction. + +Below are example of equivalent `PerspectiveCameras` instantiations in NDC and screen space, respectively. + +```python +# NDC space camera +fcl_ndc = (1.2,) +prp_ndc = ((0.2, 0.5),) +cameras_ndc = PerspectiveCameras(focal_length=fcl_ndc, principal_point=prp_ndc) + +# Screen space camera +image_size = ((128, 256),) # (h, w) +fcl_screen = (76.8,) # fcl_ndc * min(image_size) / 2 +prp_screen = ((115.2, 32), ) # w / 2 - px_ndc * min(image_size) / 2, h / 2 - py_ndc * min(image_size) / 2 +cameras_screen = PerspectiveCameras(focal_length=fcl_screen, principal_point=prp_screen, in_ndc=False, image_size=image_size) +``` + +The relationship between screen and NDC specifications of a camera's `focal_length` and `principal_point` is given by the following equations, where `s = min(image_width, image_height)`. +The transformation of x and y coordinates between screen and NDC is exactly the same as for px and py. + +``` +fx_ndc = fx_screen * 2.0 / s +fy_ndc = fy_screen * 2.0 / s + +px_ndc = - (px_screen - image_width / 2.0) * 2.0 / s +py_ndc = - (py_screen - image_height / 2.0) * 2.0 / s +``` diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/cubify.md b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/cubify.md new file mode 100644 index 0000000000000000000000000000000000000000..41f8ecdf008ad72e30ebf7f99bb8db3fdb1edcdb --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/cubify.md @@ -0,0 +1,12 @@ +--- +hide_title: true +sidebar_label: Cubify +--- + +# Cubify + +The [cubify operator](https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/ops/cubify.py) converts an 3D occupancy grid of shape `BxDxHxW`, where `B` is the batch size, into a mesh instantiated as a [Meshes](https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/structures/meshes.py) data structure of `B` elements. The operator replaces every occupied voxel (if its occupancy probability is greater than a user defined threshold) with a cuboid of 12 faces and 8 vertices. Shared vertices are merged, and internal faces are removed resulting in a **watertight** mesh. + +The operator provides three alignment modes {*topleft*, *corner*, *center*} which define the span of the mesh vertices with respect to the voxel grid. The alignment modes are described in the figure below for a 2D grid. + +![input](https://user-images.githubusercontent.com/4369065/81032959-af697380-8e46-11ea-91a8-fae89597f988.png) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/datasets.md b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/datasets.md new file mode 100644 index 0000000000000000000000000000000000000000..ee3588f2ae444567c9aa8787300add255e42e49d --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/datasets.md @@ -0,0 +1,20 @@ +--- +hide_title: true +sidebar_label: Data loaders +--- + +# Data loaders for common 3D Datasets + +### ShapetNetCore + +ShapeNet is a dataset of 3D CAD models. ShapeNetCore is a subset of the ShapeNet dataset and can be downloaded from https://www.shapenet.org/. There are two versions ShapeNetCore: v1 (55 categories) and v2 (57 categories). + +The PyTorch3D [ShapeNetCore data loader](https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/datasets/shapenet/shapenet_core.py) inherits from `torch.utils.data.Dataset`. It takes the path where the ShapeNetCore dataset is stored locally and loads models in the dataset. The ShapeNetCore class loads and returns models with their `categories`, `model_ids`, `vertices` and `faces`. The `ShapeNetCore` data loader also has a customized `render` function that renders models by the specified `model_ids (List[int])`, `categories (List[str])` or `indices (List[int])` with PyTorch3D's differentiable renderer. + +The loaded dataset can be passed to `torch.utils.data.DataLoader` with PyTorch3D's customized collate_fn: `collate_batched_meshes` from the `pytorch3d.dataset.utils` module. The `vertices` and `faces` of the models are used to construct a [Meshes](https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/structures/meshes.py) object representing the batched meshes. This `Meshes` representation can be easily used with other ops and rendering in PyTorch3D. + +### R2N2 + +The R2N2 dataset contains 13 categories that are a subset of the ShapeNetCore v.1 dataset. The R2N2 dataset also contains its own 24 renderings of each object and voxelized models. The R2N2 Dataset can be downloaded following the instructions [here](http://3d-r2n2.stanford.edu/). + +The PyTorch3D [R2N2 data loader](https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/datasets/r2n2/r2n2.py) is initialized with the paths to the ShapeNet dataset, the R2N2 dataset and the splits file for R2N2. Just like `ShapeNetCore`, it can be passed to `torch.utils.data.DataLoader` with a customized collate_fn: `collate_batched_R2N2` from the `pytorch3d.dataset.r2n2.utils` module. It returns all the data that `ShapeNetCore` returns, and in addition, it returns the R2N2 renderings (24 views for each model) along with the camera calibration matrices and a voxel representation for each model. Similar to `ShapeNetCore`, it has a customized `render` function that supports rendering specified models with the PyTorch3D differentiable renderer. In addition, it supports rendering models with the same orientations as R2N2's original renderings. diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/io.md b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/io.md new file mode 100644 index 0000000000000000000000000000000000000000..a75842716cb12e87069889255f5fcdce60b6b55a --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/io.md @@ -0,0 +1,34 @@ +--- +hide_title: true +sidebar_label: File IO +--- + +# File IO +There is a flexible interface for loading and saving point clouds and meshes from different formats. + +The main usage is via the `pytorch3d.io.IO` object, and its methods +`load_mesh`, `save_mesh`, `load_pointcloud` and `save_pointcloud`. + +For example, to load a mesh you might do +``` +from pytorch3d.io import IO + +device=torch.device("cuda:0") +mesh = IO().load_mesh("mymesh.obj", device=device) +``` + +and to save a pointcloud you might do +``` +pcl = Pointclouds(...) +IO().save_pointcloud(pcl, "output_pointcloud.ply") +``` + +For meshes, this supports OBJ, PLY and OFF files. + +For pointclouds, this supports PLY files. + +In addition, there is experimental support for loading meshes from +[glTF 2 assets](https://github.com/KhronosGroup/glTF/tree/master/specification/2.0) +stored either in a GLB container file or a glTF JSON file with embedded binary data. +This must be enabled explicitly, as described in +`pytorch3d/io/experimental_gltf_io.py`. diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/iou3d.md b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/iou3d.md new file mode 100644 index 0000000000000000000000000000000000000000..548d67811cdcc91c30ef12858a6ccda4952c3b87 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/iou3d.md @@ -0,0 +1,93 @@ +--- +hide_title: true +sidebar_label: IoU3D +--- + +# Intersection Over Union of Oriented 3D Boxes: A New Algorithm + +Author: Georgia Gkioxari + +Implementation: Georgia Gkioxari and Nikhila Ravi + +## Description + +Intersection over union (IoU) of boxes is widely used as an evaluation metric in object detection ([1][pascalvoc], [2][coco]). +In 2D, IoU is commonly applied to axis-aligned boxes, namely boxes with edges parallel to the image axis. +In 3D, boxes are usually not axis aligned and can be oriented in any way in the world. +We introduce a new algorithm which computes the *exact* IoU of two *oriented 3D boxes*. + +Our algorithm is based on the simple observation that the intersection of two oriented 3D boxes, `box1` and `box2`, is a convex polyhedron (convex n-gon in 2D) with `n > 2` comprised of connected *planar units*. +In 3D, these planar units are 3D triangular faces. +In 2D, they are 2D edges. +Each planar unit belongs strictly to either `box1` or `box2`. +Our algorithm finds these units by iterating through the sides of each box. + +1. For each 3D triangular face `e` in `box1` we check wether `e` is *inside* `box2`. +2. If `e` is not *inside*, then we discard it. +3. If `e` is *inside* or *partially inside*, then the part of `e` *inside* `box2` is added to the units that comprise the final intersection shape. +4. We repeat for `box2`. + +Below, we show a visualization of our algorithm for the case of 2D oriented boxes. + +

+drawing +

+ +Note that when a box's unit `e` is *partially inside* a `box` then `e` breaks into smaller units. In 2D, `e` is an edge and breaks into smaller edges. In 3D, `e` is a 3D triangular face and is clipped to more and smaller faces by the plane of the `box` it intersects with. +This is the sole fundamental difference between the algorithms for 2D and 3D. + +## Comparison With Other Algorithms + +Current algorithms for 3D box IoU rely on crude approximations or make box assumptions, for example they restrict the orientation of the 3D boxes. +[Objectron][objectron] provides a nice discussion on the limitations of prior works. +[Objectron][objectron] introduces a great algorithm for exact IoU computation of oriented 3D boxes. +Objectron's algorithm computes the intersection points of two boxes using the [Sutherland-Hodgman algorithm][clipalgo]. +The intersection shape is formed by the convex hull from the intersection points, using the [Qhull library][qhull]. + +Our algorithm has several advantages over Objectron's: + +* Our algorithm also computes the points of intersection, similar to Objectron, but in addition stores the *planar units* the points belong to. This eliminates the need for convex hull computation which is `O(nlogn)` and relies on a third party library which often crashes with nondescript error messages. +* Objectron's implementation assumes that boxes are a rotation away from axis aligned. Our algorithm and implementation make no such assumption and work for any 3D boxes. +* Our implementation supports batching, unlike Objectron which assumes single element inputs for `box1` and `box2`. +* Our implementation is easily parallelizable and in fact we provide a custom C++/CUDA implementation which is **450 times faster than Objectron**. + +Below we compare the performance for Objectron (in C++) and our algorithm, in C++ and CUDA. We benchmark for a common use case in object detection where `boxes1` hold M predictions and `boxes2` hold N ground truth 3D boxes in an image and compute the `MxN` IoU matrix. We report the time in ms for `M=N=16`. + +

+drawing +

+ +## Usage and Code + +```python +from pytorch3d.ops import box3d_overlap +# Assume inputs: boxes1 (M, 8, 3) and boxes2 (N, 8, 3) +intersection_vol, iou_3d = box3d_overlap(boxes1, boxes2) +``` + +For more details, read [iou_box3d.py](https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/ops/iou_box3d.py). + +Note that our implementation is not differentiable as of now. We plan to add gradient support soon. + +We also include have extensive [tests](https://github.com/facebookresearch/pytorch3d/blob/main/tests/test_iou_box3d.py) comparing our implementation with Objectron and MeshLab. + + +## Cite + +If you use our 3D IoU algorithm, please cite PyTorch3D + +```bibtex +@article{ravi2020pytorch3d, + author = {Nikhila Ravi and Jeremy Reizenstein and David Novotny and Taylor Gordon + and Wan-Yen Lo and Justin Johnson and Georgia Gkioxari}, + title = {Accelerating 3D Deep Learning with PyTorch3D}, + journal = {arXiv:2007.08501}, + year = {2020}, +} +``` + +[pascalvoc]: http://host.robots.ox.ac.uk/pascal/VOC/ +[coco]: https://cocodataset.org/ +[objectron]: https://arxiv.org/abs/2012.09988 +[qhull]: http://www.qhull.org/ +[clipalgo]: https://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/meshes_io.md b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/meshes_io.md new file mode 100644 index 0000000000000000000000000000000000000000..330c2abff7ed1a8a5c9489d5db9e7bb2f2433e6c --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/meshes_io.md @@ -0,0 +1,75 @@ +--- +sidebar_label: Loading from file +hide_title: true +--- + +# Meshes and IO + +The Meshes object represents a batch of triangulated meshes, and is central to +much of the functionality of PyTorch3D. There is no insistence that each mesh in +the batch has the same number of vertices or faces. When available, it can store +other data which pertains to the mesh, for example face normals, face areas +and textures. + +Two common file formats for storing single meshes are ".obj" and ".ply" files, +and PyTorch3D has functions for reading these. + +## OBJ + +Obj files have a standard way to store extra information about a mesh. Given an +obj file, it can be read with + +``` + verts, faces, aux = load_obj(filename) +``` + +which sets `verts` to be a (V,3)-tensor of vertices and `faces.verts_idx` to be +an (F,3)- tensor of the vertex-indices of each of the corners of the faces. +Faces which are not triangles will be split into triangles. `aux` is an object +which may contain normals, uv coordinates, material colors and textures if they +are present, and `faces` may additionally contain indices into these normals, +textures and materials in its NamedTuple structure. A Meshes object containing a +single mesh can be created from just the vertices and faces using +``` + meshes = Meshes(verts=[verts], faces=[faces.verts_idx]) +``` + +If there is texture information in the `.obj` it can be used to initialize a +`Textures` class which is passed into the `Meshes` constructor. Currently we +support loading of texture maps for meshes which have one texture map for the +entire mesh e.g. + +``` +verts_uvs = aux.verts_uvs[None, ...] # (1, V, 2) +faces_uvs = faces.textures_idx[None, ...] # (1, F, 3) +tex_maps = aux.texture_images + +# tex_maps is a dictionary of {material name: texture image}. +# Take the first image: +texture_image = list(tex_maps.values())[0] +texture_image = texture_image[None, ...] # (1, H, W, 3) + +# Create a textures object +tex = Textures(verts_uvs=verts_uvs, faces_uvs=faces_uvs, maps=texture_image) + +# Initialise the mesh with textures +meshes = Meshes(verts=[verts], faces=[faces.verts_idx], textures=tex) +``` + +The `load_objs_as_meshes` function provides this procedure. + +## PLY + +Ply files are flexible in the way they store additional information. PyTorch3D +provides a function just to read the vertices and faces from a ply file. +The call +``` + verts, faces = load_ply(filename) +``` +sets `verts` to be a (V,3)-tensor of vertices and `faces` to be an (F,3)- +tensor of the vertex-indices of each of the corners of the faces. Faces which +are not triangles will be split into triangles. A Meshes object containing a +single mesh can be created from this data using +``` + meshes = Meshes(verts=[verts], faces=[faces]) +``` diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/renderer.md b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/renderer.md new file mode 100644 index 0000000000000000000000000000000000000000..463dd2f0702c040fdb34a051cc789b14422528a0 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/renderer.md @@ -0,0 +1,76 @@ +--- +hide_title: true +sidebar_label: Overview +--- + +# Rendering Overview + +Differentiable rendering is a relatively new and exciting research area in computer vision, bridging the gap between 2D and 3D by allowing 2D image pixels to be related back to 3D properties of a scene. + +For example, by rendering an image from a 3D shape predicted by a neural network, it is possible to compute a 2D loss with a reference image. Inverting the rendering step means we can relate the 2D loss from the pixels back to the 3D properties of the shape such as the positions of mesh vertices, enabling 3D shapes to be learnt without any explicit 3D supervision. + +We extensively researched existing codebases for differentiable rendering and found that: +- the rendering pipeline is complex with more than 7 separate components which need to interoperate and be differentiable +- popular existing approaches [[1](#1), [2](#2)] are based on the same core implementation which bundles many of the key components into large CUDA kernels which require significant expertise to understand, and has limited scope for extensions +- existing methods either do not support batching or assume that meshes in a batch have the same number of vertices and faces +- existing projects only provide CUDA implementations so they cannot be used without GPUs + +In order to experiment with different approaches, we wanted a modular implementation that is easy to use and extend, and supports [heterogeneous batching](batching.md). Taking inspiration from existing work [[1](#1), [2](#2)], we have created a new, modular, differentiable renderer with **parallel implementations in PyTorch, C++ and CUDA**, as well as comprehensive documentation and tests, with the aim of helping to further research in this field. + +Our implementation decouples the rasterization and shading steps of rendering. The core rasterization step (based on [[2]](#2)) returns several intermediate variables and has an optimized implementation in CUDA. The rest of the pipeline is implemented purely in PyTorch, and is designed to be customized and extended. With this approach, the PyTorch3D differentiable renderer can be imported as a library. + +## Get started + +To learn about more the implementation and start using the renderer refer to [getting started with renderer](renderer_getting_started.md), which also contains the [architecture overview](assets/architecture_renderer.jpg) and [coordinate transformation conventions](assets/transforms_overview.jpg). + +## Tech Report + +For an in depth explanation of the renderer design, key features and benchmarks please refer to the PyTorch3D Technical Report on ArXiv: [Accelerating 3D Deep Learning with PyTorch3D](https://arxiv.org/abs/2007.08501), for the pulsar backend see here: [Fast Differentiable Raycasting for Neural Rendering using Sphere-based Representations](https://arxiv.org/abs/2004.07484). + +--- + +**NOTE: CUDA Memory usage** + +The main comparison in the Technical Report is with SoftRasterizer [[2](#2)]. The SoftRasterizer forward CUDA kernel only outputs one `(N, H, W, 4)` FloatTensor compared with the PyTorch3D rasterizer forward CUDA kernel which outputs 4 tensors: + + - `pix_to_face`, LongTensor `(N, H, W, K)` + - `zbuf`, FloatTensor `(N, H, W, K)` + - `dist`, FloatTensor `(N, H, W, K)` + - `bary_coords`, FloatTensor `(N, H, W, K, 3)` + +where **N** = batch size, **H/W** are image height/width, **K** is the faces per pixel. The PyTorch3D backward pass returns gradients for `zbuf`, `dist` and `bary_coords`. + +Returning intermediate variables from rasterization has an associated memory cost. We can calculate the theoretical lower bound on the memory usage for the forward and backward pass as follows: + +``` +# Assume 4 bytes per float, and 8 bytes for long + +memory_forward_pass = ((N * H * W * K) * 2 + (N * H * W * K * 3)) * 4 + (N * H * W * K) * 8 +memory_backward_pass = ((N * H * W * K) * 2 + (N * H * W * K * 3)) * 4 + +total_memory = memory_forward_pass + memory_backward_pass + = (N * H * W * K) * (5 * 4 * 2 + 8) + = (N * H * W * K) * 48 +``` + +We need 48 bytes per face per pixel of the rasterized output. In order to remain within bounds for memory usage we can vary the batch size (**N**), image size (**H/W**) and faces per pixel (**K**). For example, for a fixed batch size, if using a larger image size, try reducing the faces per pixel. + +--- + +### References + +[1] Kato et al, 'Neural 3D Mesh Renderer', CVPR 2018 + +[2] Liu et al, 'Soft Rasterizer: A Differentiable Renderer for Image-based 3D Reasoning', ICCV 2019 + +[3] Loper et al, 'OpenDR: An Approximate Differentiable Renderer', ECCV 2014 + +[4] De La Gorce et al, 'Model-based 3D Hand Pose Estimation from Monocular Video', PAMI 2011 + +[5] Li et al, 'Differentiable Monte Carlo Ray Tracing through Edge Sampling', SIGGRAPH Asia 2018 + +[6] Yifan et al, 'Differentiable Surface Splatting for Point-based Geometry Processing', SIGGRAPH Asia 2019 + +[7] Loubet et al, 'Reparameterizing Discontinuous Integrands for Differentiable Rendering', SIGGRAPH Asia 2019 + +[8] Chen et al, 'Learning to Predict 3D Objects with an Interpolation-based Differentiable Renderer', NeurIPS 2019 diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/renderer_getting_started.md b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/renderer_getting_started.md new file mode 100644 index 0000000000000000000000000000000000000000..21a480a9444b8f1312a79c73a7289d108aeef358 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/renderer_getting_started.md @@ -0,0 +1,147 @@ +--- +hide_title: true +sidebar_label: Getting Started +--- + +# Getting Started With Renderer + +### Architecture Overview + +The renderer is designed to be modular, extensible and support batching and gradients for all inputs. The following figure describes all the components of the rendering pipeline. + + + +##### Fragments + +The **rasterizer** returns 4 output tensors in a named tuple. + +- **`pix_to_face`**: LongTensor of shape `(N, image_size, image_size, faces_per_pixel)` specifying the indices of the faces (in the packed faces) which overlap each pixel in the image. +- **`zbuf`**: FloatTensor of shape `(N, image_size, image_size, faces_per_pixel)` giving the z-coordinates of the nearest faces at each pixel in world coordinates, sorted in ascending z-order. +- **`bary_coords`**: FloatTensor of shape `(N, image_size, image_size, faces_per_pixel, 3)` + giving the barycentric coordinates in NDC units of the nearest faces at each pixel, sorted in ascending z-order. +- **`pix_dists`**: FloatTensor of shape `(N, image_size, image_size, faces_per_pixel)` giving the signed Euclidean distance (in NDC units) in the x/y plane of each point closest to the pixel. + + +See the renderer API reference for more details about each component in the pipeline. + +--- + +**NOTE:** + +The differentiable renderer API is experimental and subject to change!. + +--- + +### Coordinate transformation conventions + +Rendering requires transformations between several different coordinate frames: world space, view/camera space, NDC space and screen space. At each step it is important to know where the camera is located, how the +X, +Y, +Z axes are aligned and the possible range of values. The following figure outlines the conventions used PyTorch3D. + + + + +For example, given a teapot mesh, the world coordinate frame, camera coordinate frame and image are shown in the figure below. Note that the world and camera coordinate frames have the +z direction pointing in to the page. + + + +--- + +**NOTE: PyTorch3D vs OpenGL** + +While we tried to emulate several aspects of OpenGL, there are differences in the coordinate frame conventions. +- The default world coordinate frame in PyTorch3D has +Z pointing in to the screen whereas in OpenGL, +Z is pointing out of the screen. Both are right handed. +- The NDC coordinate system in PyTorch3D is **right-handed** compared with a **left-handed** NDC coordinate system in OpenGL (the projection matrix switches the handedness). + + + +--- + +### Rasterizing Non Square Images + +To rasterize an image where H != W, you can specify the `image_size` in the `RasterizationSettings` as a tuple of (H, W). + +The aspect ratio needs special consideration. There are two aspect ratios to be aware of: + - the aspect ratio of each pixel + - the aspect ratio of the output image +In the cameras e.g. `FoVPerspectiveCameras`, the `aspect_ratio` argument can be used to set the pixel aspect ratio. In the rasterizer, we assume square pixels, but variable image aspect ratio (i.e rectangle images). + +In most cases you will want to set the camera aspect ratio to 1.0 (i.e. square pixels) and only vary the `image_size` in the `RasterizationSettings`(i.e. the output image dimensions in pixels). + +--- + +### The pulsar backend + +Since v0.3, [pulsar](https://arxiv.org/abs/2004.07484) can be used as a backend for point-rendering. It has a focus on efficiency, which comes with pros and cons: it is highly optimized and all rendering stages are integrated in the CUDA kernels. This leads to significantly higher speed and better scaling behavior. We use it at Facebook Reality Labs to render and optimize scenes with millions of spheres in resolutions up to 4K. You can find a runtime comparison plot below (settings: `bin_size=None`, `points_per_pixel=5`, `image_size=1024`, `radius=1e-2`, `composite_params.radius=1e-4`; benchmarked on an RTX 2070 GPU). + + + +Pulsar's processing steps are tightly integrated CUDA kernels and do not work with custom `rasterizer` and `compositor` components. We provide two ways to use Pulsar: (1) there is a unified interface to match the PyTorch3D calling convention seamlessly. This is, for example, illustrated in the [point cloud tutorial](https://github.com/facebookresearch/pytorch3d/blob/main/docs/tutorials/render_colored_points.ipynb). (2) There is a direct interface available to the pulsar backend, which exposes the full functionality of the backend (including opacity, which is not yet available in PyTorch3D). Examples showing its use as well as the matching PyTorch3D interface code are available in [this folder](https://github.com/facebookresearch/pytorch3d/tree/master/docs/examples). + +--- + +### Texturing options + +For mesh texturing we offer several options (in `pytorch3d/renderer/mesh/texturing.py`): + +1. **Vertex Textures**: D dimensional textures for each vertex (for example an RGB color) which can be interpolated across the face. This can be represented as an `(N, V, D)` tensor. This is a fairly simple representation though and cannot model complex textures if the mesh faces are large. +2. **UV Textures**: vertex UV coordinates and **one** texture map for the whole mesh. For a point on a face with given barycentric coordinates, the face color can be computed by interpolating the vertex uv coordinates and then sampling from the texture map. This representation requires two tensors (UVs: `(N, V, 2), Texture map: `(N, H, W, 3)`), and is limited to only support one texture map per mesh. +3. **Face Textures**: In more complex cases such as ShapeNet meshes, there are multiple texture maps per mesh and some faces have texture while other do not. For these cases, a more flexible representation is a texture atlas, where each face is represented as an `(RxR)` texture map where R is the texture resolution. For a given point on the face, the texture value can be sampled from the per face texture map using the barycentric coordinates of the point. This representation requires one tensor of shape `(N, F, R, R, 3)`. This texturing method is inspired by the SoftRasterizer implementation. For more details refer to the [`make_material_atlas`](https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/io/mtl_io.py#L123) and [`sample_textures`](https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/renderer/mesh/textures.py#L452) functions. **NOTE:**: The `TexturesAtlas` texture sampling is only differentiable with respect to the texture atlas but not differentiable with respect to the barycentric coordinates. + + + + +--- + +### A simple renderer + +A renderer in PyTorch3D is composed of a **rasterizer** and a **shader**. Create a renderer in a few simple steps: + +``` +# Imports +from pytorch3d.renderer import ( + FoVPerspectiveCameras, look_at_view_transform, + RasterizationSettings, BlendParams, + MeshRenderer, MeshRasterizer, HardPhongShader +) + +# Initialize an OpenGL perspective camera. +R, T = look_at_view_transform(2.7, 10, 20) +cameras = FoVPerspectiveCameras(device=device, R=R, T=T) + +# Define the settings for rasterization and shading. Here we set the output image to be of size +# 512x512. As we are rendering images for visualization purposes only we will set faces_per_pixel=1 +# and blur_radius=0.0. Refer to rasterize_meshes.py for explanations of these parameters. +raster_settings = RasterizationSettings( + image_size=512, + blur_radius=0.0, + faces_per_pixel=1, +) + +# Create a Phong renderer by composing a rasterizer and a shader. Here we can use a predefined +# PhongShader, passing in the device on which to initialize the default parameters +renderer = MeshRenderer( + rasterizer=MeshRasterizer(cameras=cameras, raster_settings=raster_settings), + shader=HardPhongShader(device=device, cameras=cameras) +) +``` + +--- + +### A custom shader + +Shaders are the most flexible part of the PyTorch3D rendering API. We have created some examples of shaders in `shaders.py` but this is a non exhaustive set. + +A shader can incorporate several steps: +- **texturing** (e.g interpolation of vertex RGB colors or interpolation of vertex UV coordinates followed by sampling from a texture map (interpolation uses barycentric coordinates output from rasterization)) +- **lighting/shading** (e.g. ambient, diffuse, specular lighting, Phong, Gouraud, Flat) +- **blending** (e.g. hard blending using only the closest face for each pixel, or soft blending using a weighted sum of the top K faces per pixel) + + We have examples of several combinations of these functions based on the texturing/shading/blending support we have currently. These are summarised in this table below. Many other combinations are possible and we plan to expand the options available for texturing, shading and blending. + +|Example Shaders | Vertex Textures| UV Textures | Textures Atlas | Flat Shading| Gouraud Shading| Phong Shading | Hard blending | Soft Blending | +| ------------- |:-------------: | :--------------:| :--------------:| :--------------:| :--------------:| :--------------:|:--------------:|:--------------:| +| HardPhongShader | ✔️ |✔️|✔️||| ✔️ | ✔️|| +| SoftPhongShader | ✔️ |✔️|✔️||| ✔️ | | ✔️| +| HardGouraudShader | ✔️ |✔️|✔️|| ✔️ || ✔️|| +| SoftGouraudShader | ✔️ |✔️|✔️|| ✔️ ||| ✔️| +| HardFlatShader | ✔️ |✔️|✔️| ✔️ ||| ✔️|| +| SoftSilhouetteShader |||||||| ✔️| diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/visualization.md b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/visualization.md new file mode 100644 index 0000000000000000000000000000000000000000..71aa51654f85882d70bcc8eaf90f1920e145c1e1 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/visualization.md @@ -0,0 +1,27 @@ +--- +hide_title: true +sidebar_label: Plotly Visualization +--- + +# Overview + +PyTorch3D provides a modular differentiable renderer, but for instances where we want interactive plots or are not concerned with the differentiability of the rendering process, we provide [functions to render meshes and pointclouds in plotly](https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/vis/plotly_vis.py). These plotly figures allow you to rotate and zoom the rendered images and support plotting batched data as multiple traces in a singular plot or divided into individual subplots. + + +# Examples + +These rendering functions accept plotly x,y, and z axis arguments as `kwargs`, allowing us to customize the plots. Here are two plots with colored axes, a [Pointclouds plot](assets/plotly_pointclouds.png), a [batched Meshes plot in subplots](assets/plotly_meshes_batch.png), and a [batched Meshes plot with multiple traces](assets/plotly_meshes_trace.png). Refer to the [render textured meshes](https://pytorch3d.org/tutorials/render_textured_meshes) and [render colored pointclouds](https://pytorch3d.org/tutorials/render_colored_points) tutorials for code examples. + +# Saving plots to images + +If you want to save these plotly plots, you will need to install a separate library such as [Kaleido](https://plotly.com/python/static-image-export/). + +Install Kaleido +``` +$ pip install Kaleido +``` +Export a figure as a .png image. The image will be saved in the current working directory. +``` +fig = ... +fig.write_image("image_name.png") +``` diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/why_pytorch3d.md b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/why_pytorch3d.md new file mode 100644 index 0000000000000000000000000000000000000000..6d11e65987e58966ae08fd0edd5367081c391298 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/docs/notes/why_pytorch3d.md @@ -0,0 +1,12 @@ +--- +hide_title: true +sidebar_label: Why PyTorch3D +--- + + +# Why PyTorch3D + + +Our goal with PyTorch3D is to help accelerate research at the intersection of deep learning and 3D. 3D data is more complex than 2D images and while working on projects such as [Mesh R-CNN](https://github.com/facebookresearch/meshrcnn) and [C3DPO](https://github.com/facebookresearch/c3dpo_nrsfm), we encountered several challenges including 3D data representation, batching, and speed. We have developed many useful operators and abstractions for working on 3D deep learning and want to share this with the community to drive novel research in this area. + +In PyTorch3D we have included efficient 3D operators, heterogeneous batching capabilities, and a modular differentiable rendering API, to equip researchers in this field with a much needed toolkit to implement cutting-edge research with complex 3D inputs. diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/pytorch3d/ops/marching_cubes.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/pytorch3d/ops/marching_cubes.py new file mode 100644 index 0000000000000000000000000000000000000000..17236857d607a17270120606288451f51cb999a7 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/pytorch3d/ops/marching_cubes.py @@ -0,0 +1,305 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +# pyre-unsafe + +from typing import List, Optional, Tuple + +import torch +from pytorch3d import _C +from pytorch3d.ops.marching_cubes_data import EDGE_TO_VERTICES, FACE_TABLE, INDEX +from pytorch3d.transforms import Translate +from torch.autograd import Function + + +EPS = 0.00001 + + +class Cube: + def __init__( + self, + bfl_v: Tuple[int, int, int], + volume: torch.Tensor, + isolevel: float, + ) -> None: + """ + Initializes a cube given the bottom front left vertex coordinate + and computes the cube configuration given vertex values and isolevel. + + Edge and vertex convention: + + v4_______e4____________v5 + /| /| + / | / | + e7/ | e5/ | + /___|______e6_________/ | + v7| | |v6 |e9 + | | | | + | |e8 |e10| + e11| | | | + | |______e0_________|___| + | / v0(bfl_v) | |v1 + | / | / + | /e3 | /e1 + |/_____________________|/ + v3 e2 v2 + + Args: + bfl_vertex: a tuple of size 3 corresponding to the bottom front left vertex + of the cube in (x, y, z) format + volume: the 3D scalar data + isolevel: the isosurface value used as a threshold for determining whether a point + is inside/outside the volume + """ + x, y, z = bfl_v + self.x, self.y, self.z = x, y, z + self.bfl_v = bfl_v + self.verts = [ + [x + (v & 1), y + (v >> 1 & 1), z + (v >> 2 & 1)] for v in range(8) + ] # vertex position (x, y, z) for v0-v1-v4-v5-v3-v2-v7-v6 + + # Calculates cube configuration index given values of the cube vertices + self.cube_index = 0 + for i in range(8): + v = self.verts[INDEX[i]] + value = volume[v[2]][v[1]][v[0]] + if value < isolevel: + self.cube_index |= 1 << i + + def get_vpair_from_edge(self, edge: int, W: int, H: int) -> Tuple[int, int]: + """ + Get a tuple of global vertex ID from a local edge ID + Global vertex ID is calculated as (x + dx) + (y + dy) * W + (z + dz) * W * H + + Args: + edge: local edge ID in the cube + bfl_vertex: bottom-front-left coordinate of the cube + + Returns: + a pair of global vertex ID + """ + v1, v2 = EDGE_TO_VERTICES[edge] # two end-points on the edge + v1_id = self.verts[v1][0] + self.verts[v1][1] * W + self.verts[v1][2] * W * H + v2_id = self.verts[v2][0] + self.verts[v2][1] * W + self.verts[v2][2] * W * H + return (v1_id, v2_id) + + def vert_interp( + self, + isolevel: float, + edge: int, + vol: torch.Tensor, + ) -> List: + """ + Linearly interpolate a vertex where an isosurface cuts an edge + between the two endpoint vertices, based on their values + + Args: + isolevel: the isosurface value to use as the threshold to determine + whether points are within a volume. + edge: edge (ID) to interpolate + cube: current cube vertices + vol: 3D scalar field + + Returns: + interpolated vertex: position of the interpolated vertex on the edge + """ + v1, v2 = EDGE_TO_VERTICES[edge] + p1, p2 = self.verts[v1], self.verts[v2] + val1, val2 = ( + vol[p1[2]][p1[1]][p1[0]], + vol[p2[2]][p2[1]][p2[0]], + ) + point = None + if abs(isolevel - val1) < EPS: + point = p1 + elif abs(isolevel - val2) < EPS: + point = p2 + elif abs(val1 - val2) < EPS: + point = p1 + + if point is None: + mu = (isolevel - val1) / (val2 - val1) + x1, y1, z1 = p1 + x2, y2, z2 = p2 + x = x1 + mu * (x2 - x1) + y = y1 + mu * (y2 - y1) + z = z1 + mu * (z2 - z1) + else: + x, y, z = point + return [x, y, z] + + +def marching_cubes_naive( + vol_batch: torch.Tensor, + isolevel: Optional[float] = None, + return_local_coords: bool = True, +) -> Tuple[List[torch.Tensor], List[torch.Tensor]]: + """ + Runs the classic marching cubes algorithm, iterating over + the coordinates of the volume and using a given isolevel + for determining intersected edges of cubes. + Returns vertices and faces of the obtained mesh. + This operation is non-differentiable. + + Args: + vol_batch: a Tensor of size (N, D, H, W) corresponding to + a batch of 3D scalar fields + isolevel: the isosurface value to use as the threshold to determine + whether points are within a volume. If None, then the average of the + maximum and minimum value of the scalar field will be used. + return_local_coords: bool. If True the output vertices will be in local coordinates in + the range [-1, 1] x [-1, 1] x [-1, 1]. If False they will be in the range + [0, W-1] x [0, H-1] x [0, D-1] + Returns: + verts: [{V_0}, {V_1}, ...] List of N sets of vertices of shape (|V_i|, 3) in FloatTensor + faces: [{F_0}, {F_1}, ...] List of N sets of faces of shape (|F_i|, 3) in LongTensors + """ + batched_verts, batched_faces = [], [] + D, H, W = vol_batch.shape[1:] + + # each edge is represented with its two endpoints (represented with global id) + for i in range(len(vol_batch)): + vol = vol_batch[i] + thresh = ((vol.max() + vol.min()) / 2).item() if isolevel is None else isolevel + vpair_to_edge = {} # maps from tuple of edge endpoints to edge_id + edge_id_to_v = {} # maps from edge ID to vertex position + uniq_edge_id = {} # unique edge IDs + verts = [] # store vertex positions + faces = [] # store face indices + # enumerate each cell in the 3d grid + for z in range(0, D - 1): + for y in range(0, H - 1): + for x in range(0, W - 1): + cube = Cube((x, y, z), vol, thresh) + edge_indices = FACE_TABLE[cube.cube_index] + # cube is entirely in/out of the surface + if len(edge_indices) == 0: + continue + + # gather mesh vertices/faces by processing each cube + interp_points = [[0.0, 0.0, 0.0]] * 12 + # triangle vertex IDs and positions + tri = [] + ps = [] + for i, edge in enumerate(edge_indices): + interp_points[edge] = cube.vert_interp(thresh, edge, vol) + + # Bind interpolated vertex with a global edge_id, which + # is represented by a pair of vertex ids (v1_id, v2_id) + # corresponding to a local edge. + (v1_id, v2_id) = cube.get_vpair_from_edge(edge, W, H) + edge_id = vpair_to_edge.setdefault( + (v1_id, v2_id), len(vpair_to_edge) + ) + tri.append(edge_id) + ps.append(interp_points[edge]) + # when the isolevel are the same as the edge endpoints, the interploated + # vertices can share the same values, and lead to degenerate triangles. + if ( + (i + 1) % 3 == 0 + and ps[0] != ps[1] + and ps[1] != ps[2] + and ps[2] != ps[0] + ): + for j, edge_id in enumerate(tri): + edge_id_to_v[edge_id] = ps[j] + if edge_id not in uniq_edge_id: + uniq_edge_id[edge_id] = len(verts) + verts.append(edge_id_to_v[edge_id]) + faces.append([uniq_edge_id[tri[j]] for j in range(3)]) + tri = [] + ps = [] + + if len(faces) > 0 and len(verts) > 0: + verts = torch.tensor(verts, dtype=vol.dtype) + # Convert from world coordinates ([0, D-1], [0, H-1], [0, W-1]) to + # local coordinates in the range [-1, 1] + if return_local_coords: + verts = ( + Translate(x=+1.0, y=+1.0, z=+1.0, device=vol_batch.device) + .scale((vol_batch.new_tensor([W, H, D])[None] - 1) * 0.5) + .inverse() + ).transform_points(verts[None])[0] + batched_verts.append(verts) + batched_faces.append(torch.tensor(faces, dtype=torch.int64)) + else: + batched_verts.append([]) + batched_faces.append([]) + return batched_verts, batched_faces + + +######################################## +# Marching Cubes Implementation in C++/Cuda +######################################## +class _marching_cubes(Function): + """ + Torch Function wrapper for marching_cubes implementation. + This function is not differentiable. An autograd wrapper is used + to ensure an error if user tries to get gradients. + """ + + @staticmethod + def forward(ctx, vol, isolevel): + verts, faces, ids = _C.marching_cubes(vol, isolevel) + return verts, faces, ids + + @staticmethod + def backward(ctx, grad_verts, grad_faces): + raise ValueError("marching_cubes backward is not supported") + + +def marching_cubes( + vol_batch: torch.Tensor, + isolevel: Optional[float] = None, + return_local_coords: bool = True, +) -> Tuple[List[torch.Tensor], List[torch.Tensor]]: + """ + Run marching cubes over a volume scalar field with a designated isolevel. + Returns vertices and faces of the obtained mesh. + This operation is non-differentiable. + + Args: + vol_batch: a Tensor of size (N, D, H, W) corresponding to + a batch of 3D scalar fields + isolevel: float used as threshold to determine if a point is inside/outside + the volume. If None, then the average of the maximum and minimum value + of the scalar field is used. + return_local_coords: bool. If True the output vertices will be in local coordinates in + the range [-1, 1] x [-1, 1] x [-1, 1]. If False they will be in the range + [0, W-1] x [0, H-1] x [0, D-1] + + Returns: + verts: [{V_0}, {V_1}, ...] List of N sets of vertices of shape (|V_i|, 3) in FloatTensor + faces: [{F_0}, {F_1}, ...] List of N sets of faces of shape (|F_i|, 3) in LongTensors + """ + batched_verts, batched_faces = [], [] + D, H, W = vol_batch.shape[1:] + for i in range(len(vol_batch)): + vol = vol_batch[i] + thresh = ((vol.max() + vol.min()) / 2).item() if isolevel is None else isolevel + verts, faces, ids = _marching_cubes.apply(vol, thresh) + if len(faces) > 0 and len(verts) > 0: + # Convert from world coordinates ([0, D-1], [0, H-1], [0, W-1]) to + # local coordinates in the range [-1, 1] + if return_local_coords: + verts = ( + Translate(x=+1.0, y=+1.0, z=+1.0, device=vol.device) + .scale((vol.new_tensor([W, H, D])[None] - 1) * 0.5) + .inverse() + ).transform_points(verts[None])[0] + # deduplication for cuda + if vol.is_cuda: + unique_ids, inverse_idx = torch.unique(ids, return_inverse=True) + verts_ = verts.new_zeros(unique_ids.shape[0], 3) + verts_[inverse_idx] = verts + verts = verts_ + faces = inverse_idx[faces] + batched_verts.append(verts) + batched_faces.append(faces) + else: + batched_verts.append([]) + batched_faces.append([]) + return batched_verts, batched_faces diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/pytorch3d/ops/marching_cubes_data.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/pytorch3d/ops/marching_cubes_data.py new file mode 100644 index 0000000000000000000000000000000000000000..802377e0795a980ca539e554d40ecd11ef4b3902 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/pytorch3d/ops/marching_cubes_data.py @@ -0,0 +1,291 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +# pyre-unsafe + + +# Maps each edge (by index) to the corresponding cube vertices +EDGE_TO_VERTICES = [ + [0, 1], + [1, 5], + [4, 5], + [0, 4], + [2, 3], + [3, 7], + [6, 7], + [2, 6], + [0, 2], + [1, 3], + [5, 7], + [4, 6], +] + +# A list of lists mapping a cube_index (a given configuration) +# to a list of faces corresponding to that configuration. Each face is represented +# by 3 consecutive numbers. A configuration will at most have 5 faces. +# +# Table taken from http://paulbourke.net/geometry/polygonise/ +FACE_TABLE = [ + [], + [0, 8, 3], + [0, 1, 9], + [1, 8, 3, 9, 8, 1], + [1, 2, 10], + [0, 8, 3, 1, 2, 10], + [9, 2, 10, 0, 2, 9], + [2, 8, 3, 2, 10, 8, 10, 9, 8], + [3, 11, 2], + [0, 11, 2, 8, 11, 0], + [1, 9, 0, 2, 3, 11], + [1, 11, 2, 1, 9, 11, 9, 8, 11], + [3, 10, 1, 11, 10, 3], + [0, 10, 1, 0, 8, 10, 8, 11, 10], + [3, 9, 0, 3, 11, 9, 11, 10, 9], + [9, 8, 10, 10, 8, 11], + [4, 7, 8], + [4, 3, 0, 7, 3, 4], + [0, 1, 9, 8, 4, 7], + [4, 1, 9, 4, 7, 1, 7, 3, 1], + [1, 2, 10, 8, 4, 7], + [3, 4, 7, 3, 0, 4, 1, 2, 10], + [9, 2, 10, 9, 0, 2, 8, 4, 7], + [2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4], + [8, 4, 7, 3, 11, 2], + [11, 4, 7, 11, 2, 4, 2, 0, 4], + [9, 0, 1, 8, 4, 7, 2, 3, 11], + [4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1], + [3, 10, 1, 3, 11, 10, 7, 8, 4], + [1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4], + [4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3], + [4, 7, 11, 4, 11, 9, 9, 11, 10], + [9, 5, 4], + [9, 5, 4, 0, 8, 3], + [0, 5, 4, 1, 5, 0], + [8, 5, 4, 8, 3, 5, 3, 1, 5], + [1, 2, 10, 9, 5, 4], + [3, 0, 8, 1, 2, 10, 4, 9, 5], + [5, 2, 10, 5, 4, 2, 4, 0, 2], + [2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8], + [9, 5, 4, 2, 3, 11], + [0, 11, 2, 0, 8, 11, 4, 9, 5], + [0, 5, 4, 0, 1, 5, 2, 3, 11], + [2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5], + [10, 3, 11, 10, 1, 3, 9, 5, 4], + [4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10], + [5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3], + [5, 4, 8, 5, 8, 10, 10, 8, 11], + [9, 7, 8, 5, 7, 9], + [9, 3, 0, 9, 5, 3, 5, 7, 3], + [0, 7, 8, 0, 1, 7, 1, 5, 7], + [1, 5, 3, 3, 5, 7], + [9, 7, 8, 9, 5, 7, 10, 1, 2], + [10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3], + [8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2], + [2, 10, 5, 2, 5, 3, 3, 5, 7], + [7, 9, 5, 7, 8, 9, 3, 11, 2], + [9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11], + [2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7], + [11, 2, 1, 11, 1, 7, 7, 1, 5], + [9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11], + [5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0], + [11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0], + [11, 10, 5, 7, 11, 5], + [10, 6, 5], + [0, 8, 3, 5, 10, 6], + [9, 0, 1, 5, 10, 6], + [1, 8, 3, 1, 9, 8, 5, 10, 6], + [1, 6, 5, 2, 6, 1], + [1, 6, 5, 1, 2, 6, 3, 0, 8], + [9, 6, 5, 9, 0, 6, 0, 2, 6], + [5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8], + [2, 3, 11, 10, 6, 5], + [11, 0, 8, 11, 2, 0, 10, 6, 5], + [0, 1, 9, 2, 3, 11, 5, 10, 6], + [5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11], + [6, 3, 11, 6, 5, 3, 5, 1, 3], + [0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6], + [3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9], + [6, 5, 9, 6, 9, 11, 11, 9, 8], + [5, 10, 6, 4, 7, 8], + [4, 3, 0, 4, 7, 3, 6, 5, 10], + [1, 9, 0, 5, 10, 6, 8, 4, 7], + [10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4], + [6, 1, 2, 6, 5, 1, 4, 7, 8], + [1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7], + [8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6], + [7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9], + [3, 11, 2, 7, 8, 4, 10, 6, 5], + [5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11], + [0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6], + [9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6], + [8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6], + [5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11], + [0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7], + [6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9], + [10, 4, 9, 6, 4, 10], + [4, 10, 6, 4, 9, 10, 0, 8, 3], + [10, 0, 1, 10, 6, 0, 6, 4, 0], + [8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10], + [1, 4, 9, 1, 2, 4, 2, 6, 4], + [3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4], + [0, 2, 4, 4, 2, 6], + [8, 3, 2, 8, 2, 4, 4, 2, 6], + [10, 4, 9, 10, 6, 4, 11, 2, 3], + [0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6], + [3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10], + [6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1], + [9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3], + [8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1], + [3, 11, 6, 3, 6, 0, 0, 6, 4], + [6, 4, 8, 11, 6, 8], + [7, 10, 6, 7, 8, 10, 8, 9, 10], + [0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10], + [10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0], + [10, 6, 7, 10, 7, 1, 1, 7, 3], + [1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7], + [2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9], + [7, 8, 0, 7, 0, 6, 6, 0, 2], + [7, 3, 2, 6, 7, 2], + [2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7], + [2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7], + [1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11], + [11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1], + [8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6], + [0, 9, 1, 11, 6, 7], + [7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0], + [7, 11, 6], + [7, 6, 11], + [3, 0, 8, 11, 7, 6], + [0, 1, 9, 11, 7, 6], + [8, 1, 9, 8, 3, 1, 11, 7, 6], + [10, 1, 2, 6, 11, 7], + [1, 2, 10, 3, 0, 8, 6, 11, 7], + [2, 9, 0, 2, 10, 9, 6, 11, 7], + [6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8], + [7, 2, 3, 6, 2, 7], + [7, 0, 8, 7, 6, 0, 6, 2, 0], + [2, 7, 6, 2, 3, 7, 0, 1, 9], + [1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6], + [10, 7, 6, 10, 1, 7, 1, 3, 7], + [10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8], + [0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7], + [7, 6, 10, 7, 10, 8, 8, 10, 9], + [6, 8, 4, 11, 8, 6], + [3, 6, 11, 3, 0, 6, 0, 4, 6], + [8, 6, 11, 8, 4, 6, 9, 0, 1], + [9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6], + [6, 8, 4, 6, 11, 8, 2, 10, 1], + [1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6], + [4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9], + [10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3], + [8, 2, 3, 8, 4, 2, 4, 6, 2], + [0, 4, 2, 4, 6, 2], + [1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8], + [1, 9, 4, 1, 4, 2, 2, 4, 6], + [8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1], + [10, 1, 0, 10, 0, 6, 6, 0, 4], + [4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3], + [10, 9, 4, 6, 10, 4], + [4, 9, 5, 7, 6, 11], + [0, 8, 3, 4, 9, 5, 11, 7, 6], + [5, 0, 1, 5, 4, 0, 7, 6, 11], + [11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5], + [9, 5, 4, 10, 1, 2, 7, 6, 11], + [6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5], + [7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2], + [3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6], + [7, 2, 3, 7, 6, 2, 5, 4, 9], + [9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7], + [3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0], + [6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8], + [9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7], + [1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4], + [4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10], + [7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10], + [6, 9, 5, 6, 11, 9, 11, 8, 9], + [3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5], + [0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11], + [6, 11, 3, 6, 3, 5, 5, 3, 1], + [1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6], + [0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10], + [11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5], + [6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3], + [5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2], + [9, 5, 6, 9, 6, 0, 0, 6, 2], + [1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8], + [1, 5, 6, 2, 1, 6], + [1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6], + [10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0], + [0, 3, 8, 5, 6, 10], + [10, 5, 6], + [11, 5, 10, 7, 5, 11], + [11, 5, 10, 11, 7, 5, 8, 3, 0], + [5, 11, 7, 5, 10, 11, 1, 9, 0], + [10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1], + [11, 1, 2, 11, 7, 1, 7, 5, 1], + [0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11], + [9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7], + [7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2], + [2, 5, 10, 2, 3, 5, 3, 7, 5], + [8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5], + [9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2], + [9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2], + [1, 3, 5, 3, 7, 5], + [0, 8, 7, 0, 7, 1, 1, 7, 5], + [9, 0, 3, 9, 3, 5, 5, 3, 7], + [9, 8, 7, 5, 9, 7], + [5, 8, 4, 5, 10, 8, 10, 11, 8], + [5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0], + [0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5], + [10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4], + [2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8], + [0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11], + [0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5], + [9, 4, 5, 2, 11, 3], + [2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4], + [5, 10, 2, 5, 2, 4, 4, 2, 0], + [3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9], + [5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2], + [8, 4, 5, 8, 5, 3, 3, 5, 1], + [0, 4, 5, 1, 0, 5], + [8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5], + [9, 4, 5], + [4, 11, 7, 4, 9, 11, 9, 10, 11], + [0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11], + [1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11], + [3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4], + [4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2], + [9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3], + [11, 7, 4, 11, 4, 2, 2, 4, 0], + [11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4], + [2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9], + [9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7], + [3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10], + [1, 10, 2, 8, 7, 4], + [4, 9, 1, 4, 1, 7, 7, 1, 3], + [4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1], + [4, 0, 3, 7, 4, 3], + [4, 8, 7], + [9, 10, 8, 10, 11, 8], + [3, 0, 9, 3, 9, 11, 11, 9, 10], + [0, 1, 10, 0, 10, 8, 8, 10, 11], + [3, 1, 10, 11, 3, 10], + [1, 2, 11, 1, 11, 9, 9, 11, 8], + [3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9], + [0, 2, 11, 8, 0, 11], + [3, 2, 11], + [2, 3, 8, 2, 8, 10, 10, 8, 9], + [9, 10, 2, 0, 9, 2], + [2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8], + [1, 10, 2], + [1, 3, 8, 9, 1, 8], + [0, 9, 1], + [0, 3, 8], + [], +] + +# mapping from 0-7 to v0-v7 in cube.vertices +INDEX = [0, 1, 5, 4, 2, 3, 7, 6] diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/common_resources.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/common_resources.py new file mode 100644 index 0000000000000000000000000000000000000000..d8da89f62aefc3f586a86456b0891e09a9fe14fe --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/common_resources.py @@ -0,0 +1,161 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import contextlib +import logging +import os +import tempfile +import unittest +from pathlib import Path +from typing import Generator, Tuple +from zipfile import ZipFile + +from iopath.common.file_io import PathManager + + +CO3D_MANIFOLD_PATH: str = "manifold://co3d/tree/extracted" +CO3DV2_MANIFOLD_PATH: str = "manifold://co3d/tree/v2/extracted" + +INSIDE_RE_WORKER: bool = os.environ.get("INSIDE_RE_WORKER", False) + + +def get_path_manager(silence_logs: bool = False) -> PathManager: + """ + Returns a path manager which can access manifold internally. + + Args: + silence_logs: Whether to reduce log output from iopath library. + """ + if silence_logs: + logging.getLogger("iopath.fb.manifold").setLevel(logging.CRITICAL) + logging.getLogger("iopath.common.file_io").setLevel(logging.CRITICAL) + + if INSIDE_RE_WORKER: + raise ValueError("Cannot get to manifold from RE") + + path_manager = PathManager() + + if os.environ.get("FB_TEST", False): + from iopath.fb.manifold import ManifoldPathHandler + + path_manager.register_handler(ManifoldPathHandler()) + + return path_manager + + +@contextlib.contextmanager +def get_skateboard_data( + avoid_manifold: bool = False, silence_logs: bool = False +) -> Generator[Tuple[str, PathManager], None, None]: + """ + Context manager for accessing Co3D dataset by tests, at least for + the first 5 skateboards. Internally, we want this to exercise the + normal way to access the data directly manifold, but on an RE + worker this is impossible so we use a workaround. + + Args: + avoid_manifold: Use the method used by RE workers even locally. + silence_logs: Whether to reduce log output from iopath library. + + Yields: + dataset_root: (str) path to dataset root. + path_manager: path_manager to access it with. + """ + if silence_logs: + logging.getLogger("iopath.fb.manifold").setLevel(logging.CRITICAL) + logging.getLogger("iopath.common.file_io").setLevel(logging.CRITICAL) + + if not os.environ.get("FB_TEST", False): + if os.getenv("FAIR_ENV_CLUSTER", "") == "": + raise unittest.SkipTest("Unknown environment. Data not available.") + yield "/datasets01/co3d/081922", PathManager() + + elif avoid_manifold or INSIDE_RE_WORKER: + from libfb.py.parutil import get_file_path + + par_path = "skateboard_first_5" + source = get_file_path(par_path) + assert Path(source).is_file() + with tempfile.TemporaryDirectory() as dest: + with ZipFile(source) as f: + f.extractall(dest) + yield os.path.join(dest, "extracted"), PathManager() + else: + yield CO3D_MANIFOLD_PATH, get_path_manager() + + +def _provide_torchvision_weights(par_path: str, filename: str) -> None: + """ + Ensure the weights files are available for a torchvision model. + """ + # In OSS, torchvision looks for vgg16 weights in + # https://download.pytorch.org/models/vgg16-397923af.pth + # Inside fbcode, this is replaced by asking iopath for + # manifold://torchvision/tree/models/vgg16-397923af.pth + # (the code for this replacement is in + # fbcode/pytorch/vision/fb/_internally_replaced_utils.py ) + # + # iopath does this by looking for the file at the cache location + # and if it is not there getting it from manifold. + # (the code for this is in + # fbcode/fair_infra/data/iopath/iopath/fb/manifold.py ) + # + # On the remote execution worker, manifold is inaccessible. + # We solve this by making the cached file available before iopath + # looks. + # + # By default the cache location is + # ~/.torch/iopath_cache/manifold_cache/tree/models/vgg16-397923af.pth + # But we can't write to the home directory on the RE worker. + # We define FVCORE_CACHE to change the cache location to + # iopath_cache/manifold_cache/tree/models/vgg16-397923af.pth + # (Without it, manifold caches in unstable temporary locations on RE.) + # + # The file we want has been copied from + # tree/models/vgg16-397923af.pth in the torchvision bucket + # to + # tree/testing/vgg16-397923af.pth in the co3d bucket + # and the TARGETS file copies it somewhere in the PAR which we + # recover with get_file_path. + # (It can't copy straight to a nested location, see + # https://fb.workplace.com/groups/askbuck/posts/2644615728920359/) + # Here we symlink it to the new cache location. + if INSIDE_RE_WORKER: + from libfb.py.parutil import get_file_path + + os.environ["FVCORE_CACHE"] = "iopath_cache" + + source = Path(get_file_path(par_path)) + assert source.is_file() + + dest = Path("iopath_cache/manifold_cache/tree/models") + if not dest.exists(): + dest.mkdir(parents=True) + + if not (dest / filename).is_symlink(): + try: + (dest / filename).symlink_to(source) + except FileExistsError: + print("FileExistsError: no symlink created.") + + +def provide_lpips_vgg() -> None: + """ + Ensure the weights files are available for lpips.LPIPS(net="vgg") + to be called. Specifically, torchvision's vgg16. + """ + _provide_torchvision_weights("vgg_weights_for_lpips", "vgg16-397923af.pth") + + +def provide_resnet34() -> None: + """ + Ensure the weights files are available for + + torchvision.models.resnet34(pretrained=True) + + to be called. + """ + _provide_torchvision_weights("resnet34_weights", "resnet34-b627a593.pth") diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/data/data_source.yaml b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/data/data_source.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a444309cd99bf7300d07f9d39b37cc800105ecbf --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/data/data_source.yaml @@ -0,0 +1,131 @@ +dataset_map_provider_class_type: ??? +data_loader_map_provider_class_type: SequenceDataLoaderMapProvider +dataset_map_provider_BlenderDatasetMapProvider_args: + base_dir: ??? + object_name: ??? + path_manager_factory_class_type: PathManagerFactory + n_known_frames_for_test: null + path_manager_factory_PathManagerFactory_args: + silence_logs: true +dataset_map_provider_JsonIndexDatasetMapProvider_args: + category: ??? + task_str: singlesequence + dataset_root: '' + n_frames_per_sequence: -1 + test_on_train: false + restrict_sequence_name: [] + test_restrict_sequence_id: -1 + assert_single_seq: false + only_test_set: false + dataset_class_type: JsonIndexDataset + path_manager_factory_class_type: PathManagerFactory + dataset_JsonIndexDataset_args: + limit_to: 0 + limit_sequences_to: 0 + exclude_sequence: [] + limit_category_to: [] + load_images: true + load_depths: true + load_depth_masks: true + load_masks: true + load_point_clouds: false + max_points: 0 + mask_images: false + mask_depths: false + image_height: 800 + image_width: 800 + box_crop: true + box_crop_mask_thr: 0.4 + box_crop_context: 0.3 + remove_empty_masks: true + seed: 0 + sort_frames: false + path_manager_factory_PathManagerFactory_args: + silence_logs: true +dataset_map_provider_JsonIndexDatasetMapProviderV2_args: + category: ??? + subset_name: ??? + dataset_root: '' + test_on_train: false + only_test_set: false + load_eval_batches: true + num_load_workers: 4 + n_known_frames_for_test: 0 + dataset_class_type: JsonIndexDataset + path_manager_factory_class_type: PathManagerFactory + dataset_JsonIndexDataset_args: + limit_to: 0 + limit_sequences_to: 0 + pick_sequence: [] + exclude_sequence: [] + limit_category_to: [] + load_images: true + load_depths: true + load_depth_masks: true + load_masks: true + load_point_clouds: false + max_points: 0 + mask_images: false + mask_depths: false + image_height: 800 + image_width: 800 + box_crop: true + box_crop_mask_thr: 0.4 + box_crop_context: 0.3 + remove_empty_masks: true + n_frames_per_sequence: -1 + seed: 0 + sort_frames: false + path_manager_factory_PathManagerFactory_args: + silence_logs: true +dataset_map_provider_LlffDatasetMapProvider_args: + base_dir: ??? + object_name: ??? + path_manager_factory_class_type: PathManagerFactory + n_known_frames_for_test: null + path_manager_factory_PathManagerFactory_args: + silence_logs: true + downscale_factor: 4 +dataset_map_provider_RenderedMeshDatasetMapProvider_args: + num_views: 40 + data_file: null + azimuth_range: 180.0 + distance: 2.7 + resolution: 128 + use_point_light: true + gpu_idx: 0 + path_manager_factory_class_type: PathManagerFactory + path_manager_factory_PathManagerFactory_args: + silence_logs: true +data_loader_map_provider_SequenceDataLoaderMapProvider_args: + batch_size: 1 + num_workers: 0 + dataset_length_train: 0 + dataset_length_val: 0 + dataset_length_test: 0 + train_conditioning_type: SAME + val_conditioning_type: SAME + test_conditioning_type: KNOWN + images_per_seq_options: [] + sample_consecutive_frames: false + consecutive_frames_max_gap: 0 + consecutive_frames_max_gap_seconds: 0.1 +data_loader_map_provider_SimpleDataLoaderMapProvider_args: + batch_size: 1 + num_workers: 0 + dataset_length_train: 0 + dataset_length_val: 0 + dataset_length_test: 0 +data_loader_map_provider_TrainEvalDataLoaderMapProvider_args: + batch_size: 1 + num_workers: 0 + dataset_length_train: 0 + dataset_length_val: 0 + dataset_length_test: 0 + train_conditioning_type: SAME + val_conditioning_type: SAME + test_conditioning_type: KNOWN + images_per_seq_options: [] + sample_consecutive_frames: false + consecutive_frames_max_gap: 0 + consecutive_frames_max_gap_seconds: 0.1 diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/data/overrides.yaml b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/data/overrides.yaml new file mode 100644 index 0000000000000000000000000000000000000000..95899d898b9d05aada3ed22b87058c9ade4e93fc --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/data/overrides.yaml @@ -0,0 +1,126 @@ +log_vars: +- loss_rgb_psnr_fg +- loss_rgb_psnr +- loss_rgb_mse +- loss_rgb_huber +- loss_depth_abs +- loss_depth_abs_fg +- loss_mask_neg_iou +- loss_mask_bce +- loss_mask_beta_prior +- loss_eikonal +- loss_density_tv +- loss_depth_neg_penalty +- loss_autodecoder_norm +- loss_prev_stage_rgb_mse +- loss_prev_stage_rgb_psnr_fg +- loss_prev_stage_rgb_psnr +- loss_prev_stage_mask_bce +- objective +- epoch +- sec/it +mask_images: true +mask_depths: true +render_image_width: 400 +render_image_height: 400 +mask_threshold: 0.5 +output_rasterized_mc: false +bg_color: +- 0.0 +- 0.0 +- 0.0 +num_passes: 1 +chunk_size_grid: 4096 +render_features_dimensions: 3 +tqdm_trigger_threshold: 16 +n_train_target_views: 1 +sampling_mode_training: mask_sample +sampling_mode_evaluation: full_grid +global_encoder_class_type: SequenceAutodecoder +raysampler_class_type: AdaptiveRaySampler +renderer_class_type: LSTMRenderer +image_feature_extractor_class_type: ResNetFeatureExtractor +view_pooler_enabled: true +implicit_function_class_type: IdrFeatureField +view_metrics_class_type: ViewMetrics +regularization_metrics_class_type: RegularizationMetrics +loss_weights: + loss_rgb_mse: 1.0 + loss_prev_stage_rgb_mse: 1.0 + loss_mask_bce: 0.0 + loss_prev_stage_mask_bce: 0.0 +global_encoder_SequenceAutodecoder_args: + autodecoder_args: + encoding_dim: 0 + n_instances: 1 + init_scale: 1.0 + ignore_input: false +raysampler_AdaptiveRaySampler_args: + n_pts_per_ray_training: 64 + n_pts_per_ray_evaluation: 64 + n_rays_per_image_sampled_from_mask: 1024 + n_rays_total_training: null + stratified_point_sampling_training: true + stratified_point_sampling_evaluation: false + cast_ray_bundle_as_cone: false + scene_extent: 8.0 + scene_center: + - 0.0 + - 0.0 + - 0.0 +renderer_LSTMRenderer_args: + num_raymarch_steps: 10 + init_depth: 17.0 + init_depth_noise_std: 0.0005 + hidden_size: 16 + n_feature_channels: 256 + bg_color: null + verbose: false +image_feature_extractor_ResNetFeatureExtractor_args: + name: resnet34 + pretrained: true + stages: + - 1 + - 2 + - 3 + - 4 + normalize_image: true + image_rescale: 0.16 + first_max_pool: true + proj_dim: 32 + l2_norm: true + add_masks: true + add_images: true + global_average_pool: false + feature_rescale: 1.0 +view_pooler_args: + feature_aggregator_class_type: AngleWeightedIdentityFeatureAggregator + view_sampler_args: + masked_sampling: false + sampling_mode: bilinear + feature_aggregator_AngleWeightedIdentityFeatureAggregator_args: + exclude_target_view: true + exclude_target_view_mask_features: true + concatenate_output: true + weight_by_ray_angle_gamma: 1.0 + min_ray_angle_weight: 0.1 +implicit_function_IdrFeatureField_args: + d_in: 3 + d_out: 1 + dims: + - 512 + - 512 + - 512 + - 512 + - 512 + - 512 + - 512 + - 512 + geometric_init: true + bias: 1.0 + skip_in: [] + weight_norm: true + n_harmonic_functions_xyz: 1729 + pooled_feature_dim: 0 +view_metrics_ViewMetrics_args: {} +regularization_metrics_RegularizationMetrics_args: {} diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/data/sql_dataset/set_lists_100.json b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/data/sql_dataset/set_lists_100.json new file mode 100644 index 0000000000000000000000000000000000000000..96dbe2b4010e4db93f3d7fd0bf84145691c9cee0 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/data/sql_dataset/set_lists_100.json @@ -0,0 +1 @@ +{"train": [["cat0_seq0", 0, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq0/frame000000.jpg"], ["cat0_seq0", 2, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq0/frame000002.jpg"], ["cat0_seq0", 4, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq0/frame000004.jpg"], ["cat0_seq0", 6, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq0/frame000006.jpg"], ["cat0_seq0", 8, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq0/frame000008.jpg"], ["cat0_seq1", 0, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq1/frame000000.jpg"], ["cat0_seq1", 2, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq1/frame000002.jpg"], ["cat0_seq1", 4, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq1/frame000004.jpg"], ["cat0_seq1", 6, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq1/frame000006.jpg"], ["cat0_seq1", 8, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq1/frame000008.jpg"], ["cat0_seq2", 0, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq2/frame000000.jpg"], ["cat0_seq2", 2, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq2/frame000002.jpg"], ["cat0_seq2", 4, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq2/frame000004.jpg"], ["cat0_seq2", 6, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq2/frame000006.jpg"], ["cat0_seq2", 8, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq2/frame000008.jpg"], ["cat0_seq3", 0, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq3/frame000000.jpg"], ["cat0_seq3", 2, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq3/frame000002.jpg"], ["cat0_seq3", 4, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq3/frame000004.jpg"], ["cat0_seq3", 6, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq3/frame000006.jpg"], ["cat0_seq3", 8, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq3/frame000008.jpg"], ["cat0_seq4", 0, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq4/frame000000.jpg"], ["cat0_seq4", 2, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq4/frame000002.jpg"], ["cat0_seq4", 4, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq4/frame000004.jpg"], ["cat0_seq4", 6, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq4/frame000006.jpg"], ["cat0_seq4", 8, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq4/frame000008.jpg"], ["cat1_seq0", 0, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq0/frame000000.jpg"], ["cat1_seq0", 2, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq0/frame000002.jpg"], ["cat1_seq0", 4, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq0/frame000004.jpg"], ["cat1_seq0", 6, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq0/frame000006.jpg"], ["cat1_seq0", 8, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq0/frame000008.jpg"], ["cat1_seq1", 0, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq1/frame000000.jpg"], ["cat1_seq1", 2, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq1/frame000002.jpg"], ["cat1_seq1", 4, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq1/frame000004.jpg"], ["cat1_seq1", 6, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq1/frame000006.jpg"], ["cat1_seq1", 8, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq1/frame000008.jpg"], ["cat1_seq2", 0, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq2/frame000000.jpg"], ["cat1_seq2", 2, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq2/frame000002.jpg"], ["cat1_seq2", 4, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq2/frame000004.jpg"], ["cat1_seq2", 6, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq2/frame000006.jpg"], ["cat1_seq2", 8, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq2/frame000008.jpg"], ["cat1_seq3", 0, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq3/frame000000.jpg"], ["cat1_seq3", 2, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq3/frame000002.jpg"], ["cat1_seq3", 4, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq3/frame000004.jpg"], ["cat1_seq3", 6, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq3/frame000006.jpg"], ["cat1_seq3", 8, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq3/frame000008.jpg"], ["cat1_seq4", 0, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq4/frame000000.jpg"], ["cat1_seq4", 2, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq4/frame000002.jpg"], ["cat1_seq4", 4, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq4/frame000004.jpg"], ["cat1_seq4", 6, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq4/frame000006.jpg"], ["cat1_seq4", 8, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq4/frame000008.jpg"]], "test": [["cat0_seq0", 1, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq0/frame000001.jpg"], ["cat0_seq0", 3, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq0/frame000003.jpg"], ["cat0_seq0", 5, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq0/frame000005.jpg"], ["cat0_seq0", 7, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq0/frame000007.jpg"], ["cat0_seq0", 9, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq0/frame000009.jpg"], ["cat0_seq1", 1, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq1/frame000001.jpg"], ["cat0_seq1", 3, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq1/frame000003.jpg"], ["cat0_seq1", 5, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq1/frame000005.jpg"], ["cat0_seq1", 7, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq1/frame000007.jpg"], ["cat0_seq1", 9, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq1/frame000009.jpg"], ["cat0_seq2", 1, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq2/frame000001.jpg"], ["cat0_seq2", 3, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq2/frame000003.jpg"], ["cat0_seq2", 5, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq2/frame000005.jpg"], ["cat0_seq2", 7, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq2/frame000007.jpg"], ["cat0_seq2", 9, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq2/frame000009.jpg"], ["cat0_seq3", 1, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq3/frame000001.jpg"], ["cat0_seq3", 3, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq3/frame000003.jpg"], ["cat0_seq3", 5, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq3/frame000005.jpg"], ["cat0_seq3", 7, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq3/frame000007.jpg"], ["cat0_seq3", 9, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq3/frame000009.jpg"], ["cat0_seq4", 1, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq4/frame000001.jpg"], ["cat0_seq4", 3, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq4/frame000003.jpg"], ["cat0_seq4", 5, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq4/frame000005.jpg"], ["cat0_seq4", 7, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq4/frame000007.jpg"], ["cat0_seq4", 9, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat0_seq4/frame000009.jpg"], ["cat1_seq0", 1, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq0/frame000001.jpg"], ["cat1_seq0", 3, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq0/frame000003.jpg"], ["cat1_seq0", 5, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq0/frame000005.jpg"], ["cat1_seq0", 7, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq0/frame000007.jpg"], ["cat1_seq0", 9, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq0/frame000009.jpg"], ["cat1_seq1", 1, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq1/frame000001.jpg"], ["cat1_seq1", 3, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq1/frame000003.jpg"], ["cat1_seq1", 5, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq1/frame000005.jpg"], ["cat1_seq1", 7, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq1/frame000007.jpg"], ["cat1_seq1", 9, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq1/frame000009.jpg"], ["cat1_seq2", 1, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq2/frame000001.jpg"], ["cat1_seq2", 3, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq2/frame000003.jpg"], ["cat1_seq2", 5, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq2/frame000005.jpg"], ["cat1_seq2", 7, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq2/frame000007.jpg"], ["cat1_seq2", 9, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq2/frame000009.jpg"], ["cat1_seq3", 1, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq3/frame000001.jpg"], ["cat1_seq3", 3, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq3/frame000003.jpg"], ["cat1_seq3", 5, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq3/frame000005.jpg"], ["cat1_seq3", 7, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq3/frame000007.jpg"], ["cat1_seq3", 9, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq3/frame000009.jpg"], ["cat1_seq4", 1, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq4/frame000001.jpg"], ["cat1_seq4", 3, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq4/frame000003.jpg"], ["cat1_seq4", 5, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq4/frame000005.jpg"], ["cat1_seq4", 7, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq4/frame000007.jpg"], ["cat1_seq4", 9, "kfcdtsiagiruwsuplqemogkmqyqhfvpwbvdrikpjlnegagzxhwxrguehparmirtk/cat1_seq4/frame000009.jpg"]]} \ No newline at end of file diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/data/sql_dataset/sql_dataset_100.sqlite b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/data/sql_dataset/sql_dataset_100.sqlite new file mode 100644 index 0000000000000000000000000000000000000000..2d8ea3b2bb10d14175b1f8d87a4cebffa0210410 Binary files /dev/null and b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/data/sql_dataset/sql_dataset_100.sqlite differ diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/models/__init__.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2e41cd717f6a439a9c08d76a9d0e4a54e190fc5a --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/models/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/models/test_overfit_model.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/models/test_overfit_model.py new file mode 100644 index 0000000000000000000000000000000000000000..8012e214c3cd8fadfa443883cc15f5f80a7ecc7e --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/models/test_overfit_model.py @@ -0,0 +1,217 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import unittest +from typing import Any, Dict +from unittest.mock import patch + +import torch +from pytorch3d.implicitron.models.generic_model import GenericModel +from pytorch3d.implicitron.models.overfit_model import OverfitModel +from pytorch3d.implicitron.models.renderer.base import EvaluationMode +from pytorch3d.implicitron.tools.config import expand_args_fields +from pytorch3d.renderer.cameras import look_at_view_transform, PerspectiveCameras + +DEVICE = torch.device("cuda:0") + + +def _generate_fake_inputs(N: int, H: int, W: int) -> Dict[str, Any]: + R, T = look_at_view_transform(azim=torch.rand(N) * 360) + return { + "camera": PerspectiveCameras(R=R, T=T, device=DEVICE), + "fg_probability": torch.randint( + high=2, size=(N, 1, H, W), device=DEVICE + ).float(), + "depth_map": torch.rand((N, 1, H, W), device=DEVICE) + 0.1, + "mask_crop": torch.randint(high=2, size=(N, 1, H, W), device=DEVICE).float(), + "sequence_name": ["sequence"] * N, + "image_rgb": torch.rand((N, 1, H, W), device=DEVICE), + } + + +def mock_safe_multinomial(input: torch.Tensor, num_samples: int) -> torch.Tensor: + """Return non deterministic indexes to mock safe_multinomial + + Args: + input: tensor of shape [B, n] containing non-negative values; + rows are interpreted as unnormalized event probabilities + in categorical distributions. + num_samples: number of samples to take. + + Returns: + Tensor of shape [B, num_samples] + """ + batch_size = input.shape[0] + return torch.arange(num_samples).repeat(batch_size, 1).to(DEVICE) + + +class TestOverfitModel(unittest.TestCase): + def setUp(self): + torch.manual_seed(42) + + def test_overfit_model_vs_generic_model_with_batch_size_one(self): + """In this test we compare OverfitModel to GenericModel behavior. + + We use a Nerf setup (2 rendering passes). + + OverfitModel is a specific case of GenericModel. Hence, with the same inputs, + they should provide the exact same results. + """ + expand_args_fields(OverfitModel) + expand_args_fields(GenericModel) + batch_size, image_height, image_width = 1, 80, 80 + assert batch_size == 1 + overfit_model = OverfitModel( + render_image_height=image_height, + render_image_width=image_width, + coarse_implicit_function_class_type="NeuralRadianceFieldImplicitFunction", + # To avoid randomization to compare the outputs of our model + # we deactivate the stratified_point_sampling_training + raysampler_AdaptiveRaySampler_args={ + "stratified_point_sampling_training": False + }, + global_encoder_class_type="SequenceAutodecoder", + global_encoder_SequenceAutodecoder_args={ + "autodecoder_args": { + "n_instances": 1000, + "init_scale": 1.0, + "encoding_dim": 64, + } + }, + ) + generic_model = GenericModel( + render_image_height=image_height, + render_image_width=image_width, + n_train_target_views=batch_size, + num_passes=2, + # To avoid randomization to compare the outputs of our model + # we deactivate the stratified_point_sampling_training + raysampler_AdaptiveRaySampler_args={ + "stratified_point_sampling_training": False + }, + global_encoder_class_type="SequenceAutodecoder", + global_encoder_SequenceAutodecoder_args={ + "autodecoder_args": { + "n_instances": 1000, + "init_scale": 1.0, + "encoding_dim": 64, + } + }, + ) + + # Check if they do share the number of parameters + num_params_mvm = sum(p.numel() for p in overfit_model.parameters()) + num_params_gm = sum(p.numel() for p in generic_model.parameters()) + self.assertEqual(num_params_mvm, num_params_gm) + + # Adapt the mapping from generic model to overfit model + mapping_om_from_gm = { + key.replace( + "_implicit_functions.0._fn", "coarse_implicit_function" + ).replace("_implicit_functions.1._fn", "implicit_function"): val + for key, val in generic_model.state_dict().items() + } + # Copy parameters from generic_model to overfit_model + overfit_model.load_state_dict(mapping_om_from_gm) + + overfit_model.to(DEVICE) + generic_model.to(DEVICE) + inputs_ = _generate_fake_inputs(batch_size, image_height, image_width) + + # training forward pass + overfit_model.train() + generic_model.train() + + with patch( + "pytorch3d.renderer.implicit.raysampling._safe_multinomial", + side_effect=mock_safe_multinomial, + ): + train_preds_om = overfit_model( + **inputs_, + evaluation_mode=EvaluationMode.TRAINING, + ) + train_preds_gm = generic_model( + **inputs_, + evaluation_mode=EvaluationMode.TRAINING, + ) + + self.assertTrue(len(train_preds_om) == len(train_preds_gm)) + + self.assertTrue(train_preds_om["objective"].isfinite().item()) + # We avoid all the randomization and the weights are the same + # The objective should be the same + self.assertTrue( + torch.allclose(train_preds_om["objective"], train_preds_gm["objective"]) + ) + + # Test if the evaluation works + overfit_model.eval() + generic_model.eval() + with torch.no_grad(): + eval_preds_om = overfit_model( + **inputs_, + evaluation_mode=EvaluationMode.EVALUATION, + ) + eval_preds_gm = generic_model( + **inputs_, + evaluation_mode=EvaluationMode.EVALUATION, + ) + + self.assertEqual( + eval_preds_om["images_render"].shape, + (batch_size, 3, image_height, image_width), + ) + self.assertTrue( + torch.allclose(eval_preds_om["objective"], eval_preds_gm["objective"]) + ) + self.assertTrue( + torch.allclose( + eval_preds_om["images_render"], eval_preds_gm["images_render"] + ) + ) + + def test_overfit_model_check_share_weights(self): + model = OverfitModel(share_implicit_function_across_passes=True) + for p1, p2 in zip( + model.implicit_function.parameters(), + model.coarse_implicit_function.parameters(), + ): + self.assertEqual(id(p1), id(p2)) + + model.to(DEVICE) + inputs_ = _generate_fake_inputs(2, 80, 80) + model(**inputs_, evaluation_mode=EvaluationMode.TRAINING) + + def test_overfit_model_check_no_share_weights(self): + model = OverfitModel( + share_implicit_function_across_passes=False, + coarse_implicit_function_class_type="NeuralRadianceFieldImplicitFunction", + coarse_implicit_function_NeuralRadianceFieldImplicitFunction_args={ + "transformer_dim_down_factor": 1.0, + "n_hidden_neurons_xyz": 256, + "n_layers_xyz": 8, + "append_xyz": (5,), + }, + ) + for p1, p2 in zip( + model.implicit_function.parameters(), + model.coarse_implicit_function.parameters(), + ): + self.assertNotEqual(id(p1), id(p2)) + + model.to(DEVICE) + inputs_ = _generate_fake_inputs(2, 80, 80) + model(**inputs_, evaluation_mode=EvaluationMode.TRAINING) + + def test_overfit_model_coarse_implicit_function_is_none(self): + model = OverfitModel( + share_implicit_function_across_passes=False, + coarse_implicit_function_NeuralRadianceFieldImplicitFunction_args=None, + ) + self.assertIsNone(model.coarse_implicit_function) + model.to(DEVICE) + inputs_ = _generate_fake_inputs(2, 80, 80) + model(**inputs_, evaluation_mode=EvaluationMode.TRAINING) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/models/test_utils.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/models/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..17c21c0ebecabfafa0d7801a0e06856d2144c091 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/models/test_utils.py @@ -0,0 +1,65 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + + +import unittest + +import torch + +from pytorch3d.implicitron.models.utils import preprocess_input, weighted_sum_losses + + +class TestUtils(unittest.TestCase): + def test_prepare_inputs_wrong_num_dim(self): + img = torch.randn(3, 3, 3) + text = ( + "Model received unbatched inputs. " + + "Perhaps they came from a FrameData which had not been collated." + ) + with self.assertRaisesRegex(ValueError, text): + img, fg_prob, depth_map = preprocess_input( + img, None, None, True, True, 0.5, (0.0, 0.0, 0.0) + ) + + def test_prepare_inputs_mask_image_true(self): + batch, channels, height, width = 2, 3, 10, 10 + img = torch.ones(batch, channels, height, width) + # Create a mask on the lower triangular matrix + fg_prob = torch.tril(torch.ones(batch, 1, height, width)) * 0.3 + + out_img, out_fg_prob, out_depth_map = preprocess_input( + img, fg_prob, None, True, False, 0.3, (0.0, 0.0, 0.0) + ) + + self.assertTrue(torch.equal(out_img, torch.tril(img))) + self.assertTrue(torch.equal(out_fg_prob, fg_prob >= 0.3)) + self.assertIsNone(out_depth_map) + + def test_prepare_inputs_mask_depth_true(self): + batch, channels, height, width = 2, 3, 10, 10 + img = torch.ones(batch, channels, height, width) + depth_map = torch.randn(batch, channels, height, width) + # Create a mask on the lower triangular matrix + fg_prob = torch.tril(torch.ones(batch, 1, height, width)) * 0.3 + + out_img, out_fg_prob, out_depth_map = preprocess_input( + img, fg_prob, depth_map, False, True, 0.3, (0.0, 0.0, 0.0) + ) + + self.assertTrue(torch.equal(out_img, img)) + self.assertTrue(torch.equal(out_fg_prob, fg_prob >= 0.3)) + self.assertTrue(torch.equal(out_depth_map, torch.tril(depth_map))) + + def test_weighted_sum_losses(self): + preds = {"a": torch.tensor(2), "b": torch.tensor(2)} + weights = {"a": 2.0, "b": 0.0} + loss = weighted_sum_losses(preds, weights) + self.assertEqual(loss, 4.0) + + def test_weighted_sum_losses_raise_warning(self): + preds = {"a": torch.tensor(2), "b": torch.tensor(2)} + weights = {"c": 2.0, "d": 2.0} + self.assertIsNone(weighted_sum_losses(preds, weights)) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_batch_sampler.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_batch_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..f2ac4a9655f9b0ffcefd72331cf5c8bcca5243f6 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_batch_sampler.py @@ -0,0 +1,268 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + + +import unittest +from collections import defaultdict +from dataclasses import dataclass +from itertools import product + +import numpy as np + +import torch +from pytorch3d.implicitron.dataset.data_loader_map_provider import ( + DoublePoolBatchSampler, +) + +from pytorch3d.implicitron.dataset.dataset_base import DatasetBase +from pytorch3d.implicitron.dataset.frame_data import FrameData +from pytorch3d.implicitron.dataset.scene_batch_sampler import SceneBatchSampler + + +@dataclass +class MockFrameAnnotation: + frame_number: int + sequence_name: str = "sequence" + frame_timestamp: float = 0.0 + + +class MockDataset(DatasetBase): + def __init__(self, num_seq, max_frame_gap=1): + """ + Makes a gap of max_frame_gap frame numbers in the middle of each sequence + """ + self.seq_annots = {f"seq_{i}": None for i in range(num_seq)} + self._seq_to_idx = { + f"seq_{i}": list(range(i * 10, i * 10 + 10)) for i in range(num_seq) + } + + # frame numbers within sequence: [0, ..., 4, n, ..., n+4] + # where n - 4 == max_frame_gap + frame_nos = list(range(5)) + list(range(4 + max_frame_gap, 9 + max_frame_gap)) + self.frame_annots = [ + {"frame_annotation": MockFrameAnnotation(no)} for no in frame_nos * num_seq + ] + for seq_name, idx in self._seq_to_idx.items(): + for i in idx: + self.frame_annots[i]["frame_annotation"].sequence_name = seq_name + + def get_frame_numbers_and_timestamps(self, idxs, subset_filter=None): + assert subset_filter is None + out = [] + for idx in idxs: + frame_annotation = self.frame_annots[idx]["frame_annotation"] + out.append( + (frame_annotation.frame_number, frame_annotation.frame_timestamp) + ) + return out + + def __getitem__(self, index: int): + fa = self.frame_annots[index]["frame_annotation"] + fd = FrameData( + sequence_name=fa.sequence_name, + sequence_category="default_category", + frame_number=torch.LongTensor([fa.frame_number]), + frame_timestamp=torch.LongTensor([fa.frame_timestamp]), + ) + return fd + + +class TestSceneBatchSampler(unittest.TestCase): + def setUp(self): + np.random.seed(42) + self.dataset_overfit = MockDataset(1) + + def test_overfit(self): + num_batches = 3 + batch_size = 10 + sampler = SceneBatchSampler( + self.dataset_overfit, + batch_size=batch_size, + num_batches=num_batches, + images_per_seq_options=[10], # will try to sample batch_size anyway + ) + + self.assertEqual(len(sampler), num_batches) + + it = iter(sampler) + for _ in range(num_batches): + batch = next(it) + self.assertIsNotNone(batch) + self.assertEqual(len(batch), batch_size) # true for our examples + self.assertTrue(all(idx // 10 == 0 for idx in batch)) + + with self.assertRaises(StopIteration): + batch = next(it) + + def test_multiseq(self): + for ips_options in [[10], [2], [3], [2, 3, 4]]: + for sample_consecutive_frames in [True, False]: + for consecutive_frames_max_gap in [0, 1, 3]: + self._test_multiseq_flavour( + ips_options, + sample_consecutive_frames, + consecutive_frames_max_gap, + ) + + def test_multiseq_gaps(self): + num_batches = 16 + batch_size = 10 + dataset_multiseq = MockDataset(5, max_frame_gap=3) + for ips_options in [[10], [2], [3], [2, 3, 4]]: + debug_info = f" Images per sequence: {ips_options}." + + sampler = SceneBatchSampler( + dataset_multiseq, + batch_size=batch_size, + num_batches=num_batches, + images_per_seq_options=ips_options, + sample_consecutive_frames=True, + consecutive_frames_max_gap=1, + ) + + self.assertEqual(len(sampler), num_batches, msg=debug_info) + + it = iter(sampler) + for _ in range(num_batches): + batch = next(it) + self.assertIsNotNone(batch, "batch is None in" + debug_info) + if max(ips_options) > 5: + # true for our examples + self.assertEqual(len(batch), 5, msg=debug_info) + else: + # true for our examples + self.assertEqual(len(batch), batch_size, msg=debug_info) + + self._check_frames_are_consecutive( + batch, dataset_multiseq.frame_annots, debug_info + ) + + def _test_multiseq_flavour( + self, + ips_options, + sample_consecutive_frames, + consecutive_frames_max_gap, + num_batches=16, + batch_size=10, + ): + debug_info = ( + f" Images per sequence: {ips_options}, " + f"sample_consecutive_frames: {sample_consecutive_frames}, " + f"consecutive_frames_max_gap: {consecutive_frames_max_gap}, " + ) + # in this test, either consecutive_frames_max_gap == max_frame_gap, + # or consecutive_frames_max_gap == 0, so segments consist of full sequences + frame_gap = consecutive_frames_max_gap if consecutive_frames_max_gap > 0 else 3 + dataset_multiseq = MockDataset(5, max_frame_gap=frame_gap) + sampler = SceneBatchSampler( + dataset_multiseq, + batch_size=batch_size, + num_batches=num_batches, + images_per_seq_options=ips_options, + sample_consecutive_frames=sample_consecutive_frames, + consecutive_frames_max_gap=consecutive_frames_max_gap, + ) + + self.assertEqual(len(sampler), num_batches, msg=debug_info) + + it = iter(sampler) + typical_counts = set() + for _ in range(num_batches): + batch = next(it) + self.assertIsNotNone(batch, "batch is None in" + debug_info) + # true for our examples + self.assertEqual(len(batch), batch_size, msg=debug_info) + # find distribution over sequences + counts = _count_by_quotient(batch, 10) + freqs = _count_by_quotient(counts.values(), 1) + self.assertLessEqual( + len(freqs), + 2, + msg="We should have maximum of 2 different " + "frequences of sequences in the batch." + debug_info, + ) + if len(freqs) == 2: + most_seq_count = max(*freqs.keys()) + last_seq = min(*freqs.keys()) + self.assertEqual( + freqs[last_seq], + 1, + msg="Only one odd sequence allowed." + debug_info, + ) + else: + self.assertEqual(len(freqs), 1) + most_seq_count = next(iter(freqs)) + + self.assertIn(most_seq_count, ips_options) + typical_counts.add(most_seq_count) + + if sample_consecutive_frames: + self._check_frames_are_consecutive( + batch, + dataset_multiseq.frame_annots, + debug_info, + max_gap=consecutive_frames_max_gap, + ) + + self.assertTrue( + all(i in typical_counts for i in ips_options), + "Some of the frequency options did not occur among " + f"the {num_batches} batches (could be just bad luck)." + debug_info, + ) + + with self.assertRaises(StopIteration): + batch = next(it) + + def _check_frames_are_consecutive(self, batch, annots, debug_info, max_gap=1): + # make sure that sampled frames are consecutive + for i in range(len(batch) - 1): + curr_idx, next_idx = batch[i : i + 2] + if curr_idx // 10 == next_idx // 10: # same sequence + if max_gap > 0: + curr_idx, next_idx = [ + annots[idx]["frame_annotation"].frame_number + for idx in (curr_idx, next_idx) + ] + gap = max_gap + else: + gap = 1 # we'll check that raw dataset indices are consecutive + + self.assertLessEqual(next_idx - curr_idx, gap, msg=debug_info) + + +def _count_by_quotient(indices, divisor): + counter = defaultdict(int) + for i in indices: + counter[i // divisor] += 1 + + return counter + + +class TestRandomSampling(unittest.TestCase): + def test_double_pool_batch_sampler(self): + unknown_idxs = [2, 3, 4, 5, 8] + known_idxs = [2, 9, 10, 11, 12, 13, 14, 15, 16, 17] + for replacement, num_batches in product([True, False], [None, 4, 5, 6, 30]): + with self.subTest(f"{replacement}, {num_batches}"): + sampler = DoublePoolBatchSampler( + first_indices=unknown_idxs, + rest_indices=known_idxs, + batch_size=4, + replacement=replacement, + num_batches=num_batches, + ) + for _ in range(6): + epoch = list(sampler) + self.assertEqual(len(epoch), num_batches or len(unknown_idxs)) + for batch in epoch: + self.assertEqual(len(batch), 4) + self.assertIn(batch[0], unknown_idxs) + for i in batch[1:]: + self.assertIn(i, known_idxs) + if not replacement and 4 != num_batches: + self.assertEqual( + {batch[0] for batch in epoch}, set(unknown_idxs) + ) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_bbox.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_bbox.py new file mode 100644 index 0000000000000000000000000000000000000000..08dc119fe06237df7ab4fed65c57bd5b90957825 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_bbox.py @@ -0,0 +1,142 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import unittest + +import numpy as np + +import torch + +from pytorch3d.implicitron.dataset.utils import ( + bbox_xywh_to_xyxy, + bbox_xyxy_to_xywh, + clamp_box_to_image_bounds_and_round, + crop_around_box, + get_1d_bounds, + get_bbox_from_mask, + get_clamp_bbox, + rescale_bbox, + resize_image, +) + +from tests.common_testing import TestCaseMixin + + +class TestBBox(TestCaseMixin, unittest.TestCase): + def setUp(self): + torch.manual_seed(42) + + def test_bbox_conversion(self): + bbox_xywh_list = torch.LongTensor( + [ + [0, 0, 10, 20], + [10, 20, 5, 1], + [10, 20, 1, 1], + [5, 4, 0, 1], + ] + ) + for bbox_xywh in bbox_xywh_list: + bbox_xyxy = bbox_xywh_to_xyxy(bbox_xywh) + bbox_xywh_ = bbox_xyxy_to_xywh(bbox_xyxy) + bbox_xyxy_ = bbox_xywh_to_xyxy(bbox_xywh_) + self.assertClose(bbox_xywh_, bbox_xywh) + self.assertClose(bbox_xyxy, bbox_xyxy_) + + def test_compare_to_expected(self): + bbox_xywh_to_xyxy_expected = torch.LongTensor( + [ + [[0, 0, 10, 20], [0, 0, 10, 20]], + [[10, 20, 5, 1], [10, 20, 15, 21]], + [[10, 20, 1, 1], [10, 20, 11, 21]], + [[5, 4, 0, 1], [5, 4, 5, 5]], + ] + ) + for bbox_xywh, bbox_xyxy_expected in bbox_xywh_to_xyxy_expected: + self.assertClose(bbox_xywh_to_xyxy(bbox_xywh), bbox_xyxy_expected) + self.assertClose(bbox_xyxy_to_xywh(bbox_xyxy_expected), bbox_xywh) + + clamp_amnt = 3 + bbox_xywh_to_xyxy_clamped_expected = torch.LongTensor( + [ + [[0, 0, 10, 20], [0, 0, 10, 20]], + [[10, 20, 5, 1], [10, 20, 15, 20 + clamp_amnt]], + [[10, 20, 1, 1], [10, 20, 10 + clamp_amnt, 20 + clamp_amnt]], + [[5, 4, 0, 1], [5, 4, 5 + clamp_amnt, 4 + clamp_amnt]], + ] + ) + for bbox_xywh, bbox_xyxy_expected in bbox_xywh_to_xyxy_clamped_expected: + self.assertClose( + bbox_xywh_to_xyxy(bbox_xywh, clamp_size=clamp_amnt), + bbox_xyxy_expected, + ) + + def test_mask_to_bbox(self): + mask = np.array( + [ + [0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0], + ] + ).astype(np.float32) + expected_bbox_xywh = [2, 1, 2, 1] + bbox_xywh = get_bbox_from_mask(mask, 0.5) + self.assertClose(bbox_xywh, expected_bbox_xywh) + + def test_crop_around_box(self): + bbox = torch.LongTensor([0, 1, 2, 3]) # (x_min, y_min, x_max, y_max) + image = torch.LongTensor( + [ + [0, 0, 10, 20], + [10, 20, 5, 1], + [10, 20, 1, 1], + [5, 4, 0, 1], + ] + ) + cropped = crop_around_box(image, bbox) + self.assertClose(cropped, image[1:3, 0:2]) + + def test_clamp_box_to_image_bounds_and_round(self): + bbox = torch.LongTensor([0, 1, 10, 12]) + image_size = (5, 6) + expected_clamped_bbox = torch.LongTensor([0, 1, image_size[1], image_size[0]]) + clamped_bbox = clamp_box_to_image_bounds_and_round(bbox, image_size) + self.assertClose(clamped_bbox, expected_clamped_bbox) + + def test_get_clamp_bbox(self): + bbox_xywh = torch.LongTensor([1, 1, 4, 5]) + clamped_bbox_xyxy = get_clamp_bbox(bbox_xywh, box_crop_context=2) + # size multiplied by 2 and added coordinates + self.assertClose(clamped_bbox_xyxy, torch.Tensor([-3, -4, 9, 11])) + + def test_rescale_bbox(self): + bbox = torch.Tensor([0.0, 1.0, 3.0, 4.0]) + original_resolution = (4, 4) + new_resolution = (8, 8) # twice bigger + rescaled_bbox = rescale_bbox(bbox, original_resolution, new_resolution) + self.assertClose(bbox * 2, rescaled_bbox) + + def test_get_1d_bounds(self): + array = [0, 1, 2] + bounds = get_1d_bounds(array) + # make nonzero 1d bounds of image + self.assertClose(bounds, [1, 3]) + + def test_resize_image(self): + image = np.random.rand(3, 300, 500) # rgb image 300x500 + expected_shape = (150, 250) + + resized_image, scale, mask_crop = resize_image( + image, image_height=expected_shape[0], image_width=expected_shape[1] + ) + + original_shape = image.shape[-2:] + expected_scale = min( + expected_shape[0] / original_shape[0], expected_shape[1] / original_shape[1] + ) + + self.assertEqual(scale, expected_scale) + self.assertEqual(resized_image.shape[-2:], expected_shape) + self.assertEqual(mask_crop.shape[-2:], expected_shape) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_build.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_build.py new file mode 100644 index 0000000000000000000000000000000000000000..17d90b629b33302b2b8d5aae7989fc0fa55e7170 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_build.py @@ -0,0 +1,51 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import importlib +import os +import sys +import unittest +import unittest.mock + +from tests.common_testing import get_pytorch3d_dir + + +# This file groups together tests which look at the code without running it. +class TestBuild(unittest.TestCase): + def _test_no_import_cycles(self): + # Check each module of pytorch3d imports cleanly, + # which may fail if there are import cycles. + + with unittest.mock.patch.dict(sys.modules): + for module in list(sys.modules): + # If any of pytorch3d is already imported, + # the test would be pointless. + if module.startswith("pytorch3d"): + sys.modules.pop(module, None) + + # torchvision seems to cause problems if re-imported, + # so make sure it has been imported here. + import torchvision.utils # noqa + + root_dir = get_pytorch3d_dir() / "pytorch3d" + # Exclude opengl-related files, as Implicitron is decoupled from opengl + # components which will not work without adding a dep on pytorch3d_opengl. + ignored_modules = ( + "__init__", + "plotly_vis", + "opengl_utils", + "rasterizer_opengl", + ) + if os.environ.get("FB_TEST", False): + ignored_modules += ("orm_types", "sql_dataset", "sql_dataset_provider") + for module_file in root_dir.glob("**/*.py"): + if module_file.stem in ignored_modules: + continue + relative_module = str(module_file.relative_to(root_dir))[:-3] + module = "pytorch3d." + relative_module.replace("/", ".") + with self.subTest(name=module): + with unittest.mock.patch.dict(sys.modules): + importlib.import_module(module) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_config.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_config.py new file mode 100644 index 0000000000000000000000000000000000000000..f55acac10345fa01d58dfe4723090d8a7e5ebb8a --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_config.py @@ -0,0 +1,920 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import pickle +import textwrap +import unittest +from dataclasses import dataclass, field, is_dataclass +from enum import Enum +from typing import Any, Dict, List, Optional, Tuple +from unittest.mock import Mock + +from omegaconf import DictConfig, ListConfig, OmegaConf, ValidationError +from pytorch3d.implicitron.tools.config import ( + _get_type_to_process, + _is_actually_dataclass, + _ProcessType, + _Registry, + Configurable, + enable_get_default_args, + expand_args_fields, + get_default_args, + get_default_args_field, + registry, + remove_unused_components, + ReplaceableBase, + run_auto_creation, +) + + +@dataclass +class Animal(ReplaceableBase): + pass + + +class Fruit(ReplaceableBase): + pass + + +@registry.register +class Banana(Fruit): + pips: int + spots: int + bananame: str + + +@registry.register +class Pear(Fruit): + n_pips: int = 13 + + +class Pineapple(Fruit): + pass + + +@registry.register +class Orange(Fruit): + pass + + +@registry.register +class Kiwi(Fruit): + pass + + +@registry.register +class LargePear(Pear): + pass + + +class BoringConfigurable(Configurable): + pass + + +class MainTest(Configurable): + the_fruit: Fruit + n_ids: int + n_reps: int = 8 + the_second_fruit: Fruit + + def create_the_second_fruit(self): + expand_args_fields(Pineapple) + self.the_second_fruit = Pineapple() + + def __post_init__(self): + run_auto_creation(self) + + +class TestConfig(unittest.TestCase): + def test_is_actually_dataclass(self): + @dataclass + class A: + pass + + self.assertTrue(_is_actually_dataclass(A)) + self.assertTrue(is_dataclass(A)) + + class B(A): + a: int + + self.assertFalse(_is_actually_dataclass(B)) + self.assertTrue(is_dataclass(B)) + + def test_get_type_to_process(self): + gt = _get_type_to_process + self.assertIsNone(gt(int)) + self.assertEqual(gt(Fruit), (Fruit, _ProcessType.REPLACEABLE)) + self.assertEqual( + gt(Optional[Fruit]), (Fruit, _ProcessType.OPTIONAL_REPLACEABLE) + ) + self.assertEqual(gt(MainTest), (MainTest, _ProcessType.CONFIGURABLE)) + self.assertEqual( + gt(Optional[MainTest]), (MainTest, _ProcessType.OPTIONAL_CONFIGURABLE) + ) + self.assertIsNone(gt(Optional[int])) + self.assertIsNone(gt(Tuple[Fruit])) + self.assertIsNone(gt(Tuple[Fruit, Animal])) + self.assertIsNone(gt(Optional[List[int]])) + + def test_simple_replacement(self): + struct = get_default_args(MainTest) + struct.n_ids = 9780 + struct.the_fruit_Pear_args.n_pips = 3 + struct.the_fruit_class_type = "Pear" + struct.the_second_fruit_class_type = "Pear" + + main = MainTest(**struct) + self.assertIsInstance(main.the_fruit, Pear) + self.assertEqual(main.n_reps, 8) + self.assertEqual(main.n_ids, 9780) + self.assertEqual(main.the_fruit.n_pips, 3) + self.assertIsInstance(main.the_second_fruit, Pineapple) + + struct2 = get_default_args(MainTest) + self.assertEqual(struct2.the_fruit_Pear_args.n_pips, 13) + + self.assertEqual( + MainTest._creation_functions, + ("create_the_fruit", "create_the_second_fruit"), + ) + + def test_detect_bases(self): + # testing the _base_class_from_class function + self.assertIsNone(_Registry._base_class_from_class(ReplaceableBase)) + self.assertIsNone(_Registry._base_class_from_class(MainTest)) + self.assertIs(_Registry._base_class_from_class(Fruit), Fruit) + self.assertIs(_Registry._base_class_from_class(Pear), Fruit) + + class PricklyPear(Pear): + pass + + self.assertIs(_Registry._base_class_from_class(PricklyPear), Fruit) + + def test_registry_entries(self): + self.assertIs(registry.get(Fruit, "Banana"), Banana) + with self.assertRaisesRegex(ValueError, "Banana has not been registered."): + registry.get(Animal, "Banana") + with self.assertRaisesRegex(ValueError, "PricklyPear has not been registered."): + registry.get(Fruit, "PricklyPear") + + self.assertIs(registry.get(Pear, "Pear"), Pear) + self.assertIs(registry.get(Pear, "LargePear"), LargePear) + with self.assertRaisesRegex(ValueError, "Banana resolves to"): + registry.get(Pear, "Banana") + + all_fruit = set(registry.get_all(Fruit)) + self.assertIn(Banana, all_fruit) + self.assertIn(Pear, all_fruit) + self.assertIn(LargePear, all_fruit) + self.assertEqual(registry.get_all(Pear), [LargePear]) + + @registry.register + class Apple(Fruit): + pass + + @registry.register + class CrabApple(Apple): + pass + + self.assertEqual(registry.get_all(Apple), [CrabApple]) + + self.assertIs(registry.get(Fruit, "CrabApple"), CrabApple) + + with self.assertRaisesRegex(ValueError, "Cannot tell what it is."): + + @registry.register + class NotAFruit: + pass + + def test_recursion(self): + class Shape(ReplaceableBase): + pass + + @registry.register + class Triangle(Shape): + a: float = 5.0 + + @registry.register + class Square(Shape): + a: float = 3.0 + + @registry.register + class LargeShape(Shape): + inner: Shape + + def __post_init__(self): + run_auto_creation(self) + + class ShapeContainer(Configurable): + shape: Shape + + container = ShapeContainer(**get_default_args(ShapeContainer)) + # This is because ShapeContainer is missing __post_init__ + with self.assertRaises(AttributeError): + container.shape + + class ShapeContainer2(Configurable): + x: Shape + x_class_type: str = "LargeShape" + + def __post_init__(self): + self.x_LargeShape_args.inner_class_type = "Triangle" + run_auto_creation(self) + + container2_args = get_default_args(ShapeContainer2) + container2_args.x_LargeShape_args.inner_Triangle_args.a += 10 + self.assertIn("inner_Square_args", container2_args.x_LargeShape_args) + # We do not perform expansion that would result in an infinite recursion, + # so this member is not present. + self.assertNotIn("inner_LargeShape_args", container2_args.x_LargeShape_args) + container2_args.x_LargeShape_args.inner_Square_args.a += 100 + container2 = ShapeContainer2(**container2_args) + self.assertIsInstance(container2.x, LargeShape) + self.assertIsInstance(container2.x.inner, Triangle) + self.assertEqual(container2.x.inner.a, 15.0) + + def test_simpleclass_member(self): + # Members which are not dataclasses are + # tolerated. But it would be nice to be able to + # configure them. + class Foo: + def __init__(self, a: Any = 1, b: Any = 2): + self.a, self.b = a, b + + enable_get_default_args(Foo) + + @dataclass(frozen=True) + class Bar: + aa: int = 9 + bb: int = 9 + + class Container(Configurable): + bar: Bar = Bar() + # TODO make this work? + # foo: Foo = Foo() + fruit: Fruit + fruit_class_type: str = "Orange" + + def __post_init__(self): + run_auto_creation(self) + + self.assertEqual(get_default_args(Foo), {"a": 1, "b": 2}) + container_args = get_default_args(Container) + container = Container(**container_args) + self.assertIsInstance(container.fruit, Orange) + self.assertEqual(Container._processed_members, {"fruit": Fruit}) + self.assertEqual(container._processed_members, {"fruit": Fruit}) + + container_defaulted = Container() + container_defaulted.fruit_Pear_args.n_pips += 4 + + container_args2 = get_default_args(Container) + container = Container(**container_args2) + self.assertEqual(container.fruit_Pear_args.n_pips, 13) + + def test_inheritance(self): + # Also exercises optional replaceables + class FruitBowl(ReplaceableBase): + main_fruit: Fruit + main_fruit_class_type: str = "Orange" + + def __post_init__(self): + raise ValueError("This doesn't get called") + + class LargeFruitBowl(FruitBowl): + extra_fruit: Optional[Fruit] + extra_fruit_class_type: str = "Kiwi" + no_fruit: Optional[Fruit] + no_fruit_class_type: Optional[str] = None + + def __post_init__(self): + run_auto_creation(self) + + large_args = get_default_args(LargeFruitBowl) + self.assertNotIn("extra_fruit", large_args) + self.assertNotIn("main_fruit", large_args) + large = LargeFruitBowl(**large_args) + self.assertIsInstance(large.main_fruit, Orange) + self.assertIsInstance(large.extra_fruit, Kiwi) + self.assertIsNone(large.no_fruit) + self.assertIn("no_fruit_Kiwi_args", large_args) + + remove_unused_components(large_args) + large2 = LargeFruitBowl(**large_args) + self.assertIsInstance(large2.main_fruit, Orange) + self.assertIsInstance(large2.extra_fruit, Kiwi) + self.assertIsNone(large2.no_fruit) + needed_args = [ + "extra_fruit_Kiwi_args", + "extra_fruit_class_type", + "main_fruit_Orange_args", + "main_fruit_class_type", + "no_fruit_class_type", + ] + self.assertEqual(sorted(large_args.keys()), needed_args) + + with self.assertRaisesRegex(ValueError, "NotAFruit has not been registered."): + LargeFruitBowl(extra_fruit_class_type="NotAFruit") + + def test_inheritance2(self): + # This is a case where a class could contain an instance + # of a subclass, which is ignored. + class Parent(ReplaceableBase): + pass + + class Main(Configurable): + parent: Parent + # Note - no __post__init__ + + @registry.register + class Derived(Parent, Main): + pass + + args = get_default_args(Main) + # Derived has been ignored in processing Main. + self.assertCountEqual(args.keys(), ["parent_class_type"]) + + main = Main(**args) + + with self.assertRaisesRegex(ValueError, "UNDEFAULTED has not been registered."): + run_auto_creation(main) + + main.parent_class_type = "Derived" + # Illustrates that a dict works fine instead of a DictConfig. + main.parent_Derived_args = {} + with self.assertRaises(AttributeError): + main.parent + run_auto_creation(main) + self.assertIsInstance(main.parent, Derived) + + def test_redefine(self): + class FruitBowl(ReplaceableBase): + main_fruit: Fruit + main_fruit_class_type: str = "Grape" + + def __post_init__(self): + run_auto_creation(self) + + @registry.register + @dataclass + class Grape(Fruit): + large: bool = False + + def get_color(self): + return "red" + + def __post_init__(self): + raise ValueError("This doesn't get called") + + bowl_args = get_default_args(FruitBowl) + + @registry.register + @dataclass + class Grape(Fruit): # noqa: F811 + large: bool = True + + def get_color(self): + return "green" + + with self.assertWarnsRegex( + UserWarning, "New implementation of Grape is being chosen." + ): + defaulted_bowl = FruitBowl() + self.assertIsInstance(defaulted_bowl.main_fruit, Grape) + self.assertEqual(defaulted_bowl.main_fruit.large, True) + self.assertEqual(defaulted_bowl.main_fruit.get_color(), "green") + + with self.assertWarnsRegex( + UserWarning, "New implementation of Grape is being chosen." + ): + args_bowl = FruitBowl(**bowl_args) + self.assertIsInstance(args_bowl.main_fruit, Grape) + # Redefining the same class won't help with defaults because encoded in args + self.assertEqual(args_bowl.main_fruit.large, False) + # But the override worked. + self.assertEqual(args_bowl.main_fruit.get_color(), "green") + + # 2. Try redefining without the dataclass modifier + # This relies on the fact that default creation processes the class. + # (otherwise incomprehensible messages) + @registry.register + class Grape(Fruit): # noqa: F811 + large: bool = True + + with self.assertWarnsRegex( + UserWarning, "New implementation of Grape is being chosen." + ): + FruitBowl(**bowl_args) + + # 3. Adding a new class doesn't get picked up, because the first + # get_default_args call has frozen FruitBowl. This is intrinsic to + # the way dataclass and expand_args_fields work in-place but + # expand_args_fields is not pure - it depends on the registry. + @registry.register + class Fig(Fruit): + pass + + bowl_args2 = get_default_args(FruitBowl) + self.assertIn("main_fruit_Grape_args", bowl_args2) + self.assertNotIn("main_fruit_Fig_args", bowl_args2) + + # TODO Is it possible to make this work? + # bowl_args2["main_fruit_Fig_args"] = get_default_args(Fig) + # bowl_args2.main_fruit_class_type = "Fig" + # bowl2 = FruitBowl(**bowl_args2) <= unexpected argument + + # Note that it is possible to use Fig if you can set + # bowl2.main_fruit_Fig_args explicitly (not in bowl_args2) + # before run_auto_creation happens. See test_inheritance2 + # for an example. + + def test_no_replacement(self): + # Test of Configurables without ReplaceableBase + class A(Configurable): + n: int = 9 + + class B(Configurable): + a: A + + def __post_init__(self): + run_auto_creation(self) + + class C(Configurable): + b1: B + b2: Optional[B] + b3: Optional[B] + b2_enabled: bool = True + b3_enabled: bool = False + + def __post_init__(self): + run_auto_creation(self) + + c_args = get_default_args(C) + c = C(**c_args) + self.assertIsInstance(c.b1.a, A) + self.assertEqual(c.b1.a.n, 9) + self.assertFalse(hasattr(c, "b1_enabled")) + self.assertIsInstance(c.b2.a, A) + self.assertEqual(c.b2.a.n, 9) + self.assertTrue(c.b2_enabled) + self.assertIsNone(c.b3) + self.assertFalse(c.b3_enabled) + + def test_doc(self): + # The case in the docstring. + class A(ReplaceableBase): + k: int = 1 + + @registry.register + class A1(A): + m: int = 3 + + @registry.register + class A2(A): + n: str = "2" + + class B(Configurable): + a: A + a_class_type: str = "A2" + + def __post_init__(self): + run_auto_creation(self) + + b_args = get_default_args(B) + self.assertNotIn("a", b_args) + b = B(**b_args) + self.assertEqual(b.a.n, "2") + + def test_raw_types(self): + @dataclass + class MyDataclass: + int_field: int = 0 + none_field: Optional[int] = None + float_field: float = 9.3 + bool_field: bool = True + tuple_field: Tuple[int, ...] = (3,) + + class SimpleClass: + def __init__( + self, + tuple_member_: Tuple[int, int] = (3, 4), + ): + self.tuple_member = tuple_member_ + + def get_tuple(self): + return self.tuple_member + + enable_get_default_args(SimpleClass) + + def f(*, a: int = 3, b: str = "kj"): + self.assertEqual(a, 3) + self.assertEqual(b, "kj") + + enable_get_default_args(f) + + class C(Configurable): + simple: DictConfig = get_default_args_field(SimpleClass) + # simple2: SimpleClass2 = SimpleClass2() + mydata: DictConfig = get_default_args_field(MyDataclass) + a_tuple: Tuple[float] = (4.0, 3.0) + f_args: DictConfig = get_default_args_field(f) + + args = get_default_args(C) + c = C(**args) + self.assertCountEqual(args.keys(), ["simple", "mydata", "a_tuple", "f_args"]) + + mydata = MyDataclass(**c.mydata) + simple = SimpleClass(**c.simple) + + # OmegaConf converts tuples to ListConfigs (which act like lists). + self.assertEqual(simple.get_tuple(), [3, 4]) + self.assertTrue(isinstance(simple.get_tuple(), ListConfig)) + # get_default_args converts sets to ListConfigs (which act like lists). + self.assertEqual(c.a_tuple, [4.0, 3.0]) + self.assertTrue(isinstance(c.a_tuple, ListConfig)) + self.assertEqual(mydata.tuple_field, (3,)) + self.assertTrue(isinstance(mydata.tuple_field, ListConfig)) + f(**c.f_args) + + def test_irrelevant_bases(self): + class NotADataclass: + # Like torch.nn.Module, this class contains annotations + # but is not designed to be dataclass'd. + # This test ensures that such classes, when inherited fron, + # are not accidentally affected by expand_args_fields. + a: int = 9 + b: int + + class LeftConfigured(Configurable, NotADataclass): + left: int = 1 + + class RightConfigured(NotADataclass, Configurable): + right: int = 2 + + class Outer(Configurable): + left: LeftConfigured + right: RightConfigured + + def __post_init__(self): + run_auto_creation(self) + + outer = Outer(**get_default_args(Outer)) + self.assertEqual(outer.left.left, 1) + self.assertEqual(outer.right.right, 2) + with self.assertRaisesRegex(TypeError, "non-default argument"): + dataclass(NotADataclass) + + def test_unprocessed(self): + # behavior of Configurable classes which need processing in __new__, + class UnprocessedConfigurable(Configurable): + a: int = 9 + + class UnprocessedReplaceable(ReplaceableBase): + a: int = 9 + + for Unprocessed in [UnprocessedConfigurable, UnprocessedReplaceable]: + self.assertFalse(_is_actually_dataclass(Unprocessed)) + unprocessed = Unprocessed() + self.assertTrue(_is_actually_dataclass(Unprocessed)) + self.assertTrue(isinstance(unprocessed, Unprocessed)) + self.assertEqual(unprocessed.a, 9) + + def test_enum(self): + # Test that enum values are kept, i.e. that OmegaConf's runtime checks + # are in use. + + class A(Enum): + B1 = "b1" + B2 = "b2" + + # Test for a Configurable class, a function, and a regular class. + class C(Configurable): + a: A = A.B1 + + # Also test for a calllable with enum arguments. + def C_fn(a: A = A.B1): + pass + + enable_get_default_args(C_fn) + + class C_cl: + def __init__(self, a: A = A.B1) -> None: + pass + + enable_get_default_args(C_cl) + + for C_ in [C, C_fn, C_cl]: + base = get_default_args(C_) + self.assertEqual(OmegaConf.to_yaml(base), "a: B1\n") + self.assertEqual(base.a, A.B1) + replaced = OmegaConf.merge(base, {"a": "B2"}) + self.assertEqual(replaced.a, A.B2) + with self.assertRaises(ValidationError): + # You can't use a value which is not one of the + # choices, even if it is the str representation + # of one of the choices. + OmegaConf.merge(base, {"a": "b2"}) + + remerged = OmegaConf.merge(base, OmegaConf.create(OmegaConf.to_yaml(base))) + self.assertEqual(remerged.a, A.B1) + + def test_pickle(self): + def func(a: int = 1, b: str = "3"): + pass + + enable_get_default_args(func) + + args = get_default_args(func) + args2 = pickle.loads(pickle.dumps(args)) + self.assertEqual(args2.a, 1) + self.assertEqual(args2.b, "3") + + args_regenerated = get_default_args(func) + pickle.dumps(args_regenerated) + pickle.dumps(args) + + def test_remove_unused_components(self): + struct = get_default_args(MainTest) + struct.n_ids = 32 + struct.the_fruit_class_type = "Pear" + struct.the_second_fruit_class_type = "Banana" + remove_unused_components(struct) + expected_keys = [ + "n_ids", + "n_reps", + "the_fruit_Pear_args", + "the_fruit_class_type", + "the_second_fruit_Banana_args", + "the_second_fruit_class_type", + ] + expected_yaml = textwrap.dedent( + """\ + n_ids: 32 + n_reps: 8 + the_fruit_class_type: Pear + the_fruit_Pear_args: + n_pips: 13 + the_second_fruit_class_type: Banana + the_second_fruit_Banana_args: + pips: ??? + spots: ??? + bananame: ??? + """ + ) + self.assertEqual(sorted(struct.keys()), expected_keys) + + # Check that struct is what we expect + expected = OmegaConf.create(expected_yaml) + self.assertEqual(struct, expected) + + # Check that we get what we expect when writing to yaml. + self.assertEqual(OmegaConf.to_yaml(struct, sort_keys=False), expected_yaml) + + main = MainTest(**struct) + instance_data = OmegaConf.structured(main) + remove_unused_components(instance_data) + self.assertEqual(sorted(instance_data.keys()), expected_keys) + self.assertEqual(instance_data, expected) + + def test_remove_unused_components_optional(self): + class MainTestWrapper(Configurable): + mt: Optional[MainTest] + mt_enabled: bool = False + + args = get_default_args(MainTestWrapper) + self.assertEqual(list(args.keys()), ["mt_enabled", "mt_args"]) + remove_unused_components(args) + self.assertEqual(OmegaConf.to_yaml(args), "mt_enabled: false\n") + + def test_get_instance_args(self): + mt1, mt2 = [ + MainTest( + n_ids=0, + n_reps=909, + the_fruit_class_type="Pear", + the_second_fruit_class_type="Pear", + the_fruit_Pear_args=DictConfig({}), + the_second_fruit_Pear_args={}, + ) + for _ in range(2) + ] + # Two equivalent ways to get the DictConfig back out of an instance. + cfg1 = OmegaConf.structured(mt1) + cfg2 = get_default_args(mt2) + self.assertEqual(cfg1, cfg2) + self.assertEqual(len(cfg1.the_second_fruit_Pear_args), 0) + self.assertEqual(len(mt2.the_second_fruit_Pear_args), 0) + + from_cfg = MainTest(**cfg2) + self.assertEqual(len(from_cfg.the_second_fruit_Pear_args), 0) + + # If you want the complete args, merge with the defaults. + merged_args = OmegaConf.merge(get_default_args(MainTest), cfg2) + from_merged = MainTest(**merged_args) + self.assertEqual(len(from_merged.the_second_fruit_Pear_args), 1) + self.assertEqual(from_merged.n_reps, 909) + + def test_tweak_hook(self): + class A(Configurable): + n: int = 9 + + class Wrapper(Configurable): + fruit: Fruit + fruit_class_type: str = "Pear" + fruit2: Fruit + fruit2_class_type: str = "Pear" + a: A + a2: A + a3: A + + @classmethod + def a_tweak_args(cls, type, args): + assert type == A + args.n = 993 + + @classmethod + def a3_tweak_args(cls, type, args): + del args["n"] + + @classmethod + def fruit_tweak_args(cls, type, args): + assert issubclass(type, Fruit) + if type == Pear: + assert args.n_pips == 13 + args.n_pips = 19 + + args = get_default_args(Wrapper) + self.assertEqual(args.a_args.n, 993) + self.assertEqual(args.a2_args.n, 9) + self.assertEqual(args.a3_args, {}) + self.assertEqual(args.fruit_Pear_args.n_pips, 19) + self.assertEqual(args.fruit2_Pear_args.n_pips, 13) + + def test_impls(self): + # Check that create_x actually uses create_x_impl to do its work + # by using all the member types, both with a faked impl function + # and without. + # members with _0 are optional and absent, those with _o are + # optional and present. + control_args = [] + + def fake_impl(self, control, args): + control_args.append(control) + + for fake in [False, True]: + + class MyClass(Configurable): + fruit: Fruit + fruit_class_type: str = "Orange" + fruit_o: Optional[Fruit] + fruit_o_class_type: str = "Orange" + fruit_0: Optional[Fruit] + fruit_0_class_type: Optional[str] = None + boring: BoringConfigurable + boring_o: Optional[BoringConfigurable] + boring_o_enabled: bool = True + boring_0: Optional[BoringConfigurable] + boring_0_enabled: bool = False + + def __post_init__(self): + run_auto_creation(self) + + if fake: + MyClass.create_fruit_impl = fake_impl + MyClass.create_fruit_o_impl = fake_impl + MyClass.create_boring_impl = fake_impl + MyClass.create_boring_o_impl = fake_impl + + expand_args_fields(MyClass) + instance = MyClass() + for name in ["fruit", "fruit_o", "boring", "boring_o"]: + self.assertEqual( + hasattr(instance, name), not fake, msg=f"{name} {fake}" + ) + + self.assertIsNone(instance.fruit_0) + self.assertIsNone(instance.boring_0) + if not fake: + self.assertIsInstance(instance.fruit, Orange) + self.assertIsInstance(instance.fruit_o, Orange) + self.assertIsInstance(instance.boring, BoringConfigurable) + self.assertIsInstance(instance.boring_o, BoringConfigurable) + + self.assertEqual(control_args, ["Orange", "Orange", True, True]) + + def test_pre_expand(self): + # Check that the precreate method of a class is called once before + # when expand_args_fields is called on the class. + + class A(Configurable): + n: int = 9 + + @classmethod + def pre_expand(cls): + pass + + A.pre_expand = Mock() + expand_args_fields(A) + A.pre_expand.assert_called() + + def test_pre_expand_replaceable(self): + # Check that the precreate method of a class is called once before + # when expand_args_fields is called on the class. + + class A(ReplaceableBase): + pass + + @classmethod + def pre_expand(cls): + pass + + class A1(A): + n: 9 + + A.pre_expand = Mock() + expand_args_fields(A1) + A.pre_expand.assert_called() + + +@dataclass(eq=False) +class MockDataclass: + field_no_default: int + field_primitive_type: int = 42 + field_optional_none: Optional[int] = None + field_optional_dict_none: Optional[Dict] = None + field_optional_with_value: Optional[int] = 42 + field_list_type: List[int] = field(default_factory=lambda: []) + + +class RefObject: + pass + + +REF_OBJECT = RefObject() + + +class MockClassWithInit: # noqa: B903 + def __init__( + self, + field_no_nothing, + field_no_default: int, + field_primitive_type: int = 42, + field_optional_none: Optional[int] = None, + field_optional_dict_none: Optional[Dict] = None, + field_optional_with_value: Optional[int] = 42, + field_list_type: List[int] = [], # noqa: B006 + field_reference_type: RefObject = REF_OBJECT, + ): + self.field_no_nothing = field_no_nothing + self.field_no_default = field_no_default + self.field_primitive_type = field_primitive_type + self.field_optional_none = field_optional_none + self.field_optional_dict_none = field_optional_dict_none + self.field_optional_with_value = field_optional_with_value + self.field_list_type = field_list_type + self.field_reference_type = field_reference_type + + +enable_get_default_args(MockClassWithInit) + + +class TestRawClasses(unittest.TestCase): + def setUp(self) -> None: + self._instances = { + MockDataclass: MockDataclass(field_no_default=0), + MockClassWithInit: MockClassWithInit( + field_no_nothing="tratata", field_no_default=0 + ), + } + + def test_get_default_args(self): + for cls in [MockDataclass, MockClassWithInit]: + dataclass_defaults = get_default_args(cls) + # DictConfig fields with missing values are `not in` + self.assertNotIn("field_no_default", dataclass_defaults) + self.assertNotIn("field_no_nothing", dataclass_defaults) + self.assertNotIn("field_reference_type", dataclass_defaults) + expected_defaults = [ + "field_primitive_type", + "field_optional_none", + "field_optional_dict_none", + "field_optional_with_value", + "field_list_type", + ] + + if cls == MockDataclass: # we don't remove undefaulted from dataclasses + dataclass_defaults.field_no_default = 0 + expected_defaults.insert(0, "field_no_default") + self.assertEqual(list(dataclass_defaults), expected_defaults) + for name, val in dataclass_defaults.items(): + self.assertTrue(hasattr(self._instances[cls], name)) + self.assertEqual(val, getattr(self._instances[cls], name)) + + def test_get_default_args_readonly(self): + for cls in [MockDataclass, MockClassWithInit]: + dataclass_defaults = get_default_args(cls) + dataclass_defaults["field_list_type"].append(13) + self.assertEqual(self._instances[cls].field_list_type, []) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_config_use.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_config_use.py new file mode 100644 index 0000000000000000000000000000000000000000..9cb455da2f5f8d3fbcb3f829540adf65f1e67a5e --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_config_use.py @@ -0,0 +1,94 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import unittest + +from omegaconf import OmegaConf +from pytorch3d.implicitron.models.feature_extractor.resnet_feature_extractor import ( + ResNetFeatureExtractor, +) +from pytorch3d.implicitron.models.generic_model import GenericModel +from pytorch3d.implicitron.models.global_encoder.global_encoder import ( + SequenceAutodecoder, +) +from pytorch3d.implicitron.models.implicit_function.idr_feature_field import ( + IdrFeatureField, +) +from pytorch3d.implicitron.models.implicit_function.neural_radiance_field import ( + NeuralRadianceFieldImplicitFunction, +) +from pytorch3d.implicitron.models.renderer.lstm_renderer import LSTMRenderer +from pytorch3d.implicitron.models.renderer.multipass_ea import ( + MultiPassEmissionAbsorptionRenderer, +) +from pytorch3d.implicitron.models.view_pooler.feature_aggregator import ( + AngleWeightedIdentityFeatureAggregator, +) +from pytorch3d.implicitron.tools.config import ( + get_default_args, + remove_unused_components, +) +from tests.common_testing import get_tests_dir + +from .common_resources import provide_resnet34 + +DATA_DIR = get_tests_dir() / "implicitron/data" +DEBUG: bool = False + +# Tests the use of the config system in implicitron + + +class TestGenericModel(unittest.TestCase): + def setUp(self): + self.maxDiff = None + + def test_create_gm(self): + args = get_default_args(GenericModel) + gm = GenericModel(**args) + self.assertIsInstance(gm.renderer, MultiPassEmissionAbsorptionRenderer) + self.assertIsInstance( + gm._implicit_functions[0]._fn, NeuralRadianceFieldImplicitFunction + ) + self.assertIsNone(gm.global_encoder) + self.assertFalse(hasattr(gm, "implicit_function")) + self.assertIsNone(gm.view_pooler) + self.assertIsNone(gm.image_feature_extractor) + + def test_create_gm_overrides(self): + provide_resnet34() + args = get_default_args(GenericModel) + args.view_pooler_enabled = True + args.view_pooler_args.feature_aggregator_class_type = ( + "AngleWeightedIdentityFeatureAggregator" + ) + args.image_feature_extractor_class_type = "ResNetFeatureExtractor" + args.implicit_function_class_type = "IdrFeatureField" + args.global_encoder_class_type = "SequenceAutodecoder" + idr_args = args.implicit_function_IdrFeatureField_args + idr_args.n_harmonic_functions_xyz = 1729 + + args.renderer_class_type = "LSTMRenderer" + gm = GenericModel(**args) + self.assertIsInstance(gm.renderer, LSTMRenderer) + self.assertIsInstance( + gm.view_pooler.feature_aggregator, + AngleWeightedIdentityFeatureAggregator, + ) + self.assertIsInstance(gm._implicit_functions[0]._fn, IdrFeatureField) + self.assertEqual(gm._implicit_functions[0]._fn.n_harmonic_functions_xyz, 1729) + self.assertIsInstance(gm.global_encoder, SequenceAutodecoder) + self.assertIsInstance(gm.image_feature_extractor, ResNetFeatureExtractor) + self.assertFalse(hasattr(gm, "implicit_function")) + + instance_args = OmegaConf.structured(gm) + if DEBUG: + full_yaml = OmegaConf.to_yaml(instance_args, sort_keys=False) + (DATA_DIR / "overrides_full.yaml").write_text(full_yaml) + remove_unused_components(instance_args) + yaml = OmegaConf.to_yaml(instance_args, sort_keys=False) + if DEBUG: + (DATA_DIR / "overrides_.yaml").write_text(yaml) + self.assertEqual(yaml, (DATA_DIR / "overrides.yaml").read_text()) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_data_cow.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_data_cow.py new file mode 100644 index 0000000000000000000000000000000000000000..801863e9bcadf7f469ce75a0c6ccf15dc8e6a784 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_data_cow.py @@ -0,0 +1,57 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import os +import unittest + +import torch +from pytorch3d.implicitron.dataset.frame_data import FrameData +from pytorch3d.implicitron.dataset.rendered_mesh_dataset_map_provider import ( + RenderedMeshDatasetMapProvider, +) +from pytorch3d.implicitron.tools.config import expand_args_fields +from pytorch3d.renderer import FoVPerspectiveCameras +from tests.common_testing import TestCaseMixin + + +inside_re_worker = os.environ.get("INSIDE_RE_WORKER", False) + + +class TestDataCow(TestCaseMixin, unittest.TestCase): + def test_simple(self): + if inside_re_worker: + return + expand_args_fields(RenderedMeshDatasetMapProvider) + self._runtest(use_point_light=True, num_views=4) + self._runtest(use_point_light=False, num_views=4) + + def _runtest(self, **kwargs): + provider = RenderedMeshDatasetMapProvider(**kwargs) + dataset_map = provider.get_dataset_map() + known_matrix = torch.zeros(1, 4, 4) + known_matrix[0, 0, 0] = 1.7321 + known_matrix[0, 1, 1] = 1.7321 + known_matrix[0, 2, 2] = 1.0101 + known_matrix[0, 3, 2] = -1.0101 + known_matrix[0, 2, 3] = 1 + + self.assertIsNone(dataset_map.val) + self.assertIsNone(dataset_map.test) + self.assertEqual(len(dataset_map.train), provider.num_views) + + value = dataset_map.train[0] + self.assertIsInstance(value, FrameData) + + self.assertEqual(value.image_rgb.shape, (3, 128, 128)) + self.assertEqual(value.fg_probability.shape, (1, 128, 128)) + # corner of image is background + self.assertEqual(value.fg_probability[0, 0, 0], 0) + self.assertEqual(value.fg_probability.max(), 1.0) + self.assertIsInstance(value.camera, FoVPerspectiveCameras) + self.assertEqual(len(value.camera), 1) + self.assertIsNone(value.camera.K) + matrix = value.camera.get_projection_transform().get_matrix() + self.assertClose(matrix, known_matrix, atol=1e-4) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_eval_cameras.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_eval_cameras.py new file mode 100644 index 0000000000000000000000000000000000000000..5ec795251ee05bb3bff9425f9d9a965e4d9abffa --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_eval_cameras.py @@ -0,0 +1,42 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import unittest + +import torch +from pytorch3d.implicitron.tools.eval_video_trajectory import ( + generate_eval_video_cameras, +) +from pytorch3d.renderer.cameras import look_at_view_transform, PerspectiveCameras +from pytorch3d.transforms import axis_angle_to_matrix +from tests.common_testing import TestCaseMixin + + +class TestEvalCameras(TestCaseMixin, unittest.TestCase): + def setUp(self): + torch.manual_seed(42) + + def test_circular(self): + n_train_cameras = 10 + n_test_cameras = 100 + R, T = look_at_view_transform(azim=torch.rand(n_train_cameras) * 360) + amplitude = 0.01 + R_jiggled = torch.bmm( + R, axis_angle_to_matrix(torch.rand(n_train_cameras, 3) * amplitude) + ) + cameras_train = PerspectiveCameras(R=R_jiggled, T=T) + cameras_test = generate_eval_video_cameras( + cameras_train, trajectory_type="circular_lsq_fit", trajectory_scale=1.0 + ) + + positions_test = cameras_test.get_camera_center() + center = positions_test.mean(0) + self.assertClose(center, torch.zeros(3), atol=0.1) + self.assertClose( + (positions_test - center).norm(dim=[1]), + torch.ones(n_test_cameras), + atol=0.1, + ) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_eval_demo.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_eval_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..37df395db1cb871ae2e0f54f224d404056079fb1 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_eval_demo.py @@ -0,0 +1,29 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import os +import unittest + +from pytorch3d.implicitron import eval_demo + +from tests.common_testing import interactive_testing_requested + +from .common_resources import CO3D_MANIFOLD_PATH + +""" +This test runs a single sequence eval_demo, useful for debugging datasets. +It only runs interactively. +""" + + +class TestEvalDemo(unittest.TestCase): + def test_a(self): + if not interactive_testing_requested(): + return + + os.environ["CO3D_DATASET_ROOT"] = CO3D_MANIFOLD_PATH + + eval_demo.evaluate_dbir_for_category("donut", single_sequence_id=0) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_evaluation.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_evaluation.py new file mode 100644 index 0000000000000000000000000000000000000000..ee0edc51aa36e4ecc4db65b375fb8d73e8edbdd3 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_evaluation.py @@ -0,0 +1,322 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + + +import contextlib +import dataclasses +import itertools +import math +import os +import unittest + +import lpips +import numpy as np +import torch + +from pytorch3d.implicitron.dataset.frame_data import FrameData +from pytorch3d.implicitron.dataset.json_index_dataset import JsonIndexDataset +from pytorch3d.implicitron.evaluation.evaluate_new_view_synthesis import eval_batch +from pytorch3d.implicitron.models.base_model import ImplicitronModelBase +from pytorch3d.implicitron.models.generic_model import GenericModel # noqa +from pytorch3d.implicitron.models.model_dbir import ModelDBIR # noqa +from pytorch3d.implicitron.tools.config import expand_args_fields, registry +from pytorch3d.implicitron.tools.metric_utils import calc_psnr, eval_depth +from pytorch3d.implicitron.tools.utils import dataclass_to_cuda_ + +from .common_resources import get_skateboard_data, provide_lpips_vgg + + +class TestEvaluation(unittest.TestCase): + def setUp(self): + # initialize evaluation dataset/dataloader + torch.manual_seed(42) + + stack = contextlib.ExitStack() + dataset_root, path_manager = stack.enter_context(get_skateboard_data()) + self.addCleanup(stack.close) + + category = "skateboard" + frame_file = os.path.join(dataset_root, category, "frame_annotations.jgz") + sequence_file = os.path.join(dataset_root, category, "sequence_annotations.jgz") + self.image_size = 64 + expand_args_fields(JsonIndexDataset) + self.dataset = JsonIndexDataset( + frame_annotations_file=frame_file, + sequence_annotations_file=sequence_file, + dataset_root=dataset_root, + image_height=self.image_size, + image_width=self.image_size, + box_crop=True, + remove_empty_masks=False, + path_manager=path_manager, + ) + self.bg_color = (0.0, 0.0, 0.0) + + # init the lpips model for eval + provide_lpips_vgg() + self.lpips_model = lpips.LPIPS(net="vgg").cuda() + + def test_eval_depth(self): + """ + Check that eval_depth correctly masks errors and that, for get_best_scale=True, + the error with scaled prediction equals the error without scaling the + predicted depth. Finally, test that the error values are as expected + for prediction and gt differing by a constant offset. + """ + gt = (torch.randn(10, 1, 300, 400, device="cuda") * 5.0).clamp(0.0) + mask = (torch.rand_like(gt) > 0.5).type_as(gt) + + for diff in 10 ** torch.linspace(-5, 0, 6): + for crop in (0, 5): + pred = gt + (torch.rand_like(gt) - 0.5) * 2 * diff + + # scaled prediction test + mse_depth, abs_depth = eval_depth( + pred, + gt, + crop=crop, + mask=mask, + get_best_scale=True, + ) + mse_depth_scale, abs_depth_scale = eval_depth( + pred * 10.0, + gt, + crop=crop, + mask=mask, + get_best_scale=True, + ) + self.assertAlmostEqual( + float(mse_depth.sum()), float(mse_depth_scale.sum()), delta=1e-4 + ) + self.assertAlmostEqual( + float(abs_depth.sum()), float(abs_depth_scale.sum()), delta=1e-4 + ) + + # error masking test + pred_masked_err = gt + (torch.rand_like(gt) + diff) * (1 - mask) + mse_depth_masked, abs_depth_masked = eval_depth( + pred_masked_err, + gt, + crop=crop, + mask=mask, + get_best_scale=True, + ) + self.assertAlmostEqual( + float(mse_depth_masked.sum()), float(0.0), delta=1e-4 + ) + self.assertAlmostEqual( + float(abs_depth_masked.sum()), float(0.0), delta=1e-4 + ) + mse_depth_unmasked, abs_depth_unmasked = eval_depth( + pred_masked_err, + gt, + crop=crop, + mask=1 - mask, + get_best_scale=True, + ) + self.assertGreater( + float(mse_depth_unmasked.sum()), + float(diff**2), + ) + self.assertGreater( + float(abs_depth_unmasked.sum()), + float(diff), + ) + + # tests with constant error + pred_fix_diff = gt + diff * mask + for _mask_gt in (mask, None): + mse_depth_fix_diff, abs_depth_fix_diff = eval_depth( + pred_fix_diff, + gt, + crop=crop, + mask=_mask_gt, + get_best_scale=False, + ) + if _mask_gt is not None: + expected_err_abs = diff + expected_err_mse = diff**2 + else: + err_mask = (gt > 0.0).float() * mask + if crop > 0: + err_mask = err_mask[:, :, crop:-crop, crop:-crop] + gt_cropped = gt[:, :, crop:-crop, crop:-crop] + else: + gt_cropped = gt + gt_mass = (gt_cropped > 0.0).float().sum(dim=(1, 2, 3)) + expected_err_abs = ( + diff * err_mask.sum(dim=(1, 2, 3)) / (gt_mass) + ) + expected_err_mse = diff * expected_err_abs + self.assertTrue( + torch.allclose( + abs_depth_fix_diff, + expected_err_abs * torch.ones_like(abs_depth_fix_diff), + atol=1e-4, + ) + ) + self.assertTrue( + torch.allclose( + mse_depth_fix_diff, + expected_err_mse * torch.ones_like(mse_depth_fix_diff), + atol=1e-4, + ) + ) + + def test_psnr(self): + """ + Compare against opencv and check that the psnr is above + the minimum possible value. + """ + import cv2 + + im1 = torch.rand(100, 3, 256, 256).cuda() + im1_uint8 = (im1 * 255).to(torch.uint8) + im1_rounded = im1_uint8.float() / 255 + for max_diff in 10 ** torch.linspace(-5, 0, 6): + im2 = im1 + (torch.rand_like(im1) - 0.5) * 2 * max_diff + im2 = im2.clamp(0.0, 1.0) + im2_uint8 = (im2 * 255).to(torch.uint8) + im2_rounded = im2_uint8.float() / 255 + # check that our psnr matches the output of opencv + psnr = calc_psnr(im1_rounded, im2_rounded) + # some versions of cv2 can only take uint8 input + psnr_cv2 = cv2.PSNR( + im1_uint8.cpu().numpy(), + im2_uint8.cpu().numpy(), + ) + self.assertAlmostEqual(float(psnr), float(psnr_cv2), delta=1e-4) + # check that all PSNRs are bigger than the minimum possible PSNR + max_mse = max_diff**2 + min_psnr = 10 * math.log10(1.0 / max_mse) + for _im1, _im2 in zip(im1, im2): + _psnr = calc_psnr(_im1, _im2) + self.assertGreaterEqual(float(_psnr) + 1e-6, min_psnr) + + def _one_sequence_test( + self, + seq_dataset, + model, + batch_indices, + check_metrics=False, + ): + loader = torch.utils.data.DataLoader( + seq_dataset, + shuffle=False, + batch_sampler=batch_indices, + collate_fn=FrameData.collate, + ) + + for frame_data in loader: + self.assertIsNone(frame_data.frame_type) + self.assertIsNotNone(frame_data.image_rgb) + # override the frame_type + frame_data.frame_type = [ + "train_unseen", + *(["train_known"] * (len(frame_data.image_rgb) - 1)), + ] + + frame_data = dataclass_to_cuda_(frame_data) + preds = model(**dataclasses.asdict(frame_data)) + + eval_result = eval_batch( + frame_data, + preds["implicitron_render"], + bg_color=self.bg_color, + lpips_model=self.lpips_model, + ) + + if check_metrics: + self._check_metrics( + frame_data, preds["implicitron_render"], eval_result + ) + + def _check_metrics(self, frame_data, implicitron_render, eval_result): + # Make a terribly bad NVS prediction and check that this is worse + # than the DBIR prediction. + implicitron_render_bad = implicitron_render.clone() + implicitron_render_bad.depth_render += ( + torch.randn_like(implicitron_render_bad.depth_render) * 100.0 + ) + implicitron_render_bad.image_render += ( + torch.randn_like(implicitron_render_bad.image_render) * 100.0 + ) + implicitron_render_bad.mask_render = ( + torch.randn_like(implicitron_render_bad.mask_render) > 0.0 + ).float() + eval_result_bad = eval_batch( + frame_data, + implicitron_render_bad, + bg_color=self.bg_color, + lpips_model=self.lpips_model, + ) + + lower_better = { + "psnr_masked": False, + "psnr_fg": False, + "psnr_full_image": False, + "depth_abs_fg": True, + "iou": False, + "rgb_l1_masked": True, + "rgb_l1_fg": True, + "lpips_masked": True, + "lpips_full_image": True, + } + + for metric in lower_better: + m_better = eval_result[metric] + m_worse = eval_result_bad[metric] + if np.isnan(m_better) or np.isnan(m_worse): + continue # metric is missing, i.e. NaN + _assert = ( + self.assertLessEqual + if lower_better[metric] + else self.assertGreaterEqual + ) + _assert(m_better, m_worse) + + def _get_random_batch_indices( + self, seq_dataset, n_batches=2, min_batch_size=5, max_batch_size=10 + ): + batch_indices = [] + for _ in range(n_batches): + batch_size = torch.randint( + low=min_batch_size, high=max_batch_size, size=(1,) + ) + batch_indices.append(torch.randperm(len(seq_dataset))[:batch_size]) + + return batch_indices + + def test_full_eval(self, n_sequences=5): + """Test evaluation.""" + + # caching batch indices first to preserve RNG state + seq_datasets = {} + batch_indices = {} + for seq in itertools.islice(self.dataset.sequence_names(), n_sequences): + idx = list(self.dataset.sequence_indices_in_order(seq)) + seq_dataset = torch.utils.data.Subset(self.dataset, idx) + seq_datasets[seq] = seq_dataset + batch_indices[seq] = self._get_random_batch_indices(seq_dataset) + + for model_class_type in ["ModelDBIR", "GenericModel"]: + ModelClass = registry.get(ImplicitronModelBase, model_class_type) + expand_args_fields(ModelClass) + model = ModelClass( + render_image_width=self.image_size, + render_image_height=self.image_size, + bg_color=self.bg_color, + ) + model.eval() + model.cuda() + + for seq in itertools.islice(self.dataset.sequence_names(), n_sequences): + self._one_sequence_test( + seq_datasets[seq], + model, + batch_indices[seq], + check_metrics=(model_class_type == "ModelDBIR"), + ) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_forward_pass.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_forward_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..32e726a84fd65bd420cde3db7275539a1a489308 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_forward_pass.py @@ -0,0 +1,226 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import os +import unittest + +import torch +from omegaconf import DictConfig, OmegaConf +from pytorch3d.implicitron.models.generic_model import GenericModel +from pytorch3d.implicitron.models.renderer.base import EvaluationMode +from pytorch3d.implicitron.tools.config import expand_args_fields, get_default_args +from pytorch3d.renderer.cameras import look_at_view_transform, PerspectiveCameras +from tests.common_testing import get_pytorch3d_dir + +from .common_resources import provide_resnet34 + +IMPLICITRON_CONFIGS_DIR = ( + get_pytorch3d_dir() / "projects" / "implicitron_trainer" / "configs" +) + + +class TestGenericModel(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + provide_resnet34() + + def setUp(self): + torch.manual_seed(42) + + def test_gm(self): + # Simple test of a forward and backward pass of the default GenericModel. + device = torch.device("cuda:0") + expand_args_fields(GenericModel) + model = GenericModel(render_image_height=80, render_image_width=80) + model.to(device) + self._one_model_test(model, device) + + def test_all_gm_configs(self): + # Tests all model settings in the implicitron_trainer config folder. + device = torch.device("cuda:0") + config_files = [] + + for pattern in ("repro_singleseq*.yaml", "repro_multiseq*.yaml"): + config_files.extend( + [ + f + for f in IMPLICITRON_CONFIGS_DIR.glob(pattern) + if not f.name.endswith("_base.yaml") + ] + ) + + for config_file in config_files: + with self.subTest(name=config_file.stem): + cfg = _load_model_config_from_yaml(str(config_file)) + cfg.render_image_height = 80 + cfg.render_image_width = 80 + model = GenericModel(**cfg) + model.to(device) + self._one_model_test( + model, + device, + eval_test=True, + bw_test=True, + ) + + def _one_model_test( + self, + model, + device, + n_train_cameras: int = 5, + eval_test: bool = True, + bw_test: bool = True, + ): + R, T = look_at_view_transform(azim=torch.rand(n_train_cameras) * 360) + cameras = PerspectiveCameras(R=R, T=T, device=device) + + N, H, W = n_train_cameras, model.render_image_height, model.render_image_width + + random_args = { + "camera": cameras, + "fg_probability": _random_input_tensor(N, 1, H, W, True, device), + "depth_map": _random_input_tensor(N, 1, H, W, False, device) + 0.1, + "mask_crop": _random_input_tensor(N, 1, H, W, True, device), + "sequence_name": ["sequence"] * N, + "image_rgb": _random_input_tensor(N, 3, H, W, False, device), + } + + # training foward pass + model.train() + train_preds = model( + **random_args, + evaluation_mode=EvaluationMode.TRAINING, + ) + self.assertTrue( + train_preds["objective"].isfinite().item() + ) # check finiteness of the objective + + if bw_test: + train_preds["objective"].backward() + + if eval_test: + model.eval() + with torch.no_grad(): + eval_preds = model( + **random_args, + evaluation_mode=EvaluationMode.EVALUATION, + ) + self.assertEqual( + eval_preds["images_render"].shape, + (1, 3, model.render_image_height, model.render_image_width), + ) + + def test_idr(self): + # Forward pass of GenericModel with IDR. + device = torch.device("cuda:0") + args = get_default_args(GenericModel) + args.renderer_class_type = "SignedDistanceFunctionRenderer" + args.implicit_function_class_type = "IdrFeatureField" + args.implicit_function_IdrFeatureField_args.n_harmonic_functions_xyz = 6 + + model = GenericModel(**args) + model.to(device) + + n_train_cameras = 2 + R, T = look_at_view_transform(azim=torch.rand(n_train_cameras) * 360) + cameras = PerspectiveCameras(R=R, T=T, device=device) + + defaulted_args = { + "depth_map": None, + "mask_crop": None, + "sequence_name": None, + } + + target_image_rgb = torch.rand( + (n_train_cameras, 3, model.render_image_height, model.render_image_width), + device=device, + ) + fg_probability = torch.rand( + (n_train_cameras, 1, model.render_image_height, model.render_image_width), + device=device, + ) + train_preds = model( + camera=cameras, + evaluation_mode=EvaluationMode.TRAINING, + image_rgb=target_image_rgb, + fg_probability=fg_probability, + **defaulted_args, + ) + self.assertGreater(train_preds["objective"].item(), 0) + + def test_viewpool(self): + device = torch.device("cuda:0") + args = get_default_args(GenericModel) + args.view_pooler_enabled = True + args.image_feature_extractor_class_type = "ResNetFeatureExtractor" + args.image_feature_extractor_ResNetFeatureExtractor_args.add_masks = False + model = GenericModel(**args) + model.to(device) + + n_train_cameras = 2 + R, T = look_at_view_transform(azim=torch.rand(n_train_cameras) * 360) + cameras = PerspectiveCameras(R=R, T=T, device=device) + + defaulted_args = { + "fg_probability": None, + "depth_map": None, + "mask_crop": None, + } + + target_image_rgb = torch.rand( + (n_train_cameras, 3, model.render_image_height, model.render_image_width), + device=device, + ) + train_preds = model( + camera=cameras, + evaluation_mode=EvaluationMode.TRAINING, + image_rgb=target_image_rgb, + sequence_name=["a"] * n_train_cameras, + **defaulted_args, + ) + self.assertGreater(train_preds["objective"].item(), 0) + + +def _random_input_tensor( + N: int, + C: int, + H: int, + W: int, + is_binary: bool, + device: torch.device, +) -> torch.Tensor: + T = torch.rand(N, C, H, W, device=device) + if is_binary: + T = (T > 0.5).float() + return T + + +def _load_model_config_from_yaml(config_path, strict=True) -> DictConfig: + default_cfg = get_default_args(GenericModel) + cfg = _load_model_config_from_yaml_rec(default_cfg, config_path) + return cfg + + +def _load_model_config_from_yaml_rec(cfg: DictConfig, config_path: str) -> DictConfig: + cfg_loaded = OmegaConf.load(config_path) + cfg_model_loaded = None + if "model_factory_ImplicitronModelFactory_args" in cfg_loaded: + factory_args = cfg_loaded.model_factory_ImplicitronModelFactory_args + if "model_GenericModel_args" in factory_args: + cfg_model_loaded = factory_args.model_GenericModel_args + defaults = cfg_loaded.pop("defaults", None) + if defaults is not None: + for default_name in defaults: + if default_name in ("_self_", "default_config"): + continue + default_name = os.path.splitext(default_name)[0] + defpath = os.path.join(os.path.dirname(config_path), default_name + ".yaml") + cfg = _load_model_config_from_yaml_rec(cfg, defpath) + if cfg_model_loaded is not None: + cfg = OmegaConf.merge(cfg, cfg_model_loaded) + elif cfg_model_loaded is not None: + cfg = OmegaConf.merge(cfg, cfg_model_loaded) + return cfg diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_models_renderer_base.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_models_renderer_base.py new file mode 100644 index 0000000000000000000000000000000000000000..cafd06a8d23b6fdf9f36be821d7f3ea508540bd6 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_models_renderer_base.py @@ -0,0 +1,285 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + + +import unittest + +import numpy as np + +import torch + +from pytorch3d.implicitron.models.renderer.base import ( + approximate_conical_frustum_as_gaussians, + compute_3d_diagonal_covariance_gaussian, + conical_frustum_to_gaussian, + ImplicitronRayBundle, +) +from pytorch3d.implicitron.models.renderer.ray_sampler import AbstractMaskRaySampler + +from tests.common_testing import TestCaseMixin + + +class TestRendererBase(TestCaseMixin, unittest.TestCase): + def test_implicitron_from_bins(self) -> None: + bins = torch.randn(2, 3, 4, 5) + ray_bundle = ImplicitronRayBundle( + origins=None, + directions=None, + lengths=None, + xys=None, + bins=bins, + ) + self.assertClose(ray_bundle.lengths, 0.5 * (bins[..., 1:] + bins[..., :-1])) + self.assertClose(ray_bundle.bins, bins) + + def test_implicitron_raise_value_error_bins_is_set_and_try_to_set_lengths( + self, + ) -> None: + ray_bundle = ImplicitronRayBundle( + origins=torch.rand(2, 3, 4, 3), + directions=torch.rand(2, 3, 4, 3), + lengths=None, + xys=torch.rand(2, 3, 4, 2), + bins=torch.rand(2, 3, 4, 14), + ) + with self.assertRaisesRegex( + ValueError, + "If the bins attribute is not None you cannot set the lengths attribute.", + ): + ray_bundle.lengths = torch.empty(2) + + def test_implicitron_raise_value_error_if_bins_dim_equal_1(self) -> None: + with self.assertRaisesRegex( + ValueError, "The last dim of bins must be at least superior or equal to 2." + ): + ImplicitronRayBundle( + origins=torch.rand(2, 3, 4, 3), + directions=torch.rand(2, 3, 4, 3), + lengths=None, + xys=torch.rand(2, 3, 4, 2), + bins=torch.rand(2, 3, 4, 1), + ) + + def test_implicitron_raise_value_error_if_neither_bins_or_lengths_provided( + self, + ) -> None: + with self.assertRaisesRegex( + ValueError, + "Please set either bins or lengths to initialize an ImplicitronRayBundle.", + ): + ImplicitronRayBundle( + origins=torch.rand(2, 3, 4, 3), + directions=torch.rand(2, 3, 4, 3), + lengths=None, + xys=torch.rand(2, 3, 4, 2), + bins=None, + ) + + def test_conical_frustum_to_gaussian(self) -> None: + origins = torch.zeros(3, 3, 3) + directions = torch.tensor( + [ + [[0, 0, 0], [1, 0, 0], [3, 0, 0]], + [[0, 0.25, 0], [1, 0.25, 0], [3, 0.25, 0]], + [[0, 1, 0], [1, 1, 0], [3, 1, 0]], + ] + ) + bins = torch.tensor( + [ + [[0.5, 1.5], [0.3, 0.7], [0.3, 0.7]], + [[0.5, 1.5], [0.3, 0.7], [0.3, 0.7]], + [[0.5, 1.5], [0.3, 0.7], [0.3, 0.7]], + ] + ) + # see test_compute_pixel_radii_from_ray_direction + radii = torch.tensor( + [ + [1.25, 2.25, 2.25], + [1.75, 2.75, 2.75], + [1.75, 2.75, 2.75], + ] + ) + radii = radii[..., None] / 12**0.5 + + # The expected mean and diagonal covariance have been computed + # by hand from the official code of MipNerf. + # https://github.com/google/mipnerf/blob/84c969e0a623edd183b75693aed72a7e7c22902d/internal/mip.py#L125 + # mean, cov_diag = cast_rays(length, origins, directions, radii, 'cone', diag=True) + + expected_mean = torch.tensor( + [ + [ + [[0.0, 0.0, 0.0]], + [[0.5506329, 0.0, 0.0]], + [[1.6518986, 0.0, 0.0]], + ], + [ + [[0.0, 0.28846154, 0.0]], + [[0.5506329, 0.13765822, 0.0]], + [[1.6518986, 0.13765822, 0.0]], + ], + [ + [[0.0, 1.1538461, 0.0]], + [[0.5506329, 0.5506329, 0.0]], + [[1.6518986, 0.5506329, 0.0]], + ], + ] + ) + expected_diag_cov = torch.tensor( + [ + [ + [[0.04544772, 0.04544772, 0.04544772]], + [[0.01130973, 0.03317059, 0.03317059]], + [[0.10178753, 0.03317059, 0.03317059]], + ], + [ + [[0.08907752, 0.00404956, 0.08907752]], + [[0.0142245, 0.04734321, 0.04955113]], + [[0.10212927, 0.04991625, 0.04955113]], + ], + [ + [[0.08907752, 0.0647929, 0.08907752]], + [[0.03608529, 0.03608529, 0.04955113]], + [[0.10674264, 0.05590574, 0.04955113]], + ], + ] + ) + + ray = ImplicitronRayBundle( + origins=origins, + directions=directions, + bins=bins, + lengths=None, + pixel_radii_2d=radii, + xys=None, + ) + mean, diag_cov = conical_frustum_to_gaussian(ray) + + self.assertClose(mean, expected_mean) + self.assertClose(diag_cov, expected_diag_cov) + + def test_scale_conical_frustum_to_gaussian(self) -> None: + origins = torch.zeros(2, 2, 3) + directions = torch.Tensor( + [ + [[0, 1, 0], [0, 0, 1]], + [[0, 1, 0], [0, 0, 1]], + ] + ) + bins = torch.Tensor( + [ + [[0.5, 1.5], [0.3, 0.7]], + [[0.5, 1.5], [0.3, 0.7]], + ] + ) + radii = torch.ones(2, 2, 1) + + ray = ImplicitronRayBundle( + origins=origins, + directions=directions, + bins=bins, + pixel_radii_2d=radii, + lengths=None, + xys=None, + ) + + mean, diag_cov = conical_frustum_to_gaussian(ray) + + scaling_factor = 2.5 + ray = ImplicitronRayBundle( + origins=origins, + directions=directions, + bins=bins * scaling_factor, + pixel_radii_2d=radii, + lengths=None, + xys=None, + ) + mean_scaled, diag_cov_scaled = conical_frustum_to_gaussian(ray) + np.testing.assert_allclose(mean * scaling_factor, mean_scaled) + np.testing.assert_allclose( + diag_cov * scaling_factor**2, diag_cov_scaled, atol=1e-6 + ) + + def test_approximate_conical_frustum_as_gaussian(self) -> None: + """Ensure that the computation modularity in our function is well done.""" + bins = torch.Tensor([[0.5, 1.5], [0.3, 0.7]]) + radii = torch.Tensor([[1.0], [1.0]]) + t_mean, t_var, r_var = approximate_conical_frustum_as_gaussians(bins, radii) + + self.assertEqual(t_mean.shape, (2, 1)) + self.assertEqual(t_var.shape, (2, 1)) + self.assertEqual(r_var.shape, (2, 1)) + + mu = np.array([[1.0], [0.5]]) + delta = np.array([[0.5], [0.2]]) + + np.testing.assert_allclose( + mu + (2 * mu * delta**2) / (3 * mu**2 + delta**2), t_mean.numpy() + ) + np.testing.assert_allclose( + (delta**2) / 3 + - (4 / 15) + * ((delta**4 * (12 * mu**2 - delta**2)) / (3 * mu**2 + delta**2) ** 2), + t_var.numpy(), + ) + np.testing.assert_allclose( + radii**2 + * ( + (mu**2) / 4 + + (5 / 12) * delta**2 + - 4 / 15 * (delta**4) / (3 * mu**2 + delta**2) + ), + r_var.numpy(), + ) + + def test_compute_3d_diagonal_covariance_gaussian(self) -> None: + ray_directions = torch.Tensor([[0, 0, 1]]) + t_var = torch.Tensor([0.5, 0.5, 1]) + r_var = torch.Tensor([0.6, 0.3, 0.4]) + expected_diag_cov = np.array( + [ + [ + # t_cov_diag + xy_cov_diag + [0.0 + 0.6, 0.0 + 0.6, 0.5 + 0.0], + [0.0 + 0.3, 0.0 + 0.3, 0.5 + 0.0], + [0.0 + 0.4, 0.0 + 0.4, 1.0 + 0.0], + ] + ] + ) + diag_cov = compute_3d_diagonal_covariance_gaussian(ray_directions, t_var, r_var) + np.testing.assert_allclose(diag_cov.numpy(), expected_diag_cov) + + def test_conical_frustum_to_gaussian_raise_valueerror(self) -> None: + lengths = torch.linspace(0, 1, steps=6) + directions = torch.tensor([0, 0, 1]) + origins = torch.tensor([1, 1, 1]) + ray = ImplicitronRayBundle( + origins=origins, directions=directions, lengths=lengths, xys=None + ) + + expected_error_message = ( + "RayBundle pixel_radii_2d or bins have not been provided." + " Look at pytorch3d.renderer.implicit.renderer.ray_sampler::" + "AbstractMaskRaySampler to see how to compute them. Have you forgot to set" + "`cast_ray_bundle_as_cone` to True?" + ) + + with self.assertRaisesRegex(ValueError, expected_error_message): + _ = conical_frustum_to_gaussian(ray) + + # Ensure message is coherent with AbstractMaskRaySampler + class FakeRaySampler(AbstractMaskRaySampler): + def _get_min_max_depth_bounds(self, *args): + return None + + message_assertion = ( + "If cast_ray_bundle_as_cone has been removed please update the doc" + "conical_frustum_to_gaussian" + ) + self.assertIsNotNone( + getattr(FakeRaySampler(), "cast_ray_bundle_as_cone", None), + message_assertion, + ) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_models_renderer_ray_sampler.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_models_renderer_ray_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..17c1d1326a1911e7fbeff5bc636962fb13437b13 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_models_renderer_ray_sampler.py @@ -0,0 +1,290 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import unittest +from itertools import product +from typing import Tuple + +from unittest.mock import patch + +import torch +from pytorch3d.common.compat import meshgrid_ij +from pytorch3d.implicitron.models.renderer.base import EvaluationMode +from pytorch3d.implicitron.models.renderer.ray_sampler import ( + AdaptiveRaySampler, + compute_radii, + NearFarRaySampler, +) + +from pytorch3d.renderer.cameras import ( + CamerasBase, + FoVOrthographicCameras, + FoVPerspectiveCameras, + OrthographicCameras, + PerspectiveCameras, +) +from pytorch3d.renderer.implicit.utils import HeterogeneousRayBundle +from tests.common_camera_utils import init_random_cameras + +from tests.common_testing import TestCaseMixin + +CAMERA_TYPES = ( + FoVPerspectiveCameras, + FoVOrthographicCameras, + OrthographicCameras, + PerspectiveCameras, +) + + +def unproject_xy_grid_from_ndc_to_world_coord( + cameras: CamerasBase, xy_grid: torch.Tensor +) -> Tuple[torch.Tensor, torch.Tensor]: + """ + + Unproject a xy_grid from NDC coordinates to world coordinates. + + Args: + cameras: CamerasBase. + xy_grid: A tensor of shape `(..., H*W, 2)` representing the + x, y coords. + + Returns: + A tensor of shape `(..., H*W, 3)` representing the + """ + + batch_size = xy_grid.shape[0] + n_rays_per_image = xy_grid.shape[1:-1].numel() + xy = xy_grid.view(batch_size, -1, 2) + xyz = torch.cat([xy, xy_grid.new_ones(batch_size, n_rays_per_image, 1)], dim=-1) + plane_at_depth1 = cameras.unproject_points(xyz, from_ndc=True) + return plane_at_depth1.view(*xy_grid.shape[:-1], 3) + + +class TestRaysampler(TestCaseMixin, unittest.TestCase): + def test_ndc_raysampler_n_ray_total_is_none(self): + sampler = NearFarRaySampler() + message = ( + "If you introduce the support of `n_rays_total` for {0}, please handle the " + "packing and unpacking logic for the radii and lengths computation." + ) + self.assertIsNone( + sampler._training_raysampler._n_rays_total, message.format(type(sampler)) + ) + self.assertIsNone( + sampler._evaluation_raysampler._n_rays_total, message.format(type(sampler)) + ) + + sampler = AdaptiveRaySampler() + self.assertIsNone( + sampler._training_raysampler._n_rays_total, message.format(type(sampler)) + ) + self.assertIsNone( + sampler._evaluation_raysampler._n_rays_total, message.format(type(sampler)) + ) + + def test_catch_heterogeneous_exception(self): + cameras = init_random_cameras(FoVPerspectiveCameras, 1, random_z=True) + + class FakeSampler: + def __init__(self): + self.min_x, self.max_x = 1, 2 + self.min_y, self.max_y = 1, 2 + + def __call__(self, **kwargs): + return HeterogeneousRayBundle( + torch.rand(3), torch.rand(3), torch.rand(3), torch.rand(1) + ) + + with patch( + "pytorch3d.implicitron.models.renderer.ray_sampler.NDCMultinomialRaysampler", + return_value=FakeSampler(), + ): + for sampler in [ + AdaptiveRaySampler(cast_ray_bundle_as_cone=True), + NearFarRaySampler(cast_ray_bundle_as_cone=True), + ]: + with self.assertRaises(TypeError): + _ = sampler(cameras, EvaluationMode.TRAINING) + for sampler in [ + AdaptiveRaySampler(cast_ray_bundle_as_cone=False), + NearFarRaySampler(cast_ray_bundle_as_cone=False), + ]: + _ = sampler(cameras, EvaluationMode.TRAINING) + + def test_compute_radii(self): + batch_size = 1 + image_height, image_width = 20, 10 + min_y, max_y, min_x, max_x = -1.0, 1.0, -1.0, 1.0 + y, x = meshgrid_ij( + torch.linspace(min_y, max_y, image_height, dtype=torch.float32), + torch.linspace(min_x, max_x, image_width, dtype=torch.float32), + ) + xy_grid = torch.stack([x, y], dim=-1).view(-1, 2) + pixel_width = (max_x - min_x) / (image_width - 1) + pixel_height = (max_y - min_y) / (image_height - 1) + + for cam_type in CAMERA_TYPES: + # init a batch of random cameras + cameras = init_random_cameras(cam_type, batch_size, random_z=True) + # This method allow us to compute the radii whithout having + # access to the full grid. Raysamplers during the training + # will sample random rays from the grid. + radii = compute_radii( + cameras, xy_grid, pixel_hw_ndc=(pixel_height, pixel_width) + ) + plane_at_depth1 = unproject_xy_grid_from_ndc_to_world_coord( + cameras, xy_grid + ) + # This method absolutely needs the full grid to work. + expected_radii = compute_pixel_radii_from_grid( + plane_at_depth1.reshape(1, image_height, image_width, 3) + ) + self.assertClose(expected_radii.reshape(-1, 1), radii) + + def test_forward(self): + n_rays_per_image = 16 + image_height, image_width = 20, 20 + kwargs = { + "image_width": image_width, + "image_height": image_height, + "n_pts_per_ray_training": 32, + "n_pts_per_ray_evaluation": 32, + "n_rays_per_image_sampled_from_mask": n_rays_per_image, + "cast_ray_bundle_as_cone": False, + } + + batch_size = 2 + samplers = [NearFarRaySampler(**kwargs), AdaptiveRaySampler(**kwargs)] + evaluation_modes = [EvaluationMode.TRAINING, EvaluationMode.EVALUATION] + + for cam_type, sampler, evaluation_mode in product( + CAMERA_TYPES, samplers, evaluation_modes + ): + cameras = init_random_cameras(cam_type, batch_size, random_z=True) + ray_bundle = sampler(cameras, evaluation_mode) + + shape_out = ( + (batch_size, image_width, image_height) + if evaluation_mode == EvaluationMode.EVALUATION + else (batch_size, n_rays_per_image, 1) + ) + n_pts_per_ray = ( + kwargs["n_pts_per_ray_evaluation"] + if evaluation_mode == EvaluationMode.EVALUATION + else kwargs["n_pts_per_ray_training"] + ) + self.assertIsNone(ray_bundle.bins) + self.assertIsNone(ray_bundle.pixel_radii_2d) + self.assertEqual( + ray_bundle.lengths.shape, + (*shape_out, n_pts_per_ray), + ) + self.assertEqual(ray_bundle.directions.shape, (*shape_out, 3)) + self.assertEqual(ray_bundle.origins.shape, (*shape_out, 3)) + + def test_forward_with_use_bins(self): + n_rays_per_image = 16 + image_height, image_width = 20, 20 + kwargs = { + "image_width": image_width, + "image_height": image_height, + "n_pts_per_ray_training": 32, + "n_pts_per_ray_evaluation": 32, + "n_rays_per_image_sampled_from_mask": n_rays_per_image, + "cast_ray_bundle_as_cone": True, + } + + batch_size = 1 + samplers = [NearFarRaySampler(**kwargs), AdaptiveRaySampler(**kwargs)] + evaluation_modes = [EvaluationMode.TRAINING, EvaluationMode.EVALUATION] + for cam_type, sampler, evaluation_mode in product( + CAMERA_TYPES, samplers, evaluation_modes + ): + cameras = init_random_cameras(cam_type, batch_size, random_z=True) + ray_bundle = sampler(cameras, evaluation_mode) + + lengths = 0.5 * (ray_bundle.bins[..., :-1] + ray_bundle.bins[..., 1:]) + + self.assertClose(ray_bundle.lengths, lengths) + shape_out = ( + (batch_size, image_width, image_height) + if evaluation_mode == EvaluationMode.EVALUATION + else (batch_size, n_rays_per_image, 1) + ) + self.assertEqual(ray_bundle.pixel_radii_2d.shape, (*shape_out, 1)) + self.assertEqual(ray_bundle.directions.shape, (*shape_out, 3)) + self.assertEqual(ray_bundle.origins.shape, (*shape_out, 3)) + + +# Helper to test compute_radii +def compute_pixel_radii_from_grid(pixel_grid: torch.Tensor) -> torch.Tensor: + """ + Compute the radii of a conical frustum given the pixel grid. + + To compute the radii we first compute the translation from a pixel + to its neighbors along the x and y axis. Then, we compute the norm + of each translation along the x and y axis. + The radii are then obtained by the following formula: + + (dx_norm + dy_norm) * 0.5 * 2 / 12**0.5 + + where 2/12**0.5 is a scaling factor to match + the variance of the pixel’s footprint. + + Args: + pixel_grid: A tensor of shape `(..., H, W, dim)` representing the + full grid of rays pixel_grid. + + Returns: + The radiis for each pixels and shape `(..., H, W, 1)`. + """ + # [B, H, W - 1, 3] + x_translation = torch.diff(pixel_grid, dim=-2) + # [B, H - 1, W, 3] + y_translation = torch.diff(pixel_grid, dim=-3) + # [B, H, W - 1, 1] + dx_norm = torch.linalg.norm(x_translation, dim=-1, keepdim=True) + # [B, H - 1, W, 1] + dy_norm = torch.linalg.norm(y_translation, dim=-1, keepdim=True) + + # Fill the missing value [B, H, W, 1] + dx_norm = torch.concatenate([dx_norm, dx_norm[..., -1:, :]], -2) + dy_norm = torch.concatenate([dy_norm, dy_norm[..., -1:, :, :]], -3) + + # Cut the distance in half to obtain the base radius: (dx_norm + dy_norm) * 0.5 + # and multiply it by the scaling factor: * 2 / 12**0.5 + radii = (dx_norm + dy_norm) / 12**0.5 + return radii + + +class TestRadiiComputationOnFullGrid(TestCaseMixin, unittest.TestCase): + def test_compute_pixel_radii_from_grid(self): + pixel_grid = torch.tensor( + [ + [[0.0, 0, 0], [1.0, 0.0, 0], [3.0, 0.0, 0.0]], + [[0.0, 0.25, 0], [1.0, 0.25, 0], [3.0, 0.25, 0]], + [[0.0, 1, 0], [1.0, 1.0, 0], [3.0000, 1.0, 0]], + ] + ) + + expected_y_norm = torch.tensor( + [ + [0.25, 0.25, 0.25], + [0.75, 0.75, 0.75], + [0.75, 0.75, 0.75], # duplicated from previous row + ] + ) + expected_x_norm = torch.tensor( + [ + # 3rd column is duplicated from 2nd + [1.0, 2.0, 2.0], + [1.0, 2.0, 2.0], + [1.0, 2.0, 2.0], + ] + ) + expected_radii = (expected_x_norm + expected_y_norm) / 12**0.5 + radii = compute_pixel_radii_from_grid(pixel_grid) + self.assertClose(radii, expected_radii[..., None]) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_orm_types.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_orm_types.py new file mode 100644 index 0000000000000000000000000000000000000000..e6f94c0100ffc5d8ca111a553b21861b881c206a --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_orm_types.py @@ -0,0 +1,62 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import unittest + +import numpy as np + +from pytorch3d.implicitron.dataset.orm_types import ArrayTypeFactory, TupleTypeFactory + + +class TestOrmTypes(unittest.TestCase): + def test_tuple_serialization_none(self): + ttype = TupleTypeFactory()() + output = ttype.process_bind_param(None, None) + self.assertIsNone(output) + output = ttype.process_result_value(output, None) + self.assertIsNone(output) + + def test_tuple_serialization_1d(self): + for input_tuple in [(1, 2, 3), (4.5, 6.7)]: + ttype = TupleTypeFactory(type(input_tuple[0]), (len(input_tuple),))() + output = ttype.process_bind_param(input_tuple, None) + input_hat = ttype.process_result_value(output, None) + self.assertEqual(type(input_hat[0]), type(input_tuple[0])) + np.testing.assert_almost_equal(input_hat, input_tuple, decimal=6) + + def test_tuple_serialization_2d(self): + input_tuple = ((1.0, 2.0, 3.0), (4.5, 5.5, 6.6)) + ttype = TupleTypeFactory(type(input_tuple[0][0]), (2, 3))() + output = ttype.process_bind_param(input_tuple, None) + input_hat = ttype.process_result_value(output, None) + self.assertEqual(type(input_hat[0][0]), type(input_tuple[0][0])) + # we use float32 to serialise + np.testing.assert_almost_equal(input_hat, input_tuple, decimal=6) + + def test_array_serialization_none(self): + ttype = ArrayTypeFactory((3, 3))() + output = ttype.process_bind_param(None, None) + self.assertIsNone(output) + output = ttype.process_result_value(output, None) + self.assertIsNone(output) + + def test_array_serialization(self): + for input_list in [[1, 2, 3], [[4.5, 6.7], [8.9, 10.0]]]: + input_array = np.array(input_list) + + # first, dynamic-size array + ttype = ArrayTypeFactory()() + output = ttype.process_bind_param(input_array, None) + input_hat = ttype.process_result_value(output, None) + self.assertEqual(input_hat.dtype, np.float32) + np.testing.assert_almost_equal(input_hat, input_array, decimal=6) + + # second, fixed-size array + ttype = ArrayTypeFactory(tuple(input_array.shape))() + output = ttype.process_bind_param(input_array, None) + input_hat = ttype.process_result_value(output, None) + self.assertEqual(input_hat.dtype, np.float32) + np.testing.assert_almost_equal(input_hat, input_array, decimal=6) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_ray_point_refiner.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_ray_point_refiner.py new file mode 100644 index 0000000000000000000000000000000000000000..8a6ab36126cf8baab4e0854ba7f4e9574ceaf43f --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_ray_point_refiner.py @@ -0,0 +1,157 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import unittest +from itertools import product + +import torch + +from pytorch3d.implicitron.models.renderer.ray_point_refiner import ( + apply_blurpool_on_weights, + RayPointRefiner, +) +from pytorch3d.implicitron.models.renderer.ray_sampler import ImplicitronRayBundle +from tests.common_testing import TestCaseMixin + + +class TestRayPointRefiner(TestCaseMixin, unittest.TestCase): + def test_simple(self): + length = 15 + n_pts_per_ray = 10 + + for add_input_samples, use_blurpool in product([False, True], [False, True]): + ray_point_refiner = RayPointRefiner( + n_pts_per_ray=n_pts_per_ray, + random_sampling=False, + add_input_samples=add_input_samples, + blurpool_weights=use_blurpool, + ) + lengths = torch.arange(length, dtype=torch.float32).expand(3, 25, length) + bundle = ImplicitronRayBundle( + lengths=lengths, + origins=None, + directions=None, + xys=None, + camera_ids=None, + camera_counts=None, + ) + weights = torch.ones(3, 25, length) + refined = ray_point_refiner(bundle, weights) + + self.assertIsNone(refined.directions) + self.assertIsNone(refined.origins) + self.assertIsNone(refined.xys) + expected = torch.linspace(0.5, length - 1.5, n_pts_per_ray) + expected = expected.expand(3, 25, n_pts_per_ray) + if add_input_samples: + full_expected = torch.cat((lengths, expected), dim=-1).sort()[0] + else: + full_expected = expected + self.assertClose(refined.lengths, full_expected) + + ray_point_refiner_random = RayPointRefiner( + n_pts_per_ray=n_pts_per_ray, + random_sampling=True, + add_input_samples=add_input_samples, + blurpool_weights=use_blurpool, + ) + refined_random = ray_point_refiner_random(bundle, weights) + lengths_random = refined_random.lengths + self.assertEqual(lengths_random.shape, full_expected.shape) + if not add_input_samples: + self.assertGreater(lengths_random.min().item(), 0.5) + self.assertLess(lengths_random.max().item(), length - 1.5) + + # Check sorted + self.assertTrue( + (lengths_random[..., 1:] - lengths_random[..., :-1] > 0).all() + ) + + def test_simple_use_bins(self): + """ + Same spirit than test_simple but use bins in the ImplicitronRayBunle. + It has been duplicated to avoid cognitive overload while reading the + test (lot of if else). + """ + length = 15 + n_pts_per_ray = 10 + + for add_input_samples, use_blurpool in product([False, True], [False, True]): + ray_point_refiner = RayPointRefiner( + n_pts_per_ray=n_pts_per_ray, + random_sampling=False, + add_input_samples=add_input_samples, + ) + + bundle = ImplicitronRayBundle( + lengths=None, + bins=torch.arange(length + 1, dtype=torch.float32).expand( + 3, 25, length + 1 + ), + origins=None, + directions=None, + xys=None, + camera_ids=None, + camera_counts=None, + ) + weights = torch.ones(3, 25, length) + refined = ray_point_refiner(bundle, weights, blurpool_weights=use_blurpool) + + self.assertIsNone(refined.directions) + self.assertIsNone(refined.origins) + self.assertIsNone(refined.xys) + expected_bins = torch.linspace(0, length, n_pts_per_ray + 1) + expected_bins = expected_bins.expand(3, 25, n_pts_per_ray + 1) + if add_input_samples: + expected_bins = torch.cat((bundle.bins, expected_bins), dim=-1).sort()[ + 0 + ] + full_expected = torch.lerp( + expected_bins[..., :-1], expected_bins[..., 1:], 0.5 + ) + + self.assertClose(refined.lengths, full_expected) + + ray_point_refiner_random = RayPointRefiner( + n_pts_per_ray=n_pts_per_ray, + random_sampling=True, + add_input_samples=add_input_samples, + ) + + refined_random = ray_point_refiner_random( + bundle, weights, blurpool_weights=use_blurpool + ) + lengths_random = refined_random.lengths + self.assertEqual(lengths_random.shape, full_expected.shape) + if not add_input_samples: + self.assertGreater(lengths_random.min().item(), 0) + self.assertLess(lengths_random.max().item(), length) + + # Check sorted + self.assertTrue( + (lengths_random[..., 1:] - lengths_random[..., :-1] > 0).all() + ) + + def test_apply_blurpool_on_weights(self): + weights = torch.tensor( + [ + [0.5, 0.6, 0.7], + [0.5, 0.3, 0.9], + ] + ) + expected_weights = 0.5 * torch.tensor( + [ + [0.5 + 0.6, 0.6 + 0.7, 0.7 + 0.7], + [0.5 + 0.5, 0.5 + 0.9, 0.9 + 0.9], + ] + ) + out_weights = apply_blurpool_on_weights(weights) + self.assertTrue(torch.allclose(out_weights, expected_weights)) + + def test_shapes_apply_blurpool_on_weights(self): + weights = torch.randn((5, 4, 3, 2, 1)) + out_weights = apply_blurpool_on_weights(weights) + self.assertEqual((5, 4, 3, 2, 1), out_weights.shape) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_sql_dataset.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_sql_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..f5baf505752545579a7e069ef6d00b17ccc315a8 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_sql_dataset.py @@ -0,0 +1,546 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import logging +import os +import unittest +from collections import Counter + +import pkg_resources + +import torch + +from pytorch3d.implicitron.dataset.sql_dataset import SqlIndexDataset + +NO_BLOBS_KWARGS = { + "dataset_root": "", + "load_images": False, + "load_depths": False, + "load_masks": False, + "load_depth_masks": False, + "box_crop": False, +} + +logger = logging.getLogger("pytorch3d.implicitron.dataset.sql_dataset") +sh = logging.StreamHandler() +logger.addHandler(sh) +logger.setLevel(logging.DEBUG) + + +DATASET_ROOT = pkg_resources.resource_filename(__name__, "data/sql_dataset") +METADATA_FILE = os.path.join(DATASET_ROOT, "sql_dataset_100.sqlite") +SET_LIST_FILE = os.path.join(DATASET_ROOT, "set_lists_100.json") + + +class TestSqlDataset(unittest.TestCase): + def test_basic(self, sequence="cat1_seq2", frame_number=4): + dataset = SqlIndexDataset( + sqlite_metadata_file=METADATA_FILE, + remove_empty_masks=False, + frame_data_builder_FrameDataBuilder_args=NO_BLOBS_KWARGS, + ) + + self.assertEqual(len(dataset), 100) + + # check the items are consecutive + past_sequences = set() + last_frame_number = -1 + last_sequence = "" + for i in range(len(dataset)): + item = dataset[i] + + if item.frame_number == 0: + self.assertNotIn(item.sequence_name, past_sequences) + past_sequences.add(item.sequence_name) + last_sequence = item.sequence_name + else: + self.assertEqual(item.sequence_name, last_sequence) + self.assertEqual(item.frame_number, last_frame_number + 1) + + last_frame_number = item.frame_number + + # test indexing + with self.assertRaises(IndexError): + dataset[len(dataset) + 1] + + # test sequence-frame indexing + item = dataset[sequence, frame_number] + self.assertEqual(item.sequence_name, sequence) + self.assertEqual(item.frame_number, frame_number) + + with self.assertRaises(IndexError): + dataset[sequence, 13] + + def test_filter_empty_masks(self): + dataset = SqlIndexDataset( + sqlite_metadata_file=METADATA_FILE, + remove_empty_masks=True, + frame_data_builder_FrameDataBuilder_args=NO_BLOBS_KWARGS, + ) + + self.assertEqual(len(dataset), 78) + + def test_pick_frames_sql_clause(self): + dataset_no_empty_masks = SqlIndexDataset( + sqlite_metadata_file=METADATA_FILE, + remove_empty_masks=True, + frame_data_builder_FrameDataBuilder_args=NO_BLOBS_KWARGS, + ) + + dataset = SqlIndexDataset( + sqlite_metadata_file=METADATA_FILE, + remove_empty_masks=False, + pick_frames_sql_clause="_mask_mass IS NULL OR _mask_mass > 0", + frame_data_builder_FrameDataBuilder_args=NO_BLOBS_KWARGS, + ) + + # check the datasets are equal + self.assertEqual(len(dataset), len(dataset_no_empty_masks)) + for i in range(len(dataset)): + item_nem = dataset_no_empty_masks[i] + item = dataset[i] + self.assertEqual(item_nem.image_path, item.image_path) + + # remove_empty_masks together with the custom criterion + dataset_ts = SqlIndexDataset( + sqlite_metadata_file=METADATA_FILE, + remove_empty_masks=True, + pick_frames_sql_clause="frame_timestamp < 0.15", + frame_data_builder_FrameDataBuilder_args=NO_BLOBS_KWARGS, + ) + self.assertEqual(len(dataset_ts), 19) + + def test_limit_categories(self, category="cat0"): + dataset = SqlIndexDataset( + sqlite_metadata_file=METADATA_FILE, + remove_empty_masks=False, + pick_categories=[category], + frame_data_builder_FrameDataBuilder_args=NO_BLOBS_KWARGS, + ) + + self.assertEqual(len(dataset), 50) + for i in range(len(dataset)): + self.assertEqual(dataset[i].sequence_category, category) + + def test_limit_sequences(self, num_sequences=3): + dataset = SqlIndexDataset( + sqlite_metadata_file=METADATA_FILE, + remove_empty_masks=False, + limit_sequences_to=num_sequences, + frame_data_builder_FrameDataBuilder_args=NO_BLOBS_KWARGS, + ) + + self.assertEqual(len(dataset), 10 * num_sequences) + + def delist(sequence_name): + return sequence_name if isinstance(sequence_name, str) else sequence_name[0] + + unique_seqs = {delist(dataset[i].sequence_name) for i in range(len(dataset))} + self.assertEqual(len(unique_seqs), num_sequences) + + def test_pick_exclude_sequencess(self, sequence="cat1_seq2"): + # pick sequence + dataset = SqlIndexDataset( + sqlite_metadata_file=METADATA_FILE, + remove_empty_masks=False, + pick_sequences=[sequence], + frame_data_builder_FrameDataBuilder_args=NO_BLOBS_KWARGS, + ) + + self.assertEqual(len(dataset), 10) + unique_seqs = {dataset[i].sequence_name for i in range(len(dataset))} + self.assertCountEqual(unique_seqs, {sequence}) + + item = dataset[sequence, 0] + self.assertEqual(item.sequence_name, sequence) + self.assertEqual(item.frame_number, 0) + + # exclude sequence + dataset = SqlIndexDataset( + sqlite_metadata_file=METADATA_FILE, + remove_empty_masks=False, + exclude_sequences=[sequence], + frame_data_builder_FrameDataBuilder_args=NO_BLOBS_KWARGS, + ) + + self.assertEqual(len(dataset), 90) + unique_seqs = {dataset[i].sequence_name for i in range(len(dataset))} + self.assertNotIn(sequence, unique_seqs) + + with self.assertRaises(IndexError): + dataset[sequence, 0] + + def test_limit_frames(self, num_frames=13): + dataset = SqlIndexDataset( + sqlite_metadata_file=METADATA_FILE, + remove_empty_masks=False, + limit_to=num_frames, + frame_data_builder_FrameDataBuilder_args=NO_BLOBS_KWARGS, + ) + + self.assertEqual(len(dataset), num_frames) + unique_seqs = {dataset[i].sequence_name for i in range(len(dataset))} + self.assertEqual(len(unique_seqs), 2) + + # test when the limit is not binding + dataset = SqlIndexDataset( + sqlite_metadata_file=METADATA_FILE, + remove_empty_masks=False, + limit_to=1000, + frame_data_builder_FrameDataBuilder_args=NO_BLOBS_KWARGS, + ) + + self.assertEqual(len(dataset), 100) + + def test_limit_frames_per_sequence(self, num_frames=2): + dataset = SqlIndexDataset( + sqlite_metadata_file=METADATA_FILE, + remove_empty_masks=False, + n_frames_per_sequence=num_frames, + frame_data_builder_FrameDataBuilder_args=NO_BLOBS_KWARGS, + ) + + self.assertEqual(len(dataset), num_frames * 10) + seq_counts = Counter(dataset[i].sequence_name for i in range(len(dataset))) + self.assertEqual(len(seq_counts), 10) + self.assertCountEqual( + set(seq_counts.values()), {2} + ) # all counts are num_frames + + with self.assertRaises(IndexError): + dataset[next(iter(seq_counts)), num_frames + 1] + + # test when the limit is not binding + dataset = SqlIndexDataset( + sqlite_metadata_file=METADATA_FILE, + remove_empty_masks=False, + n_frames_per_sequence=13, + frame_data_builder_FrameDataBuilder_args=NO_BLOBS_KWARGS, + ) + self.assertEqual(len(dataset), 100) + + def test_limit_sequence_per_category(self, num_sequences=2): + dataset = SqlIndexDataset( + sqlite_metadata_file=METADATA_FILE, + remove_empty_masks=False, + limit_sequences_per_category_to=num_sequences, + frame_data_builder_FrameDataBuilder_args=NO_BLOBS_KWARGS, + ) + + self.assertEqual(len(dataset), num_sequences * 10 * 2) + seq_names = list(dataset.sequence_names()) + self.assertEqual(len(seq_names), num_sequences * 2) + # check that we respect the row order + for seq_name in seq_names: + self.assertLess(int(seq_name[-1]), num_sequences) + + # test when the limit is not binding + dataset = SqlIndexDataset( + sqlite_metadata_file=METADATA_FILE, + remove_empty_masks=False, + limit_sequences_per_category_to=13, + frame_data_builder_FrameDataBuilder_args=NO_BLOBS_KWARGS, + ) + self.assertEqual(len(dataset), 100) + + def test_filter_medley(self): + dataset = SqlIndexDataset( + sqlite_metadata_file=METADATA_FILE, + remove_empty_masks=True, + pick_categories=["cat1"], + exclude_sequences=["cat1_seq0"], # retaining "cat1_seq1" and on + limit_sequences_to=2, # retaining "cat1_seq1" and "cat1_seq2" + limit_to=14, # retaining full "cat1_seq1" and 4 from "cat1_seq2" + n_frames_per_sequence=6, # cutting "cat1_seq1" to 6 frames + frame_data_builder_FrameDataBuilder_args=NO_BLOBS_KWARGS, + ) + + # result: preserved 6 frames from cat1_seq1 and 4 from cat1_seq2 + seq_counts = Counter(dataset[i].sequence_name for i in range(len(dataset))) + self.assertCountEqual(seq_counts.keys(), ["cat1_seq1", "cat1_seq2"]) + self.assertEqual(seq_counts["cat1_seq1"], 6) + self.assertEqual(seq_counts["cat1_seq2"], 4) + + def test_subsets_trivial(self): + dataset = SqlIndexDataset( + sqlite_metadata_file=METADATA_FILE, + remove_empty_masks=False, + subset_lists_file=SET_LIST_FILE, + limit_to=100, # force sorting + subsets=["train", "test"], + frame_data_builder_FrameDataBuilder_args=NO_BLOBS_KWARGS, + ) + + self.assertEqual(len(dataset), 100) + + # check the items are consecutive + past_sequences = set() + last_frame_number = -1 + last_sequence = "" + for i in range(len(dataset)): + item = dataset[i] + + if item.frame_number == 0: + self.assertNotIn(item.sequence_name, past_sequences) + past_sequences.add(item.sequence_name) + last_sequence = item.sequence_name + else: + self.assertEqual(item.sequence_name, last_sequence) + self.assertEqual(item.frame_number, last_frame_number + 1) + + last_frame_number = item.frame_number + + def test_subsets_filter_empty_masks(self): + # we need to test this case as it uses quite different logic with `df.drop()` + dataset = SqlIndexDataset( + sqlite_metadata_file=METADATA_FILE, + remove_empty_masks=True, + subset_lists_file=SET_LIST_FILE, + subsets=["train", "test"], + frame_data_builder_FrameDataBuilder_args=NO_BLOBS_KWARGS, + ) + + self.assertEqual(len(dataset), 78) + + def test_subsets_pick_frames_sql_clause(self): + dataset_no_empty_masks = SqlIndexDataset( + sqlite_metadata_file=METADATA_FILE, + remove_empty_masks=True, + subset_lists_file=SET_LIST_FILE, + subsets=["train", "test"], + frame_data_builder_FrameDataBuilder_args=NO_BLOBS_KWARGS, + ) + + dataset = SqlIndexDataset( + sqlite_metadata_file=METADATA_FILE, + remove_empty_masks=False, + pick_frames_sql_clause="_mask_mass IS NULL OR _mask_mass > 0", + subset_lists_file=SET_LIST_FILE, + subsets=["train", "test"], + frame_data_builder_FrameDataBuilder_args=NO_BLOBS_KWARGS, + ) + + # check the datasets are equal + self.assertEqual(len(dataset), len(dataset_no_empty_masks)) + for i in range(len(dataset)): + item_nem = dataset_no_empty_masks[i] + item = dataset[i] + self.assertEqual(item_nem.image_path, item.image_path) + + # remove_empty_masks together with the custom criterion + dataset_ts = SqlIndexDataset( + sqlite_metadata_file=METADATA_FILE, + remove_empty_masks=True, + pick_frames_sql_clause="frame_timestamp < 0.15", + subset_lists_file=SET_LIST_FILE, + subsets=["train", "test"], + frame_data_builder_FrameDataBuilder_args=NO_BLOBS_KWARGS, + ) + + self.assertEqual(len(dataset_ts), 19) + + def test_single_subset(self): + dataset = SqlIndexDataset( + sqlite_metadata_file=METADATA_FILE, + remove_empty_masks=False, + subset_lists_file=SET_LIST_FILE, + subsets=["train"], + frame_data_builder_FrameDataBuilder_args=NO_BLOBS_KWARGS, + ) + + self.assertEqual(len(dataset), 50) + + with self.assertRaises(IndexError): + dataset[51] + + # check the items are consecutive + past_sequences = set() + last_frame_number = -1 + last_sequence = "" + for i in range(len(dataset)): + item = dataset[i] + + if item.frame_number < 2: + self.assertNotIn(item.sequence_name, past_sequences) + past_sequences.add(item.sequence_name) + last_sequence = item.sequence_name + else: + self.assertEqual(item.sequence_name, last_sequence) + self.assertEqual(item.frame_number, last_frame_number + 2) + + last_frame_number = item.frame_number + + item = dataset[last_sequence, 0] + self.assertEqual(item.sequence_name, last_sequence) + + with self.assertRaises(IndexError): + dataset[last_sequence, 1] + + def test_subset_with_filters(self): + dataset = SqlIndexDataset( + sqlite_metadata_file=METADATA_FILE, + remove_empty_masks=True, + subset_lists_file=SET_LIST_FILE, + subsets=["train"], + pick_categories=["cat1"], + exclude_sequences=["cat1_seq0"], # retaining "cat1_seq1" and on + limit_sequences_to=2, # retaining "cat1_seq1" and "cat1_seq2" + limit_to=7, # retaining full train set of "cat1_seq1" and 2 from "cat1_seq2" + n_frames_per_sequence=3, # cutting "cat1_seq1" to 3 frames + frame_data_builder_FrameDataBuilder_args=NO_BLOBS_KWARGS, + ) + + # result: preserved 6 frames from cat1_seq1 and 4 from cat1_seq2 + seq_counts = Counter(dataset[i].sequence_name for i in range(len(dataset))) + self.assertCountEqual(seq_counts.keys(), ["cat1_seq1", "cat1_seq2"]) + self.assertEqual(seq_counts["cat1_seq1"], 3) + self.assertEqual(seq_counts["cat1_seq2"], 2) + + def test_visitor(self): + dataset_sorted = SqlIndexDataset( + sqlite_metadata_file=METADATA_FILE, + remove_empty_masks=False, + frame_data_builder_FrameDataBuilder_args=NO_BLOBS_KWARGS, + ) + + sequences = dataset_sorted.sequence_names() + i = 0 + for seq in sequences: + last_ts = float("-Inf") + for ts, _, idx in dataset_sorted.sequence_frames_in_order(seq): + self.assertEqual(i, idx) + i += 1 + self.assertGreaterEqual(ts, last_ts) + last_ts = ts + + # test legacy visitor + old_indices = None + for seq in sequences: + last_ts = float("-Inf") + rows = dataset_sorted._index.index.get_loc(seq) + indices = list(range(rows.start or 0, rows.stop, rows.step or 1)) + fn_ts_list = dataset_sorted.get_frame_numbers_and_timestamps(indices) + self.assertEqual(len(fn_ts_list), len(indices)) + + if old_indices: + # check raising if we ask for multiple sequences + with self.assertRaises(ValueError): + dataset_sorted.get_frame_numbers_and_timestamps( + indices + old_indices + ) + + old_indices = indices + + def test_visitor_subsets(self): + dataset = SqlIndexDataset( + sqlite_metadata_file=METADATA_FILE, + remove_empty_masks=False, + limit_to=100, # force sorting + subset_lists_file=SET_LIST_FILE, + subsets=["train", "test"], + frame_data_builder_FrameDataBuilder_args=NO_BLOBS_KWARGS, + ) + + sequences = dataset.sequence_names() + i = 0 + for seq in sequences: + last_ts = float("-Inf") + seq_frames = list(dataset.sequence_frames_in_order(seq)) + self.assertEqual(len(seq_frames), 10) + for ts, _, idx in seq_frames: + self.assertEqual(i, idx) + i += 1 + self.assertGreaterEqual(ts, last_ts) + last_ts = ts + + last_ts = float("-Inf") + train_frames = list(dataset.sequence_frames_in_order(seq, "train")) + self.assertEqual(len(train_frames), 5) + for ts, _, _ in train_frames: + self.assertGreaterEqual(ts, last_ts) + last_ts = ts + + def test_category_to_sequence_names(self): + dataset = SqlIndexDataset( + sqlite_metadata_file=METADATA_FILE, + remove_empty_masks=False, + subset_lists_file=SET_LIST_FILE, + subsets=["train", "test"], + frame_data_builder_FrameDataBuilder_args=NO_BLOBS_KWARGS, + ) + + cat_to_seqs = dataset.category_to_sequence_names() + self.assertEqual(len(cat_to_seqs), 2) + self.assertIn("cat1", cat_to_seqs) + self.assertEqual(len(cat_to_seqs["cat1"]), 5) + + # check that override preserves the behavior + cat_to_seqs_base = super(SqlIndexDataset, dataset).category_to_sequence_names() + self.assertDictEqual(cat_to_seqs, cat_to_seqs_base) + + def test_category_to_sequence_names_filters(self): + dataset = SqlIndexDataset( + sqlite_metadata_file=METADATA_FILE, + remove_empty_masks=True, + subset_lists_file=SET_LIST_FILE, + exclude_sequences=["cat1_seq0"], + subsets=["train", "test"], + frame_data_builder_FrameDataBuilder_args=NO_BLOBS_KWARGS, + ) + + cat_to_seqs = dataset.category_to_sequence_names() + self.assertEqual(len(cat_to_seqs), 2) + self.assertIn("cat1", cat_to_seqs) + self.assertEqual(len(cat_to_seqs["cat1"]), 4) # minus one + + # check that override preserves the behavior + cat_to_seqs_base = super(SqlIndexDataset, dataset).category_to_sequence_names() + self.assertDictEqual(cat_to_seqs, cat_to_seqs_base) + + def test_meta_access(self): + dataset = SqlIndexDataset( + sqlite_metadata_file=METADATA_FILE, + remove_empty_masks=False, + subset_lists_file=SET_LIST_FILE, + subsets=["train"], + frame_data_builder_FrameDataBuilder_args=NO_BLOBS_KWARGS, + ) + + self.assertEqual(len(dataset), 50) + + for idx in [10, ("cat0_seq2", 2)]: + example_meta = dataset.meta[idx] + example = dataset[idx] + self.assertEqual(example_meta.sequence_name, example.sequence_name) + self.assertEqual(example_meta.frame_number, example.frame_number) + self.assertEqual(example_meta.frame_timestamp, example.frame_timestamp) + self.assertEqual(example_meta.sequence_category, example.sequence_category) + torch.testing.assert_close(example_meta.camera.R, example.camera.R) + torch.testing.assert_close(example_meta.camera.T, example.camera.T) + torch.testing.assert_close( + example_meta.camera.focal_length, example.camera.focal_length + ) + torch.testing.assert_close( + example_meta.camera.principal_point, example.camera.principal_point + ) + + def test_meta_access_no_blobs(self): + dataset = SqlIndexDataset( + sqlite_metadata_file=METADATA_FILE, + remove_empty_masks=False, + subset_lists_file=SET_LIST_FILE, + subsets=["train"], + frame_data_builder_FrameDataBuilder_args={ + "dataset_root": ".", + "box_crop": False, # required by blob-less accessor + }, + ) + + self.assertIsNone(dataset.meta[0].image_rgb) + self.assertIsNone(dataset.meta[0].fg_probability) + self.assertIsNone(dataset.meta[0].depth_map) + self.assertIsNone(dataset.meta[0].sequence_point_cloud) + self.assertIsNotNone(dataset.meta[0].camera) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_srn.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_srn.py new file mode 100644 index 0000000000000000000000000000000000000000..311bbaa6dbfa86e579754a31a45adccacd3cc34e --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_srn.py @@ -0,0 +1,121 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import unittest + +import torch +from pytorch3d.implicitron.models.generic_model import GenericModel +from pytorch3d.implicitron.models.implicit_function.scene_representation_networks import ( + SRNHyperNetImplicitFunction, + SRNImplicitFunction, + SRNPixelGenerator, +) +from pytorch3d.implicitron.models.renderer.ray_sampler import ImplicitronRayBundle +from pytorch3d.implicitron.tools.config import get_default_args +from pytorch3d.renderer import PerspectiveCameras + +from tests.common_testing import TestCaseMixin + +_BATCH_SIZE: int = 3 +_N_RAYS: int = 100 +_N_POINTS_ON_RAY: int = 10 + + +class TestSRN(TestCaseMixin, unittest.TestCase): + def setUp(self) -> None: + torch.manual_seed(42) + get_default_args(SRNHyperNetImplicitFunction) + get_default_args(SRNImplicitFunction) + + def test_pixel_generator(self): + SRNPixelGenerator() + + def _get_bundle(self, *, device) -> ImplicitronRayBundle: + origins = torch.rand(_BATCH_SIZE, _N_RAYS, 3, device=device) + directions = torch.rand(_BATCH_SIZE, _N_RAYS, 3, device=device) + lengths = torch.rand(_BATCH_SIZE, _N_RAYS, _N_POINTS_ON_RAY, device=device) + bundle = ImplicitronRayBundle( + lengths=lengths, + origins=origins, + directions=directions, + xys=None, + camera_ids=None, + camera_counts=None, + ) + return bundle + + def test_srn_implicit_function(self): + implicit_function = SRNImplicitFunction() + device = torch.device("cpu") + bundle = self._get_bundle(device=device) + rays_densities, rays_colors = implicit_function(ray_bundle=bundle) + out_features = implicit_function.raymarch_function.out_features + self.assertEqual( + rays_densities.shape, + (_BATCH_SIZE, _N_RAYS, _N_POINTS_ON_RAY, out_features), + ) + self.assertIsNone(rays_colors) + + def test_srn_hypernet_implicit_function(self): + # TODO investigate: If latent_dim_hypernet=0, why does this crash and dump core? + latent_dim_hypernet = 39 + device = torch.device("cuda:0") + implicit_function = SRNHyperNetImplicitFunction( + latent_dim_hypernet=latent_dim_hypernet + ) + implicit_function.to(device) + global_code = torch.rand(_BATCH_SIZE, latent_dim_hypernet, device=device) + bundle = self._get_bundle(device=device) + rays_densities, rays_colors = implicit_function( + ray_bundle=bundle, global_code=global_code + ) + out_features = implicit_function.hypernet.out_features + self.assertEqual( + rays_densities.shape, + (_BATCH_SIZE, _N_RAYS, _N_POINTS_ON_RAY, out_features), + ) + self.assertIsNone(rays_colors) + + @torch.no_grad() + def test_lstm(self): + args = get_default_args(GenericModel) + args.render_image_height = 80 + args.render_image_width = 80 + args.implicit_function_class_type = "SRNImplicitFunction" + args.renderer_class_type = "LSTMRenderer" + args.raysampler_class_type = "NearFarRaySampler" + args.raysampler_NearFarRaySampler_args.n_pts_per_ray_training = 1 + args.raysampler_NearFarRaySampler_args.n_pts_per_ray_evaluation = 1 + args.renderer_LSTMRenderer_args.bg_color = [0.4, 0.4, 0.2] + gm = GenericModel(**args) + + camera = PerspectiveCameras() + image = gm.forward( + camera=camera, + image_rgb=None, + fg_probability=None, + sequence_name="", + mask_crop=None, + depth_map=None, + )["images_render"] + self.assertEqual(image.shape, (1, 3, 80, 80)) + self.assertGreater(image.max(), 0.8) + + # Force everything to be background + pixel_generator = gm._implicit_functions[0]._fn.pixel_generator + pixel_generator._density_layer.weight.zero_() + pixel_generator._density_layer.bias.fill_(-1.0e6) + + image = gm.forward( + camera=camera, + image_rgb=None, + fg_probability=None, + sequence_name="", + mask_crop=None, + depth_map=None, + )["images_render"] + self.assertConstant(image[:, :2], 0.4) + self.assertConstant(image[:, 2], 0.2) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_types.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_types.py new file mode 100644 index 0000000000000000000000000000000000000000..aff749be56c77353caa3c9cffae8e19a257007e3 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_types.py @@ -0,0 +1,97 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + + +import dataclasses +import unittest +from typing import Dict, List, NamedTuple, Tuple + +from pytorch3d.implicitron.dataset import types +from pytorch3d.implicitron.dataset.types import FrameAnnotation + + +class _NT(NamedTuple): + annot: FrameAnnotation + + +class TestDatasetTypes(unittest.TestCase): + def setUp(self): + self.entry = FrameAnnotation( + frame_number=23, + sequence_name="1", + frame_timestamp=1.2, + image=types.ImageAnnotation(path="/tmp/1.jpg", size=(224, 224)), + mask=types.MaskAnnotation(path="/tmp/1.png", mass=42.0), + viewpoint=types.ViewpointAnnotation( + R=( + (1, 0, 0), + (1, 0, 0), + (1, 0, 0), + ), + T=(0, 0, 0), + principal_point=(100, 100), + focal_length=(200, 200), + ), + ) + + def test_asdict_rec(self): + first = [dataclasses.asdict(self.entry)] + second = types._asdict_rec([self.entry]) + self.assertEqual(first, second) + + def test_parsing(self): + """Test that we handle collections enclosing dataclasses.""" + + dct = dataclasses.asdict(self.entry) + + parsed = types._dataclass_from_dict(dct, FrameAnnotation) + self.assertEqual(parsed, self.entry) + + # namedtuple + parsed = types._dataclass_from_dict(_NT(dct), _NT) + self.assertEqual(parsed.annot, self.entry) + + # tuple + parsed = types._dataclass_from_dict((dct,), Tuple[FrameAnnotation]) + self.assertEqual(parsed, (self.entry,)) + + # list + parsed = types._dataclass_from_dict( + [ + dct, + ], + List[FrameAnnotation], + ) + self.assertEqual( + parsed, + [ + self.entry, + ], + ) + + # dict + parsed = types._dataclass_from_dict({"key": dct}, Dict[str, FrameAnnotation]) + self.assertEqual(parsed, {"key": self.entry}) + + def test_parsing_vectorized(self): + dct = dataclasses.asdict(self.entry) + + self._compare_with_scalar(dct, FrameAnnotation) + self._compare_with_scalar(_NT(dct), _NT) + self._compare_with_scalar((dct,), Tuple[FrameAnnotation]) + self._compare_with_scalar([dct], List[FrameAnnotation]) + self._compare_with_scalar({"key": dct}, Dict[str, FrameAnnotation]) + + dct2 = dct.copy() + dct2["meta"] = {"aux": 76} + self._compare_with_scalar(dct2, FrameAnnotation) + + def _compare_with_scalar(self, obj, typeannot, repeat=3): + input = [obj] * 3 + vect_output = types._dataclass_list_from_dict_list(input, typeannot) + self.assertEqual(len(input), repeat) + gt = types._dataclass_from_dict(obj, typeannot) + self.assertTrue(all(res == gt for res in vect_output)) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_viewsampling.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_viewsampling.py new file mode 100644 index 0000000000000000000000000000000000000000..a74b6c461cc8f57951cff07caae5a59e44f3cc9d --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_viewsampling.py @@ -0,0 +1,269 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + + +import unittest + +import pytorch3d as pt3d +import torch +from pytorch3d.implicitron.models.view_pooler.view_sampler import ViewSampler +from pytorch3d.implicitron.tools.config import expand_args_fields + + +class TestViewsampling(unittest.TestCase): + def setUp(self): + torch.manual_seed(42) + expand_args_fields(ViewSampler) + + def _init_view_sampler_problem(self, random_masks): + """ + Generates a view-sampling problem: + - 4 source views, 1st/2nd from the first sequence 'seq1', the rest from 'seq2' + - 3 sets of 3D points from sequences 'seq1', 'seq2', 'seq2' respectively. + - first 50 points in each batch correctly project to the source views, + while the remaining 50 do not land in any projection plane. + - each source view is labeled with image feature tensors of shape 7x100x50, + where all elements of the n-th tensor are set to `n+1`. + - the elements of the source view masks are either set to random binary number + (if `random_masks==True`), or all set to 1 (`random_masks==False`). + - the source view cameras are uniformly distributed on a unit circle + in the x-z plane and look at (0,0,0). + """ + seq_id_camera = ["seq1", "seq1", "seq2", "seq2"] + seq_id_pts = ["seq1", "seq2", "seq2"] + pts_batch = 3 + n_pts = 100 + n_views = 4 + fdim = 7 + H = 100 + W = 50 + + # points that land into the projection planes of all cameras + pts_inside = ( + torch.nn.functional.normalize( + torch.randn(pts_batch, n_pts // 2, 3, device="cuda"), + dim=-1, + ) + * 0.1 + ) + + # move the outside points far above the scene + pts_outside = pts_inside.clone() + pts_outside[:, :, 1] += 1e8 + pts = torch.cat([pts_inside, pts_outside], dim=1) + + R, T = pt3d.renderer.look_at_view_transform( + dist=1.0, + elev=0.0, + azim=torch.linspace(0, 360, n_views + 1)[:n_views], + degrees=True, + device=pts.device, + ) + focal_length = R.new_ones(n_views, 2) + principal_point = R.new_zeros(n_views, 2) + camera = pt3d.renderer.PerspectiveCameras( + R=R, + T=T, + focal_length=focal_length, + principal_point=principal_point, + device=pts.device, + ) + + feats_map = torch.arange(n_views, device=pts.device, dtype=pts.dtype) + 1 + feats = {"feats": feats_map[:, None, None, None].repeat(1, fdim, H, W)} + + masks = ( + torch.rand(n_views, 1, H, W, device=pts.device, dtype=pts.dtype) > 0.5 + ).type_as(R) + + if not random_masks: + masks[:] = 1.0 + + return pts, camera, feats, masks, seq_id_camera, seq_id_pts + + def test_compare_with_naive(self): + """ + Compares the outputs of the efficient ViewSampler module with a + naive implementation. + """ + + ( + pts, + camera, + feats, + masks, + seq_id_camera, + seq_id_pts, + ) = self._init_view_sampler_problem(True) + + for masked_sampling in (True, False): + feats_sampled_n, masks_sampled_n = _view_sample_naive( + pts, + seq_id_pts, + camera, + seq_id_camera, + feats, + masks, + masked_sampling, + ) + # make sure we generate the constructor for ViewSampler + expand_args_fields(ViewSampler) + view_sampler = ViewSampler(masked_sampling=masked_sampling) + feats_sampled, masks_sampled = view_sampler( + pts=pts, + seq_id_pts=seq_id_pts, + camera=camera, + seq_id_camera=seq_id_camera, + feats=feats, + masks=masks, + ) + for k in feats_sampled.keys(): + self.assertTrue(torch.allclose(feats_sampled[k], feats_sampled_n[k])) + self.assertTrue(torch.allclose(masks_sampled, masks_sampled_n)) + + def test_viewsampling(self): + """ + Generates a viewsampling problem with predictable outcome, and compares + the ViewSampler's output to the expected result. + """ + + ( + pts, + camera, + feats, + masks, + seq_id_camera, + seq_id_pts, + ) = self._init_view_sampler_problem(False) + + expand_args_fields(ViewSampler) + + for masked_sampling in (True, False): + view_sampler = ViewSampler(masked_sampling=masked_sampling) + + feats_sampled, masks_sampled = view_sampler( + pts=pts, + seq_id_pts=seq_id_pts, + camera=camera, + seq_id_camera=seq_id_camera, + feats=feats, + masks=masks, + ) + + n_views = camera.R.shape[0] + n_pts = pts.shape[1] + feat_dim = feats["feats"].shape[1] + pts_batch = pts.shape[0] + n_pts_away = n_pts // 2 + + for pts_i in range(pts_batch): + for view_i in range(n_views): + if seq_id_pts[pts_i] != seq_id_camera[view_i]: + # points / cameras come from different sequences + gt_masks = pts.new_zeros(n_pts, 1) + gt_feats = pts.new_zeros(n_pts, feat_dim) + else: + gt_masks = pts.new_ones(n_pts, 1) + gt_feats = pts.new_ones(n_pts, feat_dim) * (view_i + 1) + gt_feats[n_pts_away:] = 0.0 + if masked_sampling: + gt_masks[n_pts_away:] = 0.0 + + for k in feats_sampled: + self.assertTrue( + torch.allclose( + feats_sampled[k][pts_i, view_i], + gt_feats, + ) + ) + self.assertTrue( + torch.allclose( + masks_sampled[pts_i, view_i], + gt_masks, + ) + ) + + +def _view_sample_naive( + pts, + seq_id_pts, + camera, + seq_id_camera, + feats, + masks, + masked_sampling, +): + """ + A naive implementation of the forward pass of ViewSampler. + Refer to ViewSampler's docstring for description of the arguments. + """ + + pts_batch = pts.shape[0] + n_views = camera.R.shape[0] + n_pts = pts.shape[1] + + feats_sampled = [[[] for _ in range(n_views)] for _ in range(pts_batch)] + masks_sampled = [[[] for _ in range(n_views)] for _ in range(pts_batch)] + + for pts_i in range(pts_batch): + for view_i in range(n_views): + if seq_id_pts[pts_i] != seq_id_camera[view_i]: + # points/cameras come from different sequences + feats_sampled_ = { + k: f.new_zeros(n_pts, f.shape[1]) for k, f in feats.items() + } + masks_sampled_ = masks.new_zeros(n_pts, 1) + else: + # same sequence of pts and cameras -> sample + feats_sampled_, masks_sampled_ = _sample_one_view_naive( + camera[view_i], + pts[pts_i], + {k: f[view_i] for k, f in feats.items()}, + masks[view_i], + masked_sampling, + sampling_mode="bilinear", + ) + feats_sampled[pts_i][view_i] = feats_sampled_ + masks_sampled[pts_i][view_i] = masks_sampled_ + + masks_sampled_cat = torch.stack([torch.stack(m) for m in masks_sampled]) + feats_sampled_cat = {} + for k in feats_sampled[0][0].keys(): + feats_sampled_cat[k] = torch.stack( + [torch.stack([f_[k] for f_ in f]) for f in feats_sampled] + ) + return feats_sampled_cat, masks_sampled_cat + + +def _sample_one_view_naive( + camera, + pts, + feats, + masks, + masked_sampling, + sampling_mode="bilinear", +): + """ + Sample a single source view. + """ + proj_ndc = camera.transform_points(pts[None])[None, ..., :-1] # 1 x 1 x n_pts x 2 + feats_sampled = { + k: pt3d.renderer.ndc_grid_sample(f[None], proj_ndc, mode=sampling_mode).permute( + 0, 3, 1, 2 + )[0, :, :, 0] + for k, f in feats.items() + } # n_pts x dim + if not masked_sampling: + n_pts = pts.shape[0] + masks_sampled = proj_ndc.new_ones(n_pts, 1) + else: + masks_sampled = pt3d.renderer.ndc_grid_sample( + masks[None], + proj_ndc, + mode=sampling_mode, + align_corners=False, + )[0, 0, 0, :][:, None] + return feats_sampled, masks_sampled diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_voxel_grid_implicit_function.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_voxel_grid_implicit_function.py new file mode 100644 index 0000000000000000000000000000000000000000..9727ba982adcfca916728d51bf280be59735988c --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/implicitron/test_voxel_grid_implicit_function.py @@ -0,0 +1,227 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + + +import unittest + +import torch + +from omegaconf import DictConfig, OmegaConf +from pytorch3d.implicitron.models.implicit_function.voxel_grid_implicit_function import ( + VoxelGridImplicitFunction, +) +from pytorch3d.implicitron.models.renderer.base import ImplicitronRayBundle + +from pytorch3d.implicitron.tools.config import expand_args_fields, get_default_args +from pytorch3d.renderer import ray_bundle_to_ray_points +from tests.common_testing import TestCaseMixin + + +class TestVoxelGridImplicitFunction(TestCaseMixin, unittest.TestCase): + def setUp(self) -> None: + torch.manual_seed(42) + expand_args_fields(VoxelGridImplicitFunction) + + def _get_simple_implicit_function(self, scaffold_res=16): + default_cfg = get_default_args(VoxelGridImplicitFunction) + custom_cfg = DictConfig( + { + "voxel_grid_density_args": { + "voxel_grid_FullResolutionVoxelGrid_args": {"n_features": 7} + }, + "decoder_density_class_type": "ElementwiseDecoder", + "decoder_color_class_type": "MLPDecoder", + "decoder_color_MLPDecoder_args": { + "network_args": { + "n_layers": 2, + "output_dim": 3, + "hidden_dim": 128, + } + }, + "scaffold_resolution": (scaffold_res, scaffold_res, scaffold_res), + } + ) + cfg = OmegaConf.merge(default_cfg, custom_cfg) + return VoxelGridImplicitFunction(**cfg) + + def test_forward(self) -> None: + """ + Test one forward of VoxelGridImplicitFunction. + """ + func = self._get_simple_implicit_function() + + n_grids, n_points = 10, 9 + raybundle = ImplicitronRayBundle( + origins=torch.randn(n_grids, 2, 3, 3), + directions=torch.randn(n_grids, 2, 3, 3), + lengths=torch.randn(n_grids, 2, 3, n_points), + xys=0, + ) + func(raybundle) + + def test_scaffold_formation(self): + """ + Test calculating the scaffold. + + We define a custom density function and make the implicit function use it + After calculating the scaffold we compare the density of our custom + density function with densities from the scaffold. + """ + device = "cuda" if torch.cuda.is_available() else "cpu" + func = self._get_simple_implicit_function().to(device) + func.scaffold_max_pool_kernel_size = 1 + + def new_density(points): + """ + Density function which returns 1 if p>(0.5, 0.5, 0.5) or + p < (-0.5, -0.5, -0.5) else 0 + """ + inshape = points.shape + points = points.view(-1, 3) + out = [] + for p in points: + if torch.all(p > 0.5) or torch.all(p < -0.5): + out.append(torch.tensor([[1.0]])) + else: + out.append(torch.tensor([[0.0]])) + return torch.cat(out).view(*inshape[:-1], 1).to(device) + + func._get_density = new_density + func._get_scaffold(0) + + points = torch.tensor( + [ + [0, 0, 0], + [1, 1, 1], + [1, 0, 0], + [0.1, 0, 0], + [10, 1, -1], + [-0.8, -0.7, -0.9], + ] + ).to(device) + expected = new_density(points).float().to(device) + assert torch.allclose(func.voxel_grid_scaffold(points), expected), ( + func.voxel_grid_scaffold(points), + expected, + ) + + def test_scaffold_filtering(self, n_test_points=100): + """ + Test that filtering points with scaffold works. + + We define a scaffold and make the implicit function use it. We also + define new density and color functions which check that all passed + points are not in empty space (with scaffold function). In the end + we compare the result from the implicit function with one calculated + simple python, this checks that the points were merged correectly. + """ + device = "cuda" + func = self._get_simple_implicit_function().to(device) + + def scaffold(points): + """' + Function to deterministically and randomly enough assign a point + to empty or occupied space. + Return 1 if second digit of sum after 0 is odd else 0 + """ + return ( + ((points.sum(dim=-1, keepdim=True) * 10**2 % 10).long() % 2) == 1 + ).float() + + def new_density(points): + # check if all passed points should be passed here + assert torch.all(scaffold(points)), (scaffold(points), points.shape) + return points.sum(dim=-1, keepdim=True) + + def new_color(points, camera, directions, non_empty_points, num_points_per_ray): + # check if all passed points should be passed here + assert torch.all(scaffold(points)) # , (scaffold(points), points) + return points * 2 + + # check both computation paths that they contain only points + # which are not in empty space + func._get_density = new_density + func._get_color = new_color + func.voxel_grid_scaffold.forward = scaffold + func._scaffold_ready = True + + bundle = ImplicitronRayBundle( + origins=torch.rand((n_test_points, 2, 1, 3), device=device), + directions=torch.rand((n_test_points, 2, 1, 3), device=device), + lengths=torch.rand((n_test_points, 2, 1, 4), device=device), + xys=None, + ) + points = ray_bundle_to_ray_points(bundle) + result_density, result_color, _ = func(bundle) + + # construct the wanted result 'by hand' + flat_points = points.view(-1, 3) + expected_result_density, expected_result_color = [], [] + for point in flat_points: + if scaffold(point) == 1: + expected_result_density.append(point.sum(dim=-1, keepdim=True)) + expected_result_color.append(point * 2) + else: + expected_result_density.append(point.new_zeros((1,))) + expected_result_color.append(point.new_zeros((3,))) + expected_result_density = torch.stack(expected_result_density, dim=0).view( + *points.shape[:-1], 1 + ) + expected_result_color = torch.stack(expected_result_color, dim=0).view( + *points.shape[:-1], 3 + ) + + # check that thre result is expected + assert torch.allclose(result_density, expected_result_density), ( + result_density, + expected_result_density, + ) + assert torch.allclose(result_color, expected_result_color), ( + result_color, + expected_result_color, + ) + + def test_cropping(self, scaffold_res=9): + """ + Tests whether implicit function finds the bounding box of the object and sends + correct min and max points to voxel grids for rescaling. + """ + device = "cuda" if torch.cuda.is_available() else "cpu" + func = self._get_simple_implicit_function(scaffold_res=scaffold_res).to(device) + + assert scaffold_res >= 8 + div = (scaffold_res - 1) / 2 + true_min_point = torch.tensor( + [-3 / div, 0 / div, -3 / div], + device=device, + ) + true_max_point = torch.tensor( + [1 / div, 2 / div, 3 / div], + device=device, + ) + + def new_scaffold(points): + # 1 if between true_min and true_max point else 0 + # return points.new_ones((*points.shape[:-1], 1)) + return ( + torch.logical_and(true_min_point <= points, points <= true_max_point) + .all(dim=-1) + .float()[..., None] + ) + + called_crop = [] + + def assert_min_max_points(min_point, max_point): + called_crop.append(1) + self.assertClose(min_point, true_min_point) + self.assertClose(max_point, true_max_point) + + func.voxel_grid_density.crop_self = assert_min_max_points + func.voxel_grid_color.crop_self = assert_min_max_points + func.voxel_grid_scaffold.forward = new_scaffold + func._scaffold_ready = True + func._crop(epoch=0) + assert len(called_crop) == 2 diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_camera_pixels.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_camera_pixels.py new file mode 100644 index 0000000000000000000000000000000000000000..3f7e428d018fdce7cf8f72d2d35efebf31077688 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_camera_pixels.py @@ -0,0 +1,264 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import unittest + +import torch +from pytorch3d.renderer import ( + MeshRasterizer, + NDCMultinomialRaysampler, + PerspectiveCameras, + PointsRasterizationSettings, + PointsRasterizer, + PulsarPointsRenderer, + RasterizationSettings, +) +from pytorch3d.structures import Meshes, Pointclouds + +from .common_testing import TestCaseMixin + + +""" +PyTorch3D renderers operate in an align_corners=False manner. +This file demonstrates the pixel-perfect calculation by very simple +examples. +""" + + +class _CommonData: + """ + Contains data for all these tests. + + - Firstly, a non-square at the origin specified in ndc space and + screen space. Principal point is in the center of the image. + Focal length is 1.0 in world space. + This camera has the identity as its world to view transformation, so + it is facing down the positive z axis with y being up and x being left. + A point on the z=1.0 focal plane has its x,y world coordinate equal to + its NDC. + + - Secondly, batched together with that, is a camera with the same + focal length facing in the same direction but located so that it faces + the corner of the corner pixel of the first image, with its principal + point located at its corner, so that it maps the z=1 plane to NDC just + like the first. + + - a single point self.point in world space which is located on a plane 1.0 + in front from the camera which is located exactly in the center + of a known pixel (self.x, self.y), specifically with negative x and slightly + positive y, so it is in the top right quadrant of the image. + + - A second batch of cameras defined in screen space which exactly match the + first ones. + + So that this data can be copied for making demos, it is easiest to leave + it as a freestanding class. + """ + + def __init__(self): + self.H, self.W = 249, 125 + self.image_size = (self.H, self.W) + self.camera_ndc = PerspectiveCameras( + focal_length=1.0, + image_size=(self.image_size,), + in_ndc=True, + T=torch.tensor([[0.0, 0.0, 0.0], [-1.0, self.H / self.W, 0.0]]), + principal_point=((-0.0, -0.0), (1.0, -self.H / self.W)), + ) + # Note how principal point is specifiied + self.camera_screen = PerspectiveCameras( + focal_length=self.W / 2.0, + principal_point=((self.W / 2.0, self.H / 2.0), (0.0, self.H)), + image_size=(self.image_size,), + T=torch.tensor([[0.0, 0.0, 0.0], [-1.0, self.H / self.W, 0.0]]), + in_ndc=False, + ) + + # 81 is more than half of 125, 113 is a bit less than half of 249 + self.x, self.y = 81, 113 + self.point = [-0.304, 0.176, 1] + # The point is in the center of pixel (81, 113) + # where pixel (0,0) is the top left. + # 81 is 38/2 pixels over the midpoint (125-1)/2=62 + # and 38/125=0.304 + # 113 is 22/2 pixels under the midpoint (249-1)/2=124 + # and 22/125=0.176 + + +class TestPixels(TestCaseMixin, unittest.TestCase): + def test_mesh(self): + data = _CommonData() + # Three points on the plane at unit 1 from the camera in + # world space, whose mean is the known point. + verts = torch.tensor( + [[-0.288, 0.192, 1], [-0.32, 0.192, 1], [-0.304, 0.144, 1]] + ) + self.assertClose(verts.mean(0), torch.tensor(data.point)) + faces = torch.LongTensor([[0, 1, 2]]) + # A mesh of one triangular face whose centroid is the known point + # duplicated so it can be rendered from two cameras. + meshes = Meshes(verts=[verts], faces=[faces]).extend(2) + faces_per_pixel = 2 + for camera in (data.camera_ndc, data.camera_screen): + rasterizer = MeshRasterizer( + cameras=camera, + raster_settings=RasterizationSettings( + image_size=data.image_size, faces_per_pixel=faces_per_pixel + ), + ) + barycentric_coords_found = rasterizer(meshes).bary_coords + self.assertTupleEqual( + barycentric_coords_found.shape, + (2,) + data.image_size + (faces_per_pixel, 3), + ) + # We see that the barycentric coordinates at the expected + # pixel are (1/3, 1/3, 1/3), indicating that this pixel + # hits the centroid of the triangle. + self.assertClose( + barycentric_coords_found[:, data.y, data.x, 0], + torch.full((2, 3), 1 / 3.0), + atol=1e-5, + ) + + def test_pointcloud(self): + data = _CommonData() + clouds = Pointclouds(points=torch.tensor([[data.point]])).extend(2) + colorful_cloud = Pointclouds( + points=torch.tensor([[data.point]]), features=torch.ones(1, 1, 3) + ).extend(2) + points_per_pixel = 2 + # for camera in [data.camera_screen]: + for camera in (data.camera_ndc, data.camera_screen): + rasterizer = PointsRasterizer( + cameras=camera, + raster_settings=PointsRasterizationSettings( + image_size=data.image_size, + radius=0.0001, + points_per_pixel=points_per_pixel, + ), + ) + # when rasterizing we expect only one pixel to be occupied + rasterizer_output = rasterizer(clouds).idx + self.assertTupleEqual( + rasterizer_output.shape, (2,) + data.image_size + (points_per_pixel,) + ) + found = torch.nonzero(rasterizer_output != -1) + self.assertTupleEqual(found.shape, (2, 4)) + self.assertListEqual(found[0].tolist(), [0, data.y, data.x, 0]) + self.assertListEqual(found[1].tolist(), [1, data.y, data.x, 0]) + + if camera.in_ndc(): + # Pulsar not currently working in screen space. + pulsar_renderer = PulsarPointsRenderer(rasterizer=rasterizer) + pulsar_output = pulsar_renderer( + colorful_cloud, gamma=(0.1, 0.1), znear=(0.1, 0.1), zfar=(70, 70) + ) + self.assertTupleEqual( + pulsar_output.shape, (2,) + data.image_size + (3,) + ) + # Look for points rendered in the red channel only, expecting our one. + # Check the first batch element only. + # TODO: Something is odd with the second. + found = torch.nonzero(pulsar_output[0, :, :, 0]) + self.assertTupleEqual(found.shape, (1, 2)) + self.assertListEqual(found[0].tolist(), [data.y, data.x]) + # Should be: + # found = torch.nonzero(pulsar_output[:, :, :, 0]) + # self.assertTupleEqual(found.shape, (2, 3)) + # self.assertListEqual(found[0].tolist(), [0, data.y, data.x]) + # self.assertListEqual(found[1].tolist(), [1, data.y, data.x]) + + def test_raysampler(self): + data = _CommonData() + gridsampler = NDCMultinomialRaysampler( + image_width=data.W, + image_height=data.H, + n_pts_per_ray=2, + min_depth=1.0, + max_depth=2.0, + ) + for camera in (data.camera_ndc, data.camera_screen): + bundle = gridsampler(camera) + self.assertTupleEqual(bundle.xys.shape, (2,) + data.image_size + (2,)) + self.assertTupleEqual( + bundle.directions.shape, (2,) + data.image_size + (3,) + ) + self.assertClose( + bundle.xys[:, data.y, data.x], + torch.tensor(data.point[:2]).expand(2, -1), + ) + # We check only the first batch element. + # Second element varies because of camera location. + self.assertClose( + bundle.directions[0, data.y, data.x], + torch.tensor(data.point), + ) + + def test_camera(self): + data = _CommonData() + # Our point, plus the image center, and a corner of the image. + # Located at the focal-length distance away + points = torch.tensor([data.point, [0, 0, 1], [1, data.H / data.W, 1]]) + for cameras in (data.camera_ndc, data.camera_screen): + ndc_points = cameras.transform_points_ndc(points) + screen_points = cameras.transform_points_screen(points) + screen_points_without_xyflip = cameras.transform_points_screen( + points, with_xyflip=False + ) + camera_points = cameras.transform_points(points) + for batch_idx in range(2): + # NDC space agrees with the original + self.assertClose(ndc_points[batch_idx], points, atol=1e-5) + # First point in screen space is the center of our expected pixel + self.assertClose( + screen_points[batch_idx][0], + torch.tensor([data.x + 0.5, data.y + 0.5, 1.0]), + atol=1e-5, + ) + # Screen coords without xyflip should have x, y that negate the non- + # flipped values, and unchanged z. + self.assertClose( + screen_points_without_xyflip[batch_idx][0], + torch.tensor([-(data.x + 0.5), -(data.y + 0.5), 1.0]), + atol=1e-5, + ) + # Second point in screen space is the center of the screen + self.assertClose( + screen_points[batch_idx][1], + torch.tensor([data.W / 2.0, data.H / 2.0, 1.0]), + atol=1e-5, + ) + # Third point in screen space is the corner of the screen + # (corner of corner pixels) + self.assertClose( + screen_points[batch_idx][2], + torch.tensor([0.0, 0.0, 1.0]), + atol=1e-5, + ) + + if cameras.in_ndc(): + self.assertClose(camera_points[batch_idx], ndc_points[batch_idx]) + else: + # transform_points does something strange for screen cameras + if batch_idx == 0: + wanted = torch.stack( + [ + data.W - screen_points[batch_idx, :, 0], + data.H - screen_points[batch_idx, :, 1], + torch.ones(3), + ], + dim=1, + ) + else: + wanted = torch.stack( + [ + -screen_points[batch_idx, :, 0], + 2 * data.H - screen_points[batch_idx, :, 1], + torch.ones(3), + ], + dim=1, + ) + self.assertClose(camera_points[batch_idx], wanted) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_cameras.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_cameras.py new file mode 100644 index 0000000000000000000000000000000000000000..b13c514e7378f1d6cace0ef5c3c6d4bb50706e7b --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_cameras.py @@ -0,0 +1,1678 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +# @licenselint-loose-mode + +# Some of the code below is adapted from Soft Rasterizer (SoftRas) +# +# Copyright (c) 2017 Hiroharu Kato +# Copyright (c) 2018 Nikos Kolotouros +# Copyright (c) 2019 Shichen Liu +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +import math +import pickle +import unittest +from itertools import product + +import numpy as np +import torch +from pytorch3d.common.datatypes import Device +from pytorch3d.renderer.camera_utils import join_cameras_as_batch +from pytorch3d.renderer.cameras import ( + camera_position_from_spherical_angles, + CamerasBase, + FoVOrthographicCameras, + FoVPerspectiveCameras, + get_world_to_view_transform, + look_at_rotation, + look_at_view_transform, + OpenGLOrthographicCameras, + OpenGLPerspectiveCameras, + OrthographicCameras, + PerspectiveCameras, + SfMOrthographicCameras, + SfMPerspectiveCameras, +) +from pytorch3d.renderer.fisheyecameras import FishEyeCameras +from pytorch3d.transforms import Transform3d +from pytorch3d.transforms.rotation_conversions import random_rotations +from pytorch3d.transforms.so3 import so3_exp_map + +from .common_camera_utils import init_random_cameras + +from .common_testing import TestCaseMixin + + +# Naive function adapted from SoftRasterizer for test purposes. +def perspective_project_naive(points, fov=60.0): + """ + Compute perspective projection from a given viewing angle. + Args: + points: (N, V, 3) representing the padded points. + viewing angle: degrees + Returns: + (N, V, 3) tensor of projected points preserving the view space z + coordinate (no z renormalization) + """ + device = points.device + halfFov = torch.tensor((fov / 2) / 180 * np.pi, dtype=torch.float32, device=device) + scale = torch.tan(halfFov[None]) + scale = scale[:, None] + z = points[:, :, 2] + x = points[:, :, 0] / z / scale + y = points[:, :, 1] / z / scale + points = torch.stack((x, y, z), dim=2) + return points + + +def sfm_perspective_project_naive(points, fx=1.0, fy=1.0, p0x=0.0, p0y=0.0): + """ + Compute perspective projection using focal length and principal point. + + Args: + points: (N, V, 3) representing the padded points. + fx: world units + fy: world units + p0x: pixels + p0y: pixels + Returns: + (N, V, 3) tensor of projected points. + """ + z = points[:, :, 2] + x = (points[:, :, 0] * fx) / z + p0x + y = (points[:, :, 1] * fy) / z + p0y + points = torch.stack((x, y, 1.0 / z), dim=2) + return points + + +# Naive function adapted from SoftRasterizer for test purposes. +def orthographic_project_naive(points, scale_xyz=(1.0, 1.0, 1.0)): + """ + Compute orthographic projection from a given angle + Args: + points: (N, V, 3) representing the padded points. + scaled: (N, 3) scaling factors for each of xyz directions + Returns: + (N, V, 3) tensor of projected points preserving the view space z + coordinate (no z renormalization). + """ + if not torch.is_tensor(scale_xyz): + scale_xyz = torch.tensor(scale_xyz) + scale_xyz = scale_xyz.view(-1, 3) + z = points[:, :, 2] + x = points[:, :, 0] * scale_xyz[:, 0] + y = points[:, :, 1] * scale_xyz[:, 1] + points = torch.stack((x, y, z), dim=2) + return points + + +def ndc_to_screen_points_naive(points, imsize): + """ + Transforms points from PyTorch3D's NDC space to screen space + Args: + points: (N, V, 3) representing padded points + imsize: (N, 2) image size = (height, width) + Returns: + (N, V, 3) tensor of transformed points + """ + height, width = imsize.unbind(1) + width = width.view(-1, 1) + half_width = width / 2.0 + height = height.view(-1, 1) + half_height = height / 2.0 + + scale = ( + half_width * (height > width).float() + half_height * (height <= width).float() + ) + + x, y, z = points.unbind(2) + x = -scale * x + half_width + y = -scale * y + half_height + return torch.stack((x, y, z), dim=2) + + +class TestCameraHelpers(TestCaseMixin, unittest.TestCase): + def setUp(self) -> None: + super().setUp() + torch.manual_seed(42) + + def test_look_at_view_transform_from_eye_point_tuple(self): + dist = math.sqrt(2) + elev = math.pi / 4 + azim = 0.0 + eye = ((0.0, 1.0, 1.0),) + # using passed values for dist, elev, azim + R, t = look_at_view_transform(dist, elev, azim, degrees=False) + # using other values for dist, elev, azim - eye overrides + R_eye, t_eye = look_at_view_transform(dist=3, elev=2, azim=1, eye=eye) + # using only eye value + + R_eye_only, t_eye_only = look_at_view_transform(eye=eye) + self.assertTrue(torch.allclose(R, R_eye, atol=2e-7)) + self.assertTrue(torch.allclose(t, t_eye, atol=2e-7)) + self.assertTrue(torch.allclose(R, R_eye_only, atol=2e-7)) + self.assertTrue(torch.allclose(t, t_eye_only, atol=2e-7)) + + def test_look_at_view_transform_default_values(self): + dist = 1.0 + elev = 0.0 + azim = 0.0 + # Using passed values for dist, elev, azim + R, t = look_at_view_transform(dist, elev, azim) + # Using default dist=1.0, elev=0.0, azim=0.0 + R_default, t_default = look_at_view_transform() + # test default = passed = expected + self.assertTrue(torch.allclose(R, R_default, atol=2e-7)) + self.assertTrue(torch.allclose(t, t_default, atol=2e-7)) + + def test_look_at_view_transform_non_default_at_position(self): + dist = 1.0 + elev = 0.0 + azim = 0.0 + at = ((1, 1, 1),) + # Using passed values for dist, elev, azim, at + R, t = look_at_view_transform(dist, elev, azim, at=at) + # Using default dist=1.0, elev=0.0, azim=0.0 + R_default, t_default = look_at_view_transform() + # test default = passed = expected + # R must be the same, t must be translated by (1,-1,1) with respect to t_default + t_trans = torch.tensor([1, -1, 1], dtype=torch.float32).view(1, 3) + self.assertTrue(torch.allclose(R, R_default, atol=2e-7)) + self.assertTrue(torch.allclose(t, t_default + t_trans, atol=2e-7)) + + def test_camera_position_from_angles_python_scalar(self): + dist = 2.7 + elev = 90.0 + azim = 0.0 + expected_position = torch.tensor([0.0, 2.7, 0.0], dtype=torch.float32).view( + 1, 3 + ) + position = camera_position_from_spherical_angles(dist, elev, azim) + self.assertClose(position, expected_position, atol=2e-7) + + def test_camera_position_from_angles_python_scalar_radians(self): + dist = 2.7 + elev = math.pi / 2 + azim = 0.0 + expected_position = torch.tensor([0.0, 2.7, 0.0], dtype=torch.float32) + expected_position = expected_position.view(1, 3) + position = camera_position_from_spherical_angles( + dist, elev, azim, degrees=False + ) + self.assertClose(position, expected_position, atol=2e-7) + + def test_camera_position_from_angles_torch_scalars(self): + dist = torch.tensor(2.7) + elev = torch.tensor(0.0) + azim = torch.tensor(90.0) + expected_position = torch.tensor([2.7, 0.0, 0.0], dtype=torch.float32).view( + 1, 3 + ) + position = camera_position_from_spherical_angles(dist, elev, azim) + self.assertClose(position, expected_position, atol=2e-7) + + def test_camera_position_from_angles_mixed_scalars(self): + dist = 2.7 + elev = torch.tensor(0.0) + azim = 90.0 + expected_position = torch.tensor([2.7, 0.0, 0.0], dtype=torch.float32).view( + 1, 3 + ) + position = camera_position_from_spherical_angles(dist, elev, azim) + self.assertClose(position, expected_position, atol=2e-7) + + def test_camera_position_from_angles_torch_scalar_grads(self): + dist = torch.tensor(2.7, requires_grad=True) + elev = torch.tensor(45.0, requires_grad=True) + azim = torch.tensor(45.0) + position = camera_position_from_spherical_angles(dist, elev, azim) + position.sum().backward() + self.assertTrue(hasattr(elev, "grad")) + self.assertTrue(hasattr(dist, "grad")) + elev_grad = elev.grad.clone() + dist_grad = dist.grad.clone() + elev = math.pi / 180.0 * elev.detach() + azim = math.pi / 180.0 * azim + grad_dist = ( + torch.cos(elev) * torch.sin(azim) + + torch.sin(elev) + + torch.cos(elev) * torch.cos(azim) + ) + grad_elev = ( + -(torch.sin(elev)) * torch.sin(azim) + + torch.cos(elev) + - torch.sin(elev) * torch.cos(azim) + ) + grad_elev = dist * (math.pi / 180.0) * grad_elev + self.assertClose(elev_grad, grad_elev) + self.assertClose(dist_grad, grad_dist) + + def test_camera_position_from_angles_vectors(self): + dist = torch.tensor([2.0, 2.0]) + elev = torch.tensor([0.0, 90.0]) + azim = torch.tensor([90.0, 0.0]) + expected_position = torch.tensor( + [[2.0, 0.0, 0.0], [0.0, 2.0, 0.0]], dtype=torch.float32 + ) + position = camera_position_from_spherical_angles(dist, elev, azim) + self.assertClose(position, expected_position, atol=2e-7) + + def test_camera_position_from_angles_vectors_broadcast(self): + dist = torch.tensor([2.0, 3.0, 5.0]) + elev = torch.tensor([0.0]) + azim = torch.tensor([90.0]) + expected_position = torch.tensor( + [[2.0, 0.0, 0.0], [3.0, 0.0, 0.0], [5.0, 0.0, 0.0]], dtype=torch.float32 + ) + position = camera_position_from_spherical_angles(dist, elev, azim) + self.assertClose(position, expected_position, atol=3e-7) + + def test_camera_position_from_angles_vectors_mixed_broadcast(self): + dist = torch.tensor([2.0, 3.0, 5.0]) + elev = 0.0 + azim = torch.tensor(90.0) + expected_position = torch.tensor( + [[2.0, 0.0, 0.0], [3.0, 0.0, 0.0], [5.0, 0.0, 0.0]], dtype=torch.float32 + ) + position = camera_position_from_spherical_angles(dist, elev, azim) + self.assertClose(position, expected_position, atol=3e-7) + + def test_camera_position_from_angles_vectors_mixed_broadcast_grads(self): + dist = torch.tensor([2.0, 3.0, 5.0], requires_grad=True) + elev = torch.tensor(45.0, requires_grad=True) + azim = 45.0 + position = camera_position_from_spherical_angles(dist, elev, azim) + position.sum().backward() + self.assertTrue(hasattr(elev, "grad")) + self.assertTrue(hasattr(dist, "grad")) + elev_grad = elev.grad.clone() + dist_grad = dist.grad.clone() + azim = torch.tensor(azim) + elev = math.pi / 180.0 * elev.detach() + azim = math.pi / 180.0 * azim + grad_dist = ( + torch.cos(elev) * torch.sin(azim) + + torch.sin(elev) + + torch.cos(elev) * torch.cos(azim) + ) + grad_elev = ( + -(torch.sin(elev)) * torch.sin(azim) + + torch.cos(elev) + - torch.sin(elev) * torch.cos(azim) + ) + grad_elev = (dist * (math.pi / 180.0) * grad_elev).sum() + self.assertClose(elev_grad, grad_elev) + self.assertClose(dist_grad, torch.full([3], grad_dist)) + + def test_camera_position_from_angles_vectors_bad_broadcast(self): + # Batch dim for broadcast must be N or 1 + dist = torch.tensor([2.0, 3.0, 5.0]) + elev = torch.tensor([0.0, 90.0]) + azim = torch.tensor([90.0]) + with self.assertRaises(ValueError): + camera_position_from_spherical_angles(dist, elev, azim) + + def test_look_at_rotation_python_list(self): + camera_position = [[0.0, 0.0, -1.0]] # camera pointing along negative z + rot_mat = look_at_rotation(camera_position) + self.assertClose(rot_mat, torch.eye(3)[None], atol=2e-7) + + def test_look_at_rotation_input_fail(self): + camera_position = [-1.0] # expected to have xyz positions + with self.assertRaises(ValueError): + look_at_rotation(camera_position) + + def test_look_at_rotation_list_broadcast(self): + # fmt: off + camera_positions = [[0.0, 0.0, -1.0], [0.0, 0.0, 1.0]] + rot_mats_expected = torch.tensor( + [ + [ + [1.0, 0.0, 0.0], + [0.0, 1.0, 0.0], + [0.0, 0.0, 1.0] + ], + [ + [-1.0, 0.0, 0.0], # noqa: E241, E201 + [ 0.0, 1.0, 0.0], # noqa: E241, E201 + [ 0.0, 0.0, -1.0] # noqa: E241, E201 + ], + ], + dtype=torch.float32 + ) + # fmt: on + rot_mats = look_at_rotation(camera_positions) + self.assertClose(rot_mats, rot_mats_expected, atol=2e-7) + + def test_look_at_rotation_tensor_broadcast(self): + # fmt: off + camera_positions = torch.tensor([ + [0.0, 0.0, -1.0], + [0.0, 0.0, 1.0] # noqa: E241, E201 + ], dtype=torch.float32) + rot_mats_expected = torch.tensor( + [ + [ + [1.0, 0.0, 0.0], + [0.0, 1.0, 0.0], + [0.0, 0.0, 1.0] + ], + [ + [-1.0, 0.0, 0.0], # noqa: E241, E201 + [ 0.0, 1.0, 0.0], # noqa: E241, E201 + [ 0.0, 0.0, -1.0] # noqa: E241, E201 + ], + ], + dtype=torch.float32 + ) + # fmt: on + rot_mats = look_at_rotation(camera_positions) + self.assertClose(rot_mats, rot_mats_expected, atol=2e-7) + + def test_look_at_rotation_tensor_grad(self): + camera_position = torch.tensor([[0.0, 0.0, -1.0]], requires_grad=True) + rot_mat = look_at_rotation(camera_position) + rot_mat.sum().backward() + self.assertTrue(hasattr(camera_position, "grad")) + self.assertClose( + camera_position.grad, torch.zeros_like(camera_position), atol=2e-7 + ) + + def test_view_transform(self): + T = torch.tensor([0.0, 0.0, -1.0], requires_grad=True).view(1, -1) + R = look_at_rotation(T) + RT = get_world_to_view_transform(R=R, T=T) + self.assertTrue(isinstance(RT, Transform3d)) + + def test_look_at_view_transform_corner_case(self): + dist = 2.7 + elev = 90 + azim = 90 + expected_position = torch.tensor([0.0, 2.7, 0.0], dtype=torch.float32).view( + 1, 3 + ) + position = camera_position_from_spherical_angles(dist, elev, azim) + self.assertClose(position, expected_position, atol=2e-7) + R, _ = look_at_view_transform(eye=position) + x_axis = R[:, :, 0] + expected_x_axis = torch.tensor([0.0, 0.0, -1.0], dtype=torch.float32).view(1, 3) + self.assertClose(x_axis, expected_x_axis, atol=5e-3) + + +class TestCamerasCommon(TestCaseMixin, unittest.TestCase): + def test_K(self, batch_size=10): + T = torch.randn(batch_size, 3) + R = random_rotations(batch_size) + K = torch.randn(batch_size, 4, 4) + for cam_type in ( + FoVOrthographicCameras, + FoVPerspectiveCameras, + OrthographicCameras, + PerspectiveCameras, + ): + cam = cam_type(R=R, T=T, K=K) + cam.get_projection_transform() + # Just checking that we don't crash or anything + + def test_view_transform_class_method(self): + T = torch.tensor([0.0, 0.0, -1.0], requires_grad=True).view(1, -1) + R = look_at_rotation(T) + RT = get_world_to_view_transform(R=R, T=T) + for cam_type in ( + OpenGLPerspectiveCameras, + OpenGLOrthographicCameras, + SfMOrthographicCameras, + SfMPerspectiveCameras, + FoVOrthographicCameras, + FoVPerspectiveCameras, + OrthographicCameras, + PerspectiveCameras, + ): + cam = cam_type(R=R, T=T) + RT_class = cam.get_world_to_view_transform() + self.assertTrue(torch.allclose(RT.get_matrix(), RT_class.get_matrix())) + + self.assertTrue(isinstance(RT, Transform3d)) + + def test_get_camera_center(self, batch_size=10): + T = torch.randn(batch_size, 3) + R = random_rotations(batch_size) + for cam_type in ( + OpenGLPerspectiveCameras, + OpenGLOrthographicCameras, + SfMOrthographicCameras, + SfMPerspectiveCameras, + FoVOrthographicCameras, + FoVPerspectiveCameras, + OrthographicCameras, + PerspectiveCameras, + ): + cam = cam_type(R=R, T=T) + C = cam.get_camera_center() + C_ = -torch.bmm(R, T[:, :, None])[:, :, 0] + self.assertTrue(torch.allclose(C, C_, atol=1e-05)) + + @staticmethod + def init_equiv_cameras_ndc_screen(cam_type: CamerasBase, batch_size: int): + T = torch.randn(batch_size, 3) * 0.03 + T[:, 2] = 4 + R = so3_exp_map(torch.randn(batch_size, 3) * 3.0) + screen_cam_params = {"R": R, "T": T} + ndc_cam_params = {"R": R, "T": T} + if cam_type in (OrthographicCameras, PerspectiveCameras): + fcl = torch.rand((batch_size, 2)) * 3.0 + 0.1 + prc = torch.randn((batch_size, 2)) * 0.2 + # (height, width) + image_size = torch.randint(low=2, high=64, size=(batch_size, 2)) + # scale + scale = (image_size.min(dim=1, keepdim=True).values) / 2.0 + + ndc_cam_params["focal_length"] = fcl + ndc_cam_params["principal_point"] = prc + ndc_cam_params["image_size"] = image_size + + screen_cam_params["image_size"] = image_size + screen_cam_params["focal_length"] = fcl * scale + screen_cam_params["principal_point"] = ( + (image_size[:, [1, 0]]) / 2.0 - prc * scale + ) + screen_cam_params["in_ndc"] = False + else: + raise ValueError(str(cam_type)) + return cam_type(**ndc_cam_params), cam_type(**screen_cam_params) + + def test_unproject_points(self, batch_size=50, num_points=100): + """ + Checks that an unprojection of a randomly projected point cloud + stays the same. + """ + + for cam_type in ( + SfMOrthographicCameras, + OpenGLPerspectiveCameras, + OpenGLOrthographicCameras, + SfMPerspectiveCameras, + FoVOrthographicCameras, + FoVPerspectiveCameras, + OrthographicCameras, + PerspectiveCameras, + ): + # init the cameras + cameras = init_random_cameras(cam_type, batch_size) + # xyz - the ground truth point cloud + xyz = torch.randn(batch_size, num_points, 3) * 0.3 + # xyz in camera coordinates + xyz_cam = cameras.get_world_to_view_transform().transform_points(xyz) + # depth = z-component of xyz_cam + depth = xyz_cam[:, :, 2:] + # project xyz + xyz_proj = cameras.transform_points(xyz) + xy, cam_depth = xyz_proj.split(2, dim=2) + # input to the unprojection function + xy_depth = torch.cat((xy, depth), dim=2) + + for to_world in (False, True): + if to_world: + matching_xyz = xyz + else: + matching_xyz = xyz_cam + + # if we have FoV (= OpenGL) cameras + # test for scaled_depth_input=True/False + if cam_type in ( + OpenGLPerspectiveCameras, + OpenGLOrthographicCameras, + FoVPerspectiveCameras, + FoVOrthographicCameras, + ): + for scaled_depth_input in (True, False): + if scaled_depth_input: + xy_depth_ = xyz_proj + else: + xy_depth_ = xy_depth + xyz_unproj = cameras.unproject_points( + xy_depth_, + world_coordinates=to_world, + scaled_depth_input=scaled_depth_input, + ) + self.assertTrue( + torch.allclose(xyz_unproj, matching_xyz, atol=1e-4) + ) + else: + xyz_unproj = cameras.unproject_points( + xy_depth, world_coordinates=to_world + ) + self.assertTrue(torch.allclose(xyz_unproj, matching_xyz, atol=1e-4)) + + @staticmethod + def unproject_points( + cam_type, batch_size=50, num_points=100, device: Device = "cpu" + ): + """ + Checks that an unprojection of a randomly projected point cloud + stays the same. + """ + if device == "cuda": + device = torch.device("cuda:0") + else: + device = torch.device("cpu") + + str2cls = { # noqa + "OpenGLOrthographicCameras": OpenGLOrthographicCameras, + "OpenGLPerspectiveCameras": OpenGLPerspectiveCameras, + "SfMOrthographicCameras": SfMOrthographicCameras, + "SfMPerspectiveCameras": SfMPerspectiveCameras, + "FoVOrthographicCameras": FoVOrthographicCameras, + "FoVPerspectiveCameras": FoVPerspectiveCameras, + "OrthographicCameras": OrthographicCameras, + "PerspectiveCameras": PerspectiveCameras, + "FishEyeCameras": FishEyeCameras, + } + + def run_cameras(): + # init the cameras + cameras = init_random_cameras(str2cls[cam_type], batch_size, device=device) + # xyz - the ground truth point cloud + xyz = torch.randn(num_points, 3) * 0.3 + xyz = cameras.unproject_points(xyz, scaled_depth_input=True) + + return run_cameras + + def test_project_points_screen(self, batch_size=50, num_points=100): + """ + Checks that an unprojection of a randomly projected point cloud + stays the same. + """ + + for cam_type in ( + OpenGLOrthographicCameras, + OpenGLPerspectiveCameras, + SfMOrthographicCameras, + SfMPerspectiveCameras, + FoVOrthographicCameras, + FoVPerspectiveCameras, + OrthographicCameras, + PerspectiveCameras, + ): + # init the cameras + cameras = init_random_cameras(cam_type, batch_size) + # xyz - the ground truth point cloud + xy = torch.randn(batch_size, num_points, 2) * 2.0 - 1.0 + z = torch.randn(batch_size, num_points, 1) * 3.0 + 1.0 + xyz = torch.cat((xy, z), dim=2) + # image size + image_size = torch.randint(low=32, high=64, size=(batch_size, 2)) + # project points + xyz_project_ndc = cameras.transform_points_ndc(xyz) + xyz_project_screen = cameras.transform_points_screen( + xyz, image_size=image_size + ) + # naive + xyz_project_screen_naive = ndc_to_screen_points_naive( + xyz_project_ndc, image_size + ) + # we set atol to 1e-4, remember that screen points are in [0, W]x[0, H] space + self.assertClose(xyz_project_screen, xyz_project_screen_naive, atol=1e-4) + + @staticmethod + def transform_points( + cam_type, batch_size=50, num_points=100, device: Device = "cpu" + ): + """ + Checks that an unprojection of a randomly projected point cloud + stays the same. + """ + + if device == "cuda": + device = torch.device("cuda:0") + else: + device = torch.device("cpu") + str2cls = { # noqa + "OpenGLOrthographicCameras": OpenGLOrthographicCameras, + "OpenGLPerspectiveCameras": OpenGLPerspectiveCameras, + "SfMOrthographicCameras": SfMOrthographicCameras, + "SfMPerspectiveCameras": SfMPerspectiveCameras, + "FoVOrthographicCameras": FoVOrthographicCameras, + "FoVPerspectiveCameras": FoVPerspectiveCameras, + "OrthographicCameras": OrthographicCameras, + "PerspectiveCameras": PerspectiveCameras, + "FishEyeCameras": FishEyeCameras, + } + + def run_cameras(): + # init the cameras + cameras = init_random_cameras(str2cls[cam_type], batch_size, device=device) + # xyz - the ground truth point cloud + xy = torch.randn(num_points, 2) * 2.0 - 1.0 + z = torch.randn(num_points, 1) * 3.0 + 1.0 + xyz = torch.cat((xy, z), dim=-1) + xy = cameras.transform_points(xyz) + + return run_cameras + + def test_equiv_project_points(self, batch_size=50, num_points=100): + """ + Checks that NDC and screen cameras project points to ndc correctly. + Applies only to OrthographicCameras and PerspectiveCameras. + """ + for cam_type in (OrthographicCameras, PerspectiveCameras): + # init the cameras + ( + ndc_cameras, + screen_cameras, + ) = TestCamerasCommon.init_equiv_cameras_ndc_screen(cam_type, batch_size) + # xyz - the ground truth point cloud in Py3D space + xy = torch.randn(batch_size, num_points, 2) * 0.3 + z = torch.rand(batch_size, num_points, 1) + 3.0 + 0.1 + xyz = torch.cat((xy, z), dim=2) + # project points + xyz_ndc = ndc_cameras.transform_points_ndc(xyz) + xyz_screen = screen_cameras.transform_points_ndc(xyz) + # check correctness + self.assertClose(xyz_ndc, xyz_screen, atol=1e-5) + + def test_clone(self, batch_size: int = 10): + """ + Checks the clone function of the cameras. + """ + for cam_type in ( + SfMOrthographicCameras, + OpenGLPerspectiveCameras, + OpenGLOrthographicCameras, + SfMPerspectiveCameras, + FoVOrthographicCameras, + FoVPerspectiveCameras, + OrthographicCameras, + PerspectiveCameras, + ): + cameras = init_random_cameras(cam_type, batch_size) + cameras = cameras.to(torch.device("cpu")) + cameras_clone = cameras.clone() + + for var in cameras.__dict__.keys(): + val = getattr(cameras, var) + val_clone = getattr(cameras_clone, var) + if torch.is_tensor(val): + self.assertClose(val, val_clone) + self.assertSeparate(val, val_clone) + else: + self.assertTrue(val == val_clone) + + def test_join_cameras_as_batch_errors(self): + cam0 = PerspectiveCameras(device="cuda:0") + cam1 = OrthographicCameras(device="cuda:0") + + # Cameras not of the same type + with self.assertRaisesRegex(ValueError, "same type"): + join_cameras_as_batch([cam0, cam1]) + + cam2 = OrthographicCameras(device="cpu") + # Cameras not on the same device + with self.assertRaisesRegex(ValueError, "same device"): + join_cameras_as_batch([cam1, cam2]) + + cam3 = OrthographicCameras(in_ndc=False, device="cuda:0") + # Different coordinate systems -- all should be in ndc or in screen + with self.assertRaisesRegex( + ValueError, "Attribute _in_ndc is not constant across inputs" + ): + join_cameras_as_batch([cam1, cam3]) + + def join_cameras_as_batch_fov(self, camera_cls): + R0 = torch.randn((6, 3, 3)) + R1 = torch.randn((3, 3, 3)) + cam0 = camera_cls(znear=10.0, zfar=100.0, R=R0, device="cuda:0") + cam1 = camera_cls(znear=10.0, zfar=200.0, R=R1, device="cuda:0") + + cam_batch = join_cameras_as_batch([cam0, cam1]) + + self.assertEqual(cam_batch._N, cam0._N + cam1._N) + self.assertEqual(cam_batch.device, cam0.device) + self.assertClose(cam_batch.R, torch.cat((R0, R1), dim=0).to(device="cuda:0")) + + def join_cameras_as_batch(self, camera_cls): + R0 = torch.randn((6, 3, 3)) + R1 = torch.randn((3, 3, 3)) + p0 = torch.randn((6, 2, 1)) + p1 = torch.randn((3, 2, 1)) + f0 = 5.0 + f1 = torch.randn(3, 2) + f2 = torch.randn(3, 1) + cam0 = camera_cls( + R=R0, + focal_length=f0, + principal_point=p0, + ) + cam1 = camera_cls( + R=R1, + focal_length=f0, + principal_point=p1, + ) + cam2 = camera_cls( + R=R1, + focal_length=f1, + principal_point=p1, + ) + cam3 = camera_cls( + R=R1, + focal_length=f2, + principal_point=p1, + ) + cam_batch = join_cameras_as_batch([cam0, cam1]) + + self.assertEqual(cam_batch._N, cam0._N + cam1._N) + self.assertEqual(cam_batch.device, cam0.device) + self.assertClose(cam_batch.R, torch.cat((R0, R1), dim=0)) + self.assertClose(cam_batch.principal_point, torch.cat((p0, p1), dim=0)) + self.assertEqual(cam_batch._in_ndc, cam0._in_ndc) + + # Test one broadcasted value and one fixed value + # Focal length as (N,) in one camera and (N, 2) in the other + cam_batch = join_cameras_as_batch([cam0, cam2]) + self.assertEqual(cam_batch._N, cam0._N + cam2._N) + self.assertClose(cam_batch.R, torch.cat((R0, R1), dim=0)) + self.assertClose( + cam_batch.focal_length, + torch.cat([torch.tensor([[f0, f0]]).expand(6, -1), f1], dim=0), + ) + + # Focal length as (N, 1) in one camera and (N, 2) in the other + cam_batch = join_cameras_as_batch([cam2, cam3]) + self.assertClose( + cam_batch.focal_length, + torch.cat([f1, f2.expand(-1, 2)], dim=0), + ) + + def test_join_batch_perspective(self): + self.join_cameras_as_batch_fov(FoVPerspectiveCameras) + self.join_cameras_as_batch(PerspectiveCameras) + + def test_join_batch_orthographic(self): + self.join_cameras_as_batch_fov(FoVOrthographicCameras) + self.join_cameras_as_batch(OrthographicCameras) + + def test_iterable(self): + for camera_type in [PerspectiveCameras, OrthographicCameras]: + a_list = list(camera_type()) + self.assertEqual(len(a_list), 1) + + +############################################################ +# FoVPerspective Camera # +############################################################ + + +class TestFoVPerspectiveProjection(TestCaseMixin, unittest.TestCase): + def test_perspective(self): + far = 10.0 + near = 1.0 + cameras = FoVPerspectiveCameras(znear=near, zfar=far, fov=60.0) + P = cameras.get_projection_transform() + # vertices are at the far clipping plane so z gets mapped to 1. + vertices = torch.tensor([1, 2, far], dtype=torch.float32) + projected_verts = torch.tensor( + [np.sqrt(3) / far, 2 * np.sqrt(3) / far, 1.0], dtype=torch.float32 + ) + vertices = vertices[None, None, :] + v1 = P.transform_points(vertices) + v2 = perspective_project_naive(vertices, fov=60.0) + self.assertClose(v1[..., :2], v2[..., :2]) + self.assertClose(far * v1[..., 2], v2[..., 2]) + self.assertClose(v1.squeeze(), projected_verts) + + # vertices are at the near clipping plane so z gets mapped to 0.0. + vertices[..., 2] = near + projected_verts = torch.tensor( + [np.sqrt(3) / near, 2 * np.sqrt(3) / near, 0.0], dtype=torch.float32 + ) + v1 = P.transform_points(vertices) + v2 = perspective_project_naive(vertices, fov=60.0) + self.assertClose(v1[..., :2], v2[..., :2]) + self.assertClose(v1.squeeze(), projected_verts) + + def test_perspective_kwargs(self): + cameras = FoVPerspectiveCameras(znear=5.0, zfar=100.0, fov=0.0) + # Override defaults by passing in values to get_projection_transform + far = 10.0 + P = cameras.get_projection_transform(znear=1.0, zfar=far, fov=60.0) + vertices = torch.tensor([1, 2, far], dtype=torch.float32) + projected_verts = torch.tensor( + [np.sqrt(3) / far, 2 * np.sqrt(3) / far, 1.0], dtype=torch.float32 + ) + vertices = vertices[None, None, :] + v1 = P.transform_points(vertices) + self.assertClose(v1.squeeze(), projected_verts) + + def test_perspective_mixed_inputs_broadcast(self): + far = torch.tensor([10.0, 20.0], dtype=torch.float32) + near = 1.0 + fov = torch.tensor(60.0) + cameras = FoVPerspectiveCameras(znear=near, zfar=far, fov=fov) + P = cameras.get_projection_transform() + vertices = torch.tensor([1, 2, 10], dtype=torch.float32) + z1 = 1.0 # vertices at far clipping plane so z = 1.0 + z2 = (20.0 / (20.0 - 1.0) * 10.0 + -20.0 / (20.0 - 1.0)) / 10.0 + projected_verts = torch.tensor( + [ + [np.sqrt(3) / 10.0, 2 * np.sqrt(3) / 10.0, z1], + [np.sqrt(3) / 10.0, 2 * np.sqrt(3) / 10.0, z2], + ], + dtype=torch.float32, + ) + vertices = vertices[None, None, :] + v1 = P.transform_points(vertices) + v2 = perspective_project_naive(vertices, fov=60.0) + self.assertClose(v1[..., :2], torch.cat([v2, v2])[..., :2]) + self.assertClose(v1.squeeze(), projected_verts) + + def test_perspective_mixed_inputs_grad(self): + far = torch.tensor([10.0]) + near = 1.0 + fov = torch.tensor(60.0, requires_grad=True) + cameras = FoVPerspectiveCameras(znear=near, zfar=far, fov=fov) + P = cameras.get_projection_transform() + vertices = torch.tensor([1, 2, 10], dtype=torch.float32) + vertices_batch = vertices[None, None, :] + v1 = P.transform_points(vertices_batch).squeeze() + v1.sum().backward() + self.assertTrue(hasattr(fov, "grad")) + fov_grad = fov.grad.clone() + half_fov_rad = (math.pi / 180.0) * fov.detach() / 2.0 + grad_cotan = -(1.0 / (torch.sin(half_fov_rad) ** 2.0) * 1 / 2.0) + grad_fov = (math.pi / 180.0) * grad_cotan + grad_fov = (vertices[0] + vertices[1]) * grad_fov / 10.0 + self.assertClose(fov_grad, grad_fov) + + def test_camera_class_init(self): + device = torch.device("cuda:0") + cam = FoVPerspectiveCameras(znear=10.0, zfar=(100.0, 200.0)) + + # Check broadcasting + self.assertTrue(cam.znear.shape == (2,)) + self.assertTrue(cam.zfar.shape == (2,)) + + # Test to + new_cam = cam.to(device=device) + self.assertTrue(new_cam.device == device) + + def test_getitem(self): + N_CAMERAS = 6 + R_matrix = torch.randn((N_CAMERAS, 3, 3)) + cam = FoVPerspectiveCameras(znear=10.0, zfar=100.0, R=R_matrix) + + # Check get item returns an instance of the same class + # with all the same keys + c0 = cam[0] + self.assertTrue(isinstance(c0, FoVPerspectiveCameras)) + self.assertEqual(cam.__dict__.keys(), c0.__dict__.keys()) + + # Check all fields correct in get item with int index + self.assertEqual(len(c0), 1) + self.assertClose(c0.zfar, torch.tensor([100.0])) + self.assertClose(c0.znear, torch.tensor([10.0])) + self.assertClose(c0.R, R_matrix[0:1, ...]) + self.assertEqual(c0.device, torch.device("cpu")) + + # Check list(int) index + c012 = cam[[0, 1, 2]] + self.assertEqual(len(c012), 3) + self.assertClose(c012.zfar, torch.tensor([100.0] * 3)) + self.assertClose(c012.znear, torch.tensor([10.0] * 3)) + self.assertClose(c012.R, R_matrix[0:3, ...]) + + # Check torch.LongTensor index + SLICE = [1, 3, 5] + index = torch.tensor(SLICE, dtype=torch.int64) + c135 = cam[index] + self.assertEqual(len(c135), 3) + self.assertClose(c135.zfar, torch.tensor([100.0] * 3)) + self.assertClose(c135.znear, torch.tensor([10.0] * 3)) + self.assertClose(c135.R, R_matrix[SLICE, ...]) + + # Check torch.BoolTensor index + bool_slice = [i in SLICE for i in range(N_CAMERAS)] + index = torch.tensor(bool_slice, dtype=torch.bool) + c135 = cam[index] + self.assertEqual(len(c135), 3) + self.assertClose(c135.zfar, torch.tensor([100.0] * 3)) + self.assertClose(c135.znear, torch.tensor([10.0] * 3)) + self.assertClose(c135.R, R_matrix[SLICE, ...]) + + # Check errors with get item + with self.assertRaisesRegex(IndexError, "out of bounds"): + cam[N_CAMERAS] + + index = torch.tensor([1, 0, 1], dtype=torch.bool) + with self.assertRaisesRegex(ValueError, "does not match cameras"): + cam[index] + + with self.assertRaisesRegex(ValueError, "Invalid index type"): + cam[slice(0, 1)] + + with self.assertRaisesRegex(ValueError, "Invalid index type"): + cam[[True, False]] + + index = torch.tensor(SLICE, dtype=torch.float32) + with self.assertRaisesRegex(ValueError, "Invalid index type"): + cam[index] + + def test_get_full_transform(self): + cam = FoVPerspectiveCameras() + T = torch.tensor([0.0, 0.0, 1.0]).view(1, -1) + R = look_at_rotation(T) + P = cam.get_full_projection_transform(R=R, T=T) + self.assertTrue(isinstance(P, Transform3d)) + self.assertClose(cam.R, R) + self.assertClose(cam.T, T) + + def test_transform_points(self): + # Check transform_points methods works with default settings for + # RT and P + far = 10.0 + cam = FoVPerspectiveCameras(znear=1.0, zfar=far, fov=60.0) + points = torch.tensor([1, 2, far], dtype=torch.float32) + points = points.view(1, 1, 3).expand(5, 10, -1) + projected_points = torch.tensor( + [np.sqrt(3) / far, 2 * np.sqrt(3) / far, 1.0], dtype=torch.float32 + ) + projected_points = projected_points.view(1, 1, 3).expand(5, 10, -1) + new_points = cam.transform_points(points) + self.assertClose(new_points, projected_points) + + def test_perspective_type(self): + cam = FoVPerspectiveCameras(znear=1.0, zfar=10.0, fov=60.0) + self.assertTrue(cam.is_perspective()) + self.assertEqual(cam.get_znear(), 1.0) + + +############################################################ +# FoVOrthographic Camera # +############################################################ + + +class TestFoVOrthographicProjection(TestCaseMixin, unittest.TestCase): + def test_orthographic(self): + far = 10.0 + near = 1.0 + cameras = FoVOrthographicCameras(znear=near, zfar=far) + P = cameras.get_projection_transform() + + vertices = torch.tensor([1, 2, far], dtype=torch.float32) + projected_verts = torch.tensor([1, 2, 1], dtype=torch.float32) + vertices = vertices[None, None, :] + v1 = P.transform_points(vertices) + v2 = orthographic_project_naive(vertices) + self.assertClose(v1[..., :2], v2[..., :2]) + self.assertClose(v1.squeeze(), projected_verts) + + vertices[..., 2] = near + projected_verts[2] = 0.0 + v1 = P.transform_points(vertices) + v2 = orthographic_project_naive(vertices) + self.assertClose(v1[..., :2], v2[..., :2]) + self.assertClose(v1.squeeze(), projected_verts) + + def test_orthographic_scaled(self): + vertices = torch.tensor([1, 2, 0.5], dtype=torch.float32) + vertices = vertices[None, None, :] + scale = torch.tensor([[2.0, 0.5, 20]]) + # applying the scale puts the z coordinate at the far clipping plane + # so the z is mapped to 1.0 + projected_verts = torch.tensor([2, 1, 1], dtype=torch.float32) + cameras = FoVOrthographicCameras(znear=1.0, zfar=10.0, scale_xyz=scale) + P = cameras.get_projection_transform() + v1 = P.transform_points(vertices) + v2 = orthographic_project_naive(vertices, scale) + self.assertClose(v1[..., :2], v2[..., :2]) + self.assertClose(v1, projected_verts[None, None]) + + def test_orthographic_kwargs(self): + cameras = FoVOrthographicCameras(znear=5.0, zfar=100.0) + far = 10.0 + P = cameras.get_projection_transform(znear=1.0, zfar=far) + vertices = torch.tensor([1, 2, far], dtype=torch.float32) + projected_verts = torch.tensor([1, 2, 1], dtype=torch.float32) + vertices = vertices[None, None, :] + v1 = P.transform_points(vertices) + self.assertClose(v1.squeeze(), projected_verts) + + def test_orthographic_mixed_inputs_broadcast(self): + far = torch.tensor([10.0, 20.0]) + near = 1.0 + cameras = FoVOrthographicCameras(znear=near, zfar=far) + P = cameras.get_projection_transform() + vertices = torch.tensor([1.0, 2.0, 10.0], dtype=torch.float32) + z2 = 1.0 / (20.0 - 1.0) * 10.0 + -1.0 / (20.0 - 1.0) + projected_verts = torch.tensor( + [[1.0, 2.0, 1.0], [1.0, 2.0, z2]], dtype=torch.float32 + ) + vertices = vertices[None, None, :] + v1 = P.transform_points(vertices) + v2 = orthographic_project_naive(vertices) + self.assertClose(v1[..., :2], torch.cat([v2, v2])[..., :2]) + self.assertClose(v1.squeeze(), projected_verts) + + def test_orthographic_mixed_inputs_grad(self): + far = torch.tensor([10.0]) + near = 1.0 + scale = torch.tensor([[1.0, 1.0, 1.0]], requires_grad=True) + cameras = FoVOrthographicCameras(znear=near, zfar=far, scale_xyz=scale) + P = cameras.get_projection_transform() + vertices = torch.tensor([1.0, 2.0, 10.0], dtype=torch.float32) + vertices_batch = vertices[None, None, :] + v1 = P.transform_points(vertices_batch) + v1.sum().backward() + self.assertTrue(hasattr(scale, "grad")) + scale_grad = scale.grad.clone() + grad_scale = torch.tensor( + [ + [ + vertices[0] * P._matrix[:, 0, 0], + vertices[1] * P._matrix[:, 1, 1], + vertices[2] * P._matrix[:, 2, 2], + ] + ] + ) + self.assertClose(scale_grad, grad_scale) + + def test_perspective_type(self): + cam = FoVOrthographicCameras(znear=1.0, zfar=10.0) + self.assertFalse(cam.is_perspective()) + self.assertEqual(cam.get_znear(), 1.0) + + def test_getitem(self): + R_matrix = torch.randn((6, 3, 3)) + scale = torch.tensor([[1.0, 1.0, 1.0]], requires_grad=True) + cam = FoVOrthographicCameras( + znear=10.0, zfar=100.0, R=R_matrix, scale_xyz=scale + ) + + # Check get item returns an instance of the same class + # with all the same keys + c0 = cam[0] + self.assertTrue(isinstance(c0, FoVOrthographicCameras)) + self.assertEqual(cam.__dict__.keys(), c0.__dict__.keys()) + + # Check torch.LongTensor index + index = torch.tensor([1, 3, 5], dtype=torch.int64) + c135 = cam[index] + self.assertEqual(len(c135), 3) + self.assertClose(c135.zfar, torch.tensor([100.0] * 3)) + self.assertClose(c135.znear, torch.tensor([10.0] * 3)) + self.assertClose(c135.min_x, torch.tensor([-1.0] * 3)) + self.assertClose(c135.max_x, torch.tensor([1.0] * 3)) + self.assertClose(c135.R, R_matrix[[1, 3, 5], ...]) + self.assertClose(c135.scale_xyz, scale.expand(3, -1)) + + +############################################################ +# Orthographic Camera # +############################################################ + + +class TestOrthographicProjection(TestCaseMixin, unittest.TestCase): + def test_orthographic(self): + cameras = OrthographicCameras() + P = cameras.get_projection_transform() + + vertices = torch.randn([3, 4, 3], dtype=torch.float32) + projected_verts = vertices.clone() + v1 = P.transform_points(vertices) + v2 = orthographic_project_naive(vertices) + + self.assertClose(v1[..., :2], v2[..., :2]) + self.assertClose(v1, projected_verts) + + def test_orthographic_scaled(self): + focal_length_x = 10.0 + focal_length_y = 15.0 + + cameras = OrthographicCameras(focal_length=((focal_length_x, focal_length_y),)) + P = cameras.get_projection_transform() + + vertices = torch.randn([3, 4, 3], dtype=torch.float32) + projected_verts = vertices.clone() + projected_verts[:, :, 0] *= focal_length_x + projected_verts[:, :, 1] *= focal_length_y + v1 = P.transform_points(vertices) + v2 = orthographic_project_naive( + vertices, scale_xyz=(focal_length_x, focal_length_y, 1.0) + ) + v3 = cameras.transform_points(vertices) + self.assertClose(v1[..., :2], v2[..., :2]) + self.assertClose(v3[..., :2], v2[..., :2]) + self.assertClose(v1, projected_verts) + + def test_orthographic_kwargs(self): + cameras = OrthographicCameras(focal_length=5.0, principal_point=((2.5, 2.5),)) + P = cameras.get_projection_transform( + focal_length=2.0, principal_point=((2.5, 3.5),) + ) + vertices = torch.randn([3, 4, 3], dtype=torch.float32) + projected_verts = vertices.clone() + projected_verts[:, :, :2] *= 2.0 + projected_verts[:, :, 0] += 2.5 + projected_verts[:, :, 1] += 3.5 + v1 = P.transform_points(vertices) + self.assertClose(v1, projected_verts) + + def test_perspective_type(self): + cam = OrthographicCameras(focal_length=5.0, principal_point=((2.5, 2.5),)) + self.assertFalse(cam.is_perspective()) + self.assertIsNone(cam.get_znear()) + + def test_getitem(self): + R_matrix = torch.randn((6, 3, 3)) + principal_point = torch.randn((6, 2, 1)) + focal_length = 5.0 + cam = OrthographicCameras( + R=R_matrix, + focal_length=focal_length, + principal_point=principal_point, + ) + + # Check get item returns an instance of the same class + # with all the same keys + c0 = cam[0] + self.assertTrue(isinstance(c0, OrthographicCameras)) + self.assertEqual(cam.__dict__.keys(), c0.__dict__.keys()) + + # Check torch.LongTensor index + index = torch.tensor([1, 3, 5], dtype=torch.int64) + c135 = cam[index] + self.assertEqual(len(c135), 3) + self.assertClose(c135.focal_length, torch.tensor([[5.0, 5.0]] * 3)) + self.assertClose(c135.R, R_matrix[[1, 3, 5], ...]) + self.assertClose(c135.principal_point, principal_point[[1, 3, 5], ...]) + + +############################################################ +# Perspective Camera # +############################################################ + + +class TestPerspectiveProjection(TestCaseMixin, unittest.TestCase): + def test_perspective(self): + cameras = PerspectiveCameras() + P = cameras.get_projection_transform() + + vertices = torch.randn([3, 4, 3], dtype=torch.float32) + v1 = P.transform_points(vertices) + v2 = sfm_perspective_project_naive(vertices) + self.assertClose(v1, v2) + + def test_perspective_scaled(self): + focal_length_x = 10.0 + focal_length_y = 15.0 + p0x = 15.0 + p0y = 30.0 + + cameras = PerspectiveCameras( + focal_length=((focal_length_x, focal_length_y),), + principal_point=((p0x, p0y),), + ) + P = cameras.get_projection_transform() + + vertices = torch.randn([3, 4, 3], dtype=torch.float32) + v1 = P.transform_points(vertices) + v2 = sfm_perspective_project_naive( + vertices, fx=focal_length_x, fy=focal_length_y, p0x=p0x, p0y=p0y + ) + v3 = cameras.transform_points(vertices) + self.assertClose(v1, v2) + self.assertClose(v3[..., :2], v2[..., :2]) + + def test_perspective_kwargs(self): + cameras = PerspectiveCameras(focal_length=5.0, principal_point=((2.5, 2.5),)) + P = cameras.get_projection_transform( + focal_length=2.0, principal_point=((2.5, 3.5),) + ) + vertices = torch.randn([3, 4, 3], dtype=torch.float32) + v1 = P.transform_points(vertices) + v2 = sfm_perspective_project_naive(vertices, fx=2.0, fy=2.0, p0x=2.5, p0y=3.5) + self.assertClose(v1, v2, atol=1e-6) + + def test_perspective_type(self): + cam = PerspectiveCameras(focal_length=5.0, principal_point=((2.5, 2.5),)) + self.assertTrue(cam.is_perspective()) + self.assertIsNone(cam.get_znear()) + + def test_getitem(self): + R_matrix = torch.randn((6, 3, 3)) + principal_point = torch.randn((6, 2, 1)) + focal_length = 5.0 + cam = PerspectiveCameras( + R=R_matrix, + focal_length=focal_length, + principal_point=principal_point, + ) + + # Check get item returns an instance of the same class + # with all the same keys + c0 = cam[0] + self.assertTrue(isinstance(c0, PerspectiveCameras)) + self.assertEqual(cam.__dict__.keys(), c0.__dict__.keys()) + + # Check torch.LongTensor index + index = torch.tensor([1, 3, 5], dtype=torch.int64) + c135 = cam[index] + self.assertEqual(len(c135), 3) + self.assertClose(c135.focal_length, torch.tensor([[5.0, 5.0]] * 3)) + self.assertClose(c135.R, R_matrix[[1, 3, 5], ...]) + self.assertClose(c135.principal_point, principal_point[[1, 3, 5], ...]) + + # Check in_ndc is handled correctly + self.assertEqual(cam._in_ndc, c0._in_ndc) + + def test_clone_picklable(self): + camera = PerspectiveCameras() + pickle.dumps(camera) + pickle.dumps(camera.clone()) + + +############################################################ +# FishEye Camera # +############################################################ + + +class TestFishEyeProjection(TestCaseMixin, unittest.TestCase): + def setUpSimpleCase(self) -> None: + super().setUp() + focal = torch.tensor([[240]], dtype=torch.float32) + principal_point = torch.tensor([[320, 240]]) + p_3d = torch.tensor( + [ + [2.0, 3.0, 1.0], + [3.0, 2.0, 1.0], + ], + dtype=torch.float32, + ) + return focal, principal_point, p_3d + + def setUpAriaCase(self) -> None: + super().setUp() + torch.manual_seed(42) + focal = torch.tensor([[608.9255557152]], dtype=torch.float32) + principal_point = torch.tensor( + [[712.0114821205, 706.8666571177]], dtype=torch.float32 + ) + radial_params = torch.tensor( + [ + [ + 0.3877090026, + -0.315613384, + -0.3434984955, + 1.8565874201, + -2.1799372221, + 0.7713834763, + ], + ], + dtype=torch.float32, + ) + tangential_params = torch.tensor( + [[-0.0002747019, 0.0005228974]], dtype=torch.float32 + ) + thin_prism_params = torch.tensor( + [ + [0.000134884, -0.000084822, -0.0009420014, -0.0001276838], + ], + dtype=torch.float32, + ) + return ( + focal, + principal_point, + radial_params, + tangential_params, + thin_prism_params, + ) + + def setUpBatchCameras(self, combination: None) -> None: + super().setUp() + focal, principal_point, p_3d = self.setUpSimpleCase() + radial_params = torch.tensor( + [ + [0, 0, 0, 0, 0, 0], + ], + dtype=torch.float32, + ) + tangential_params = torch.tensor([[0, 0]], dtype=torch.float32) + thin_prism_params = torch.tensor([[0, 0, 0, 0]], dtype=torch.float32) + ( + focal1, + principal_point1, + radial_params1, + tangential_params1, + thin_prism_params1, + ) = self.setUpAriaCase() + focal = torch.cat([focal, focal1], dim=0) + principal_point = torch.cat([principal_point, principal_point1], dim=0) + radial_params = torch.cat([radial_params, radial_params1], dim=0) + tangential_params = torch.cat([tangential_params, tangential_params1], dim=0) + thin_prism_params = torch.cat([thin_prism_params, thin_prism_params1], dim=0) + if combination is None: + combination = [True, True, True] + cameras = FishEyeCameras( + use_radial=combination[0], + use_tangential=combination[1], + use_thin_prism=combination[2], + focal_length=focal, + principal_point=principal_point, + radial_params=radial_params, + tangential_params=tangential_params, + thin_prism_params=thin_prism_params, + ) + + return cameras + + def test_distortion_params_set_to_zeors(self): + # test case 1: all distortion params are 0. Note that + # setting radial_params to zeros is not equivalent to + # disabling radial distortions, set use_radial=False does + focal, principal_point, p_3d = self.setUpSimpleCase() + cameras = FishEyeCameras( + focal_length=focal, + principal_point=principal_point, + ) + uv_case1 = cameras.transform_points(p_3d) + self.assertClose( + uv_case1, + torch.tensor( + [[493.0993, 499.6489, 1.0], [579.6489, 413.0993, 1.0]], + ), + ) + # test case 2: equivalent of test case 1 by + # disabling use_tangential and use_thin_prism + cameras = FishEyeCameras( + focal_length=focal, + principal_point=principal_point, + use_tangential=False, + use_thin_prism=False, + ) + uv_case2 = cameras.transform_points(p_3d) + self.assertClose(uv_case2, uv_case1) + + def test_fisheye_against_perspective_cameras(self): + # test case: check equivalence with PerspectiveCameras + # by disabling all distortions + focal, principal_point, p_3d = self.setUpSimpleCase() + cameras = PerspectiveCameras( + focal_length=focal, + principal_point=principal_point, + ) + P = cameras.get_projection_transform() + uv_perspective = P.transform_points(p_3d) + + # disable all distortions + cameras = FishEyeCameras( + focal_length=focal, + principal_point=principal_point, + use_radial=False, + use_tangential=False, + use_thin_prism=False, + ) + uv = cameras.transform_points(p_3d) + self.assertClose(uv, uv_perspective) + + def test_project_shape_broadcasts(self): + focal, principal_point, p_3d = self.setUpSimpleCase() + torch.set_printoptions(precision=6) + combinations = product([0, 1], repeat=3) + for combination in combinations: + cameras = FishEyeCameras( + use_radial=combination[0], + use_tangential=combination[1], + use_thin_prism=combination[2], + focal_length=focal, + principal_point=principal_point, + ) + # test case 1: + # 1 transform with points of shape (P, 3) -> (P, 3) + # 1 transform with points of shape (1, P, 3) -> (1, P, 3) + # 1 transform with points of shape (M, P, 3) -> (M, P, 3) + points = p_3d.repeat(1, 1, 1) + cameras = FishEyeCameras( + focal_length=focal, + principal_point=principal_point, + use_radial=False, + use_tangential=False, + use_thin_prism=False, + ) + uv = cameras.transform_points(p_3d) + uv_point_batch = cameras.transform_points(points) + self.assertClose(uv_point_batch, uv.repeat(1, 1, 1)) + + points = p_3d.repeat(3, 1, 1) + uv_point_batch = cameras.transform_points(points) + self.assertClose(uv_point_batch, uv.repeat(3, 1, 1)) + + # test case 2 + # test with N transforms and points of shape (P, 3) -> (N, P, 3) + # test with N transforms and points of shape (1, P, 3) -> (N, P, 3) + torch.set_printoptions(sci_mode=False) + p_3d = torch.tensor( + [ + [2.0, 3.0, 1.0], + [3.0, 2.0, 1.0], + ] + ) + expected_res = torch.tensor( + [ + [ + [ + [800.000000, 960.000000, 1.000000], + [1040.000000, 720.000000, 1.000000], + ], + [ + [1929.862549, 2533.643311, 1.000000], + [2538.788086, 1924.717773, 1.000000], + ], + ], + [ + [ + [800.000000, 960.000000, 1.000000], + [1040.000000, 720.000000, 1.000000], + ], + [ + [1927.272095, 2524.220459, 1.000000], + [2536.197754, 1915.295166, 1.000000], + ], + ], + [ + [ + [800.000000, 960.000000, 1.000000], + [1040.000000, 720.000000, 1.000000], + ], + [ + [1930.050293, 2538.434814, 1.000000], + [2537.956543, 1927.569092, 1.000000], + ], + ], + [ + [ + [800.000000, 960.000000, 1.000000], + [1040.000000, 720.000000, 1.000000], + ], + [ + [1927.459839, 2529.011963, 1.000000], + [2535.366211, 1918.146484, 1.000000], + ], + ], + [ + [ + [493.099304, 499.648926, 1.000000], + [579.648926, 413.099304, 1.000000], + ], + [ + [1662.673950, 2132.860352, 1.000000], + [2138.005127, 1657.529053, 1.000000], + ], + ], + [ + [ + [493.099304, 499.648926, 1.000000], + [579.648926, 413.099304, 1.000000], + ], + [ + [1660.083496, 2123.437744, 1.000000], + [2135.414795, 1648.106445, 1.000000], + ], + ], + [ + [ + [493.099304, 499.648926, 1.000000], + [579.648926, 413.099304, 1.000000], + ], + [ + [1662.861816, 2137.651855, 1.000000], + [2137.173828, 1660.380371, 1.000000], + ], + ], + [ + [ + [493.099304, 499.648926, 1.000000], + [579.648926, 413.099304, 1.000000], + ], + [ + [1660.271240, 2128.229248, 1.000000], + [2134.583496, 1650.957764, 1.000000], + ], + ], + ] + ) + combinations = product([0, 1], repeat=3) + for i, combination in enumerate(combinations): + cameras = self.setUpBatchCameras(combination) + uv_point_batch = cameras.transform_points(p_3d) + self.assertClose(uv_point_batch, expected_res[i]) + + uv_point_batch = cameras.transform_points(p_3d.repeat(1, 1, 1)) + self.assertClose(uv_point_batch, expected_res[i].repeat(1, 1, 1)) + + def test_cuda(self): + """ + Test cuda device + """ + focal, principal_point, p_3d = self.setUpSimpleCase() + cameras_cuda = FishEyeCameras( + focal_length=focal, + principal_point=principal_point, + device="cuda:0", + ) + uv = cameras_cuda.transform_points(p_3d) + expected_res = torch.tensor( + [[493.0993, 499.6489, 1.0], [579.6489, 413.0993, 1.0]], + ) + self.assertClose(uv, expected_res.to("cuda:0")) + + rep_3d = cameras_cuda.unproject_points(uv) + self.assertClose(rep_3d, p_3d.to("cuda:0")) + + def test_unproject_shape_broadcasts(self): + # test case 1: + # 1 transform with points of (P, 3) -> (P, 3) + # 1 transform with points of (M, P, 3) -> (M, P, 3) + ( + focal, + principal_point, + radial_params, + tangential_params, + thin_prism_params, + ) = self.setUpAriaCase() + xy_depth = torch.tensor( + [ + [2134.5814033, 1650.95653328, 1.0], + [1074.25442904, 1159.52461285, 1.0], + ] + ) + cameras = FishEyeCameras( + focal_length=focal, + principal_point=principal_point, + radial_params=radial_params, + tangential_params=tangential_params, + thin_prism_params=thin_prism_params, + ) + rep_3d = cameras.unproject_points(xy_depth) + expected_res = torch.tensor( + [ + [[2.999442, 1.990583, 1.000000], [0.666728, 0.833142, 1.000000]], + [[2.997338, 2.005411, 1.000000], [0.666859, 0.834456, 1.000000]], + [[3.002090, 1.985229, 1.000000], [0.666537, 0.832025, 1.000000]], + [[2.999999, 2.000000, 1.000000], [0.666667, 0.833333, 1.000000]], + [[2.999442, 1.990583, 1.000000], [0.666728, 0.833142, 1.000000]], + [[2.997338, 2.005411, 1.000000], [0.666859, 0.834456, 1.000000]], + [[3.002090, 1.985229, 1.000000], [0.666537, 0.832025, 1.000000]], + [[2.999999, 2.000000, 1.000000], [0.666667, 0.833333, 1.000000]], + ] + ) + torch.set_printoptions(precision=6) + combinations = product([0, 1], repeat=3) + for i, combination in enumerate(combinations): + cameras = FishEyeCameras( + use_radial=combination[0], + use_tangential=combination[1], + use_thin_prism=combination[2], + focal_length=focal, + principal_point=principal_point, + radial_params=radial_params, + tangential_params=tangential_params, + thin_prism_params=thin_prism_params, + ) + rep_3d = cameras.unproject_points(xy_depth) + self.assertClose(rep_3d, expected_res[i]) + rep_3d = cameras.unproject_points(xy_depth.repeat(3, 1, 1)) + self.assertClose(rep_3d, expected_res[i].repeat(3, 1, 1)) + + # test case 2: + # N transforms with points of (P, 3) -> (N, P, 3) + # N transforms with points of (1, P, 3) -> (N, P, 3) + cameras = FishEyeCameras( + use_radial=combination[0], + use_tangential=combination[1], + use_thin_prism=combination[2], + focal_length=focal.repeat(2, 1), + principal_point=principal_point.repeat(2, 1), + radial_params=radial_params.repeat(2, 1), + tangential_params=tangential_params.repeat(2, 1), + thin_prism_params=thin_prism_params.repeat(2, 1), + ) + rep_3d = cameras.unproject_points(xy_depth) + self.assertClose(rep_3d, expected_res[i].repeat(2, 1, 1)) + + def test_unhandled_shape(self): + """ + Test error handling when shape of transforms + and points are not expected. + """ + cameras = self.setUpBatchCameras(None) + points = torch.rand(3, 3, 1) + with self.assertRaises(ValueError): + cameras.transform_points(points) + + def test_getitem(self): + # Check get item returns an instance of the same class + # with all the same keys + cam = self.setUpBatchCameras(None) + c0 = cam[0] + self.assertTrue(isinstance(c0, FishEyeCameras)) + self.assertEqual(cam.__dict__.keys(), c0.__dict__.keys()) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_cameras_alignment.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_cameras_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..3481064807195dacdbd6b4bd8878c2c869afba0c --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_cameras_alignment.py @@ -0,0 +1,177 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import unittest + +import numpy as np +import torch +from pytorch3d.ops import corresponding_cameras_alignment +from pytorch3d.renderer.cameras import ( + OpenGLOrthographicCameras, + OpenGLPerspectiveCameras, + SfMOrthographicCameras, + SfMPerspectiveCameras, +) +from pytorch3d.transforms.rotation_conversions import random_rotations +from pytorch3d.transforms.so3 import so3_exp_map, so3_relative_angle + +from .common_testing import TestCaseMixin +from .test_cameras import init_random_cameras + + +class TestCamerasAlignment(TestCaseMixin, unittest.TestCase): + def setUp(self) -> None: + super().setUp() + torch.manual_seed(42) + np.random.seed(42) + + def test_corresponding_cameras_alignment(self): + """ + Checks the corresponding_cameras_alignment function. + """ + device = torch.device("cuda:0") + + # try few different random setups + for _ in range(3): + for estimate_scale in (True, False): + # init true alignment transform + R_align_gt = random_rotations(1, device=device)[0] + T_align_gt = torch.randn(3, dtype=torch.float32, device=device) + + # init true scale + if estimate_scale: + s_align_gt = torch.randn( + 1, dtype=torch.float32, device=device + ).exp() + else: + s_align_gt = torch.tensor(1.0, dtype=torch.float32, device=device) + + for cam_type in ( + SfMOrthographicCameras, + OpenGLPerspectiveCameras, + OpenGLOrthographicCameras, + SfMPerspectiveCameras, + ): + # try well-determined and underdetermined cases + for batch_size in (10, 4, 3, 2, 1): + # get random cameras + cameras = init_random_cameras( + cam_type, batch_size, random_z=True + ).to(device) + # try all alignment modes + for mode in ("extrinsics", "centers"): + # try different noise levels + for add_noise in (0.0, 0.01, 1e-4): + self._corresponding_cameras_alignment_test_case( + cameras, + R_align_gt, + T_align_gt, + s_align_gt, + estimate_scale, + mode, + add_noise, + ) + + def _corresponding_cameras_alignment_test_case( + self, + cameras, + R_align_gt, + T_align_gt, + s_align_gt, + estimate_scale, + mode, + add_noise, + ): + batch_size = cameras.R.shape[0] + + # get target camera centers + R_new = torch.bmm(R_align_gt[None].expand_as(cameras.R), cameras.R) + T_new = ( + torch.bmm(T_align_gt[None, None].repeat(batch_size, 1, 1), cameras.R)[:, 0] + + cameras.T + ) * s_align_gt + + if add_noise != 0.0: + R_new = torch.bmm(R_new, so3_exp_map(torch.randn_like(T_new) * add_noise)) + T_new += torch.randn_like(T_new) * add_noise + + # create new cameras from R_new and T_new + cameras_tgt = cameras.clone() + cameras_tgt.R = R_new + cameras_tgt.T = T_new + + # align cameras and cameras_tgt + cameras_aligned = corresponding_cameras_alignment( + cameras, cameras_tgt, estimate_scale=estimate_scale, mode=mode + ) + + if batch_size <= 2 and mode == "centers": + # underdetermined case - check only the center alignment error + # since the rotation and translation are ambiguous here + self.assertClose( + cameras_aligned.get_camera_center(), + cameras_tgt.get_camera_center(), + atol=max(add_noise * 7.0, 1e-4), + ) + + else: + + def _rmse(a): + return (torch.norm(a, dim=1, p=2) ** 2).mean().sqrt() + + if add_noise != 0.0: + # in a noisy case check mean rotation/translation error for + # extrinsic alignment and root mean center error for center alignment + if mode == "centers": + self.assertNormsClose( + cameras_aligned.get_camera_center(), + cameras_tgt.get_camera_center(), + _rmse, + atol=max(add_noise * 10.0, 1e-4), + ) + elif mode == "extrinsics": + angle_err = so3_relative_angle( + cameras_aligned.R, cameras_tgt.R, cos_angle=True + ).mean() + self.assertClose( + angle_err, torch.ones_like(angle_err), atol=add_noise * 0.03 + ) + self.assertNormsClose( + cameras_aligned.T, cameras_tgt.T, _rmse, atol=add_noise * 7.0 + ) + else: + raise ValueError(mode) + + else: + # compare the rotations and translations of cameras + self.assertClose(cameras_aligned.R, cameras_tgt.R, atol=3e-4) + self.assertClose(cameras_aligned.T, cameras_tgt.T, atol=3e-4) + # compare the centers + self.assertClose( + cameras_aligned.get_camera_center(), + cameras_tgt.get_camera_center(), + atol=3e-4, + ) + + @staticmethod + def corresponding_cameras_alignment( + batch_size: int, estimate_scale: bool, mode: str, cam_type=SfMPerspectiveCameras + ): + device = torch.device("cuda:0") + cameras_src, cameras_tgt = [ + init_random_cameras(cam_type, batch_size, random_z=True).to(device) + for _ in range(2) + ] + + torch.cuda.synchronize() + + def compute_corresponding_cameras_alignment(): + corresponding_cameras_alignment( + cameras_src, cameras_tgt, estimate_scale=estimate_scale, mode=mode + ) + torch.cuda.synchronize() + + return compute_corresponding_cameras_alignment diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_checkerboard.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_checkerboard.py new file mode 100644 index 0000000000000000000000000000000000000000..7da0dbacefa96365fe97a5bc1ac28c06b327de61 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_checkerboard.py @@ -0,0 +1,21 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import unittest + +import torch +from pytorch3d.utils import checkerboard + +from .common_testing import TestCaseMixin + + +class TestCheckerboard(TestCaseMixin, unittest.TestCase): + def test_simple(self): + board = checkerboard(5) + verts = board.verts_packed() + expect = torch.tensor([5.0, 5.0, 0]) + self.assertClose(verts.min(dim=0).values, -expect) + self.assertClose(verts.max(dim=0).values, expect) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_common_linear_with_repeat.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_common_linear_with_repeat.py new file mode 100644 index 0000000000000000000000000000000000000000..2b7cb63f4dc5bc139931bf657cedaa88368d7c79 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_common_linear_with_repeat.py @@ -0,0 +1,33 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import unittest + +import torch +from pytorch3d.common.linear_with_repeat import LinearWithRepeat + +from .common_testing import TestCaseMixin + + +class TestLinearWithRepeat(TestCaseMixin, unittest.TestCase): + def setUp(self) -> None: + super().setUp() + torch.manual_seed(42) + + def test_simple(self): + x = torch.rand(4, 6, 7, 3) + y = torch.rand(4, 6, 4) + + linear = torch.nn.Linear(7, 8) + torch.nn.init.xavier_uniform_(linear.weight.data) + linear.bias.data.uniform_() + equivalent = torch.cat([x, y.unsqueeze(-2).expand(4, 6, 7, 4)], dim=-1) + expected = linear.forward(equivalent) + + linear_with_repeat = LinearWithRepeat(7, 8) + linear_with_repeat.load_state_dict(linear.state_dict()) + actual = linear_with_repeat.forward((x, y)) + self.assertClose(actual, expected, rtol=1e-4) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_common_testing.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_common_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..e57f4c5c25031f38f70acfff9c433fca4702063a --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_common_testing.py @@ -0,0 +1,62 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import unittest + +import numpy as np +import torch + +from .common_testing import TestCaseMixin + + +class TestOpsUtils(TestCaseMixin, unittest.TestCase): + def setUp(self) -> None: + super().setUp() + torch.manual_seed(42) + np.random.seed(42) + + def test_all_close(self): + device = torch.device("cuda:0") + n_points = 20 + noise_std = 1e-3 + msg = "tratata" + + # test absolute tolerance + x = torch.rand(n_points, 3, device=device) + x_noise = x + noise_std * torch.rand(n_points, 3, device=device) + assert torch.allclose(x, x_noise, atol=10 * noise_std) + assert not torch.allclose(x, x_noise, atol=0.1 * noise_std) + self.assertClose(x, x_noise, atol=10 * noise_std) + with self.assertRaises(AssertionError) as context: + self.assertClose(x, x_noise, atol=0.1 * noise_std, msg=msg) + self.assertTrue(msg in str(context.exception)) + + # test numpy + def to_np(t): + return t.data.cpu().numpy() + + self.assertClose(to_np(x), to_np(x_noise), atol=10 * noise_std) + with self.assertRaises(AssertionError) as context: + self.assertClose(to_np(x), to_np(x_noise), atol=0.1 * noise_std, msg=msg) + self.assertIn(msg, str(context.exception)) + self.assertIn("Not close", str(context.exception)) + + # test relative tolerance + assert torch.allclose(x, x_noise, rtol=100 * noise_std) + assert not torch.allclose(x, x_noise, rtol=noise_std) + self.assertClose(x, x_noise, rtol=100 * noise_std) + with self.assertRaises(AssertionError) as context: + self.assertClose(x, x_noise, rtol=noise_std, msg=msg) + self.assertTrue(msg in str(context.exception)) + + # test norm aggregation + # if one of the spatial dimensions is small, norm aggregation helps + x_noise[:, 0] = x_noise[:, 0] - x[:, 0] + x[:, 0] = 0.0 + assert not torch.allclose(x, x_noise, rtol=100 * noise_std) + self.assertNormsClose( + x, x_noise, rtol=100 * noise_std, norm_fn=lambda t: t.norm(dim=-1) + ) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_harmonic_embedding.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_harmonic_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..91e1ba8bbaad747e442ed7b0f38caa367e869710 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_harmonic_embedding.py @@ -0,0 +1,153 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import unittest + +import torch +from pytorch3d.renderer.implicit import HarmonicEmbedding +from torch.distributions import MultivariateNormal + +from .common_testing import TestCaseMixin + + +class TestHarmonicEmbedding(TestCaseMixin, unittest.TestCase): + def setUp(self) -> None: + super().setUp() + torch.manual_seed(1) + + def test_correct_output_dim(self): + embed_fun = HarmonicEmbedding(n_harmonic_functions=2, append_input=False) + # input_dims * (2 * n_harmonic_functions + int(append_input)) + output_dim = 3 * (2 * 2 + int(False)) + self.assertEqual( + output_dim, + embed_fun.get_output_dim_static( + input_dims=3, n_harmonic_functions=2, append_input=False + ), + ) + self.assertEqual(output_dim, embed_fun.get_output_dim()) + + def test_correct_frequency_range(self): + embed_fun_log = HarmonicEmbedding(n_harmonic_functions=3) + embed_fun_lin = HarmonicEmbedding(n_harmonic_functions=3, logspace=False) + self.assertClose(embed_fun_log._frequencies, torch.FloatTensor((1.0, 2.0, 4.0))) + self.assertClose(embed_fun_lin._frequencies, torch.FloatTensor((1.0, 2.5, 4.0))) + + def test_correct_embed_out(self): + n_harmonic_functions = 2 + x = torch.randn((1, 5)) + D = 5 * n_harmonic_functions * 2 # sin + cos + + embed_fun = HarmonicEmbedding( + n_harmonic_functions=n_harmonic_functions, append_input=False + ) + embed_out = embed_fun(x) + + self.assertEqual(embed_out.shape, (1, D)) + # Sum the squares of the respective frequencies + # cos^2(x) + sin^2(x) = 1 + sum_squares = embed_out[0, : D // 2] ** 2 + embed_out[0, D // 2 :] ** 2 + self.assertClose(sum_squares, torch.ones((D // 2))) + + # Test append input + embed_fun = HarmonicEmbedding( + n_harmonic_functions=n_harmonic_functions, append_input=True + ) + embed_out_appended_input = embed_fun(x) + self.assertClose( + embed_out_appended_input.shape, torch.tensor((1, D + x.shape[-1])) + ) + # Last plane in output is the input + self.assertClose(embed_out_appended_input[..., -x.shape[-1] :], x) + self.assertClose(embed_out_appended_input[..., : -x.shape[-1]], embed_out) + + def test_correct_embed_out_with_diag_cov(self): + n_harmonic_functions = 2 + x = torch.randn((1, 3)) + diag_cov = torch.randn((1, 3)) + D = 3 * n_harmonic_functions * 2 # sin + cos + + embed_fun = HarmonicEmbedding( + n_harmonic_functions=n_harmonic_functions, append_input=False + ) + embed_out = embed_fun(x, diag_cov=diag_cov) + + self.assertEqual(embed_out.shape, (1, D)) + + # Compute the scaling factor introduce in MipNerf + scale_factor = ( + -0.5 * diag_cov[..., None] * torch.pow(embed_fun._frequencies[None, :], 2) + ) + scale_factor = torch.exp(scale_factor).reshape(1, -1).tile((1, 2)) + # If we remove this scaling factor, we should go back to the + # classical harmonic embedding: + # Sum the squares of the respective frequencies + # cos^2(x) + sin^2(x) = 1 + embed_out_without_cov = embed_out / scale_factor + sum_squares = ( + embed_out_without_cov[0, : D // 2] ** 2 + + embed_out_without_cov[0, D // 2 :] ** 2 + ) + self.assertClose(sum_squares, torch.ones((D // 2))) + + # Test append input + embed_fun = HarmonicEmbedding( + n_harmonic_functions=n_harmonic_functions, append_input=True + ) + embed_out_appended_input = embed_fun(x, diag_cov=diag_cov) + self.assertClose( + embed_out_appended_input.shape, torch.tensor((1, D + x.shape[-1])) + ) + # Last plane in output is the input + self.assertClose(embed_out_appended_input[..., -x.shape[-1] :], x) + self.assertClose(embed_out_appended_input[..., : -x.shape[-1]], embed_out) + + def test_correct_behavior_between_ipe_and_its_estimation_from_harmonic_embedding( + self, + ): + """ + Check that the HarmonicEmbedding with integrated_position_encoding (IPE) set to + True is coherent with the HarmonicEmbedding. + + What is the idea behind this test? + + We wish to produce an IPE that is the expectation + of our lifted multivariate gaussian, modulated by the sine and cosine of + the coordinates. These expectation has a closed-form + (see equations 11, 12, 13, 14 of [1]). + + We sample N elements from the multivariate gaussian defined by its mean and covariance + and compute the HarmonicEmbedding. The expected value of those embeddings should be + equal to our IPE. + + Inspired from: + https://github.com/google/mipnerf/blob/84c969e0a623edd183b75693aed72a7e7c22902d/internal/mip_test.py#L359 + + References: + [1] `MIP-NeRF `_. + """ + num_dims = 3 + n_harmonic_functions = 6 + mean = torch.randn(num_dims) + diag_cov = torch.rand(num_dims) + + he_fun = HarmonicEmbedding( + n_harmonic_functions=n_harmonic_functions, logspace=True, append_input=False + ) + ipe_fun = HarmonicEmbedding( + n_harmonic_functions=n_harmonic_functions, + append_input=False, + ) + + embedding_ipe = ipe_fun(mean, diag_cov=diag_cov) + + rand_mvn = MultivariateNormal(mean, torch.eye(num_dims) * diag_cov) + + # Providing a large enough number of samples + # we should obtain an estimation close to our IPE + num_samples = 100000 + embedding_he = he_fun(rand_mvn.sample_n(num_samples)) + self.assertClose(embedding_he.mean(0), embedding_ipe, rtol=1e-2, atol=1e-2) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_io_gltf.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_io_gltf.py new file mode 100644 index 0000000000000000000000000000000000000000..c69fdfdb66d5e0df7d19c21df15cf1b36ed8afa5 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_io_gltf.py @@ -0,0 +1,385 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import os.path +import unittest +from math import radians + +import numpy as np +import torch +from PIL import Image +from pytorch3d.io import IO +from pytorch3d.io.experimental_gltf_io import _read_header, MeshGlbFormat +from pytorch3d.renderer import ( + AmbientLights, + BlendParams, + FoVPerspectiveCameras, + look_at_view_transform, + PointLights, + RasterizationSettings, + rotate_on_spot, +) +from pytorch3d.renderer.mesh import ( + HardPhongShader, + MeshRasterizer, + MeshRenderer, + TexturesVertex, +) +from pytorch3d.structures import Meshes +from pytorch3d.transforms import axis_angle_to_matrix +from pytorch3d.utils import ico_sphere +from pytorch3d.vis.texture_vis import texturesuv_image_PIL + +from .common_testing import get_pytorch3d_dir, get_tests_dir, TestCaseMixin + + +DATA_DIR = get_tests_dir() / "data" +TUTORIAL_DATA_DIR = get_pytorch3d_dir() / "docs/tutorials/data" +DEBUG = False + + +def _load(path, **kwargs) -> Meshes: + io = IO() + io.register_meshes_format(MeshGlbFormat()) + return io.load_mesh(path, **kwargs) + + +def _write(mesh, path, **kwargs) -> None: + io = IO() + io.register_meshes_format(MeshGlbFormat()) + io.save_mesh(mesh, path, **kwargs) + + with open(path, "rb") as f: + _, stored_length = _read_header(f) # pyre-ignore + assert stored_length == os.path.getsize(path) + + +def _render( + mesh: Meshes, + name: str, + dist: float = 3.0, + elev: float = 10.0, + azim: float = 0, + image_size: int = 256, + pan=None, + RT=None, + use_ambient=False, +): + device = mesh.device + if RT is not None: + R, T = RT + else: + R, T = look_at_view_transform(dist, elev, azim) + if pan is not None: + R, T = rotate_on_spot(R, T, pan) + cameras = FoVPerspectiveCameras(device=device, R=R, T=T) + + raster_settings = RasterizationSettings( + image_size=image_size, blur_radius=0.0, faces_per_pixel=1 + ) + + # Init shader settings + if use_ambient: + lights = AmbientLights(device=device) + else: + lights = PointLights(device=device) + lights.location = torch.tensor([0.0, 0.0, 2.0], device=device)[None] + + blend_params = BlendParams( + sigma=1e-1, + gamma=1e-4, + background_color=torch.tensor([1.0, 1.0, 1.0], device=device), + ) + # Init renderer + renderer = MeshRenderer( + rasterizer=MeshRasterizer(cameras=cameras, raster_settings=raster_settings), + shader=HardPhongShader( + device=device, lights=lights, cameras=cameras, blend_params=blend_params + ), + ) + + output = renderer(mesh) + + image = (output[0, ..., :3].cpu().numpy() * 255).astype(np.uint8) + + if DEBUG: + Image.fromarray(image).save(DATA_DIR / f"glb_{name}_.png") + + return image + + +class TestMeshGltfIO(TestCaseMixin, unittest.TestCase): + def test_load_apartment(self): + """ + This is the example habitat example scene from inside + http://dl.fbaipublicfiles.com/habitat/habitat-test-scenes.zip + + The scene is "already lit", i.e. the textures reflect the lighting + already, so we want to render them with full ambient light. + """ + + self.skipTest("Data not available") + + glb = DATA_DIR / "apartment_1.glb" + self.assertTrue(glb.is_file()) + device = torch.device("cuda:0") + mesh = _load(glb, device=device) + + if DEBUG: + texturesuv_image_PIL(mesh.textures).save(DATA_DIR / "out_apartment.png") + + for i in range(19): + # random locations in the apartment + eye = ((np.random.uniform(-6, 0.5), np.random.uniform(-8, 2), 0),) + at = ((np.random.uniform(-6, 0.5), np.random.uniform(-8, 2), 0),) + up = ((0, 0, -1),) + RT = look_at_view_transform(eye=eye, at=at, up=up) + _render(mesh, f"apartment_eau{i}", RT=RT, use_ambient=True) + + for i in range(12): + # panning around the inner room from one location + pan = axis_angle_to_matrix(torch.FloatTensor([0, radians(30 * i), 0])) + _render(mesh, f"apartment{i}", 1.0, -90, pan, use_ambient=True) + + def test_load_cow(self): + """ + Load the cow as converted to a single mesh in a glb file. + """ + glb = DATA_DIR / "cow.glb" + self.assertTrue(glb.is_file()) + device = torch.device("cuda:0") + mesh = _load(glb, device=device) + self.assertEqual(mesh.device, device) + + self.assertEqual(mesh.faces_packed().shape, (5856, 3)) + self.assertEqual(mesh.verts_packed().shape, (3225, 3)) + mesh_obj = _load(TUTORIAL_DATA_DIR / "cow_mesh/cow.obj") + self.assertClose(mesh.get_bounding_boxes().cpu(), mesh_obj.get_bounding_boxes()) + + self.assertClose( + mesh.textures.verts_uvs_padded().cpu(), mesh_obj.textures.verts_uvs_padded() + ) + + self.assertClose( + mesh.textures.faces_uvs_padded().cpu(), mesh_obj.textures.faces_uvs_padded() + ) + + self.assertClose( + mesh.textures.maps_padded().cpu(), mesh_obj.textures.maps_padded() + ) + + if DEBUG: + texturesuv_image_PIL(mesh.textures).save(DATA_DIR / "out_cow.png") + + image = _render(mesh, "cow", azim=4) + with Image.open(DATA_DIR / "glb_cow.png") as f: + expected = np.array(f) + + self.assertClose(image, expected) + + def test_save_cow(self): + """ + Save the cow mesh to a glb file + """ + # load cow mesh from a glb file + glb = DATA_DIR / "cow.glb" + self.assertTrue(glb.is_file()) + device = torch.device("cuda:0") + mesh = _load(glb, device=device) + + # save the mesh to a glb file + glb_reload = DATA_DIR / "cow_write.glb" + _write(mesh, glb_reload) + + # load again + self.assertTrue(glb_reload.is_file()) + device = torch.device("cuda:0") + mesh_reload = _load(glb_reload, device=device) + glb_reload.unlink() + + # assertions + self.assertEqual(mesh_reload.faces_packed().shape, (5856, 3)) + self.assertEqual(mesh_reload.verts_packed().shape, (3225, 3)) + self.assertClose( + mesh_reload.get_bounding_boxes().cpu(), mesh.get_bounding_boxes().cpu() + ) + + self.assertClose( + mesh_reload.textures.verts_uvs_padded().cpu(), + mesh.textures.verts_uvs_padded().cpu(), + ) + + self.assertClose( + mesh_reload.textures.faces_uvs_padded().cpu(), + mesh.textures.faces_uvs_padded().cpu(), + ) + + self.assertClose( + mesh_reload.textures.maps_padded().cpu(), mesh.textures.maps_padded().cpu() + ) + + def test_save_ico_sphere(self): + """ + save the ico_sphere mesh in a glb file + """ + ico_sphere_mesh = ico_sphere(level=3) + glb = DATA_DIR / "ico_sphere.glb" + _write(ico_sphere_mesh, glb) + + # reload the ico_sphere + device = torch.device("cuda:0") + mesh_reload = _load(glb, device=device, include_textures=False) + glb.unlink() + + self.assertClose( + ico_sphere_mesh.verts_padded().cpu(), + mesh_reload.verts_padded().cpu(), + ) + + self.assertClose( + ico_sphere_mesh.faces_padded().cpu(), + mesh_reload.faces_padded().cpu(), + ) + + def test_load_cow_no_texture(self): + """ + Load the cow as converted to a single mesh in a glb file. + """ + glb = DATA_DIR / "cow.glb" + self.assertTrue(glb.is_file()) + device = torch.device("cuda:0") + mesh = _load(glb, device=device, include_textures=False) + self.assertEqual(len(mesh), 1) + self.assertIsNone(mesh.textures) + + self.assertEqual(mesh.faces_packed().shape, (5856, 3)) + self.assertEqual(mesh.verts_packed().shape, (3225, 3)) + mesh_obj = _load(TUTORIAL_DATA_DIR / "cow_mesh/cow.obj") + self.assertClose(mesh.get_bounding_boxes().cpu(), mesh_obj.get_bounding_boxes()) + + mesh.textures = TexturesVertex(0.5 * torch.ones_like(mesh.verts_padded())) + + image = _render(mesh, "cow_gray") + + with Image.open(DATA_DIR / "glb_cow_gray.png") as f: + expected = np.array(f) + + self.assertClose(image, expected) + + def test_load_save_load_cow_texturesvertex(self): + """ + Load the cow as converted to a single mesh in a glb file and then save it to a glb file. + """ + + glb = DATA_DIR / "cow.glb" + self.assertTrue(glb.is_file()) + device = torch.device("cuda:0") + mesh = _load(glb, device=device, include_textures=False) + self.assertEqual(len(mesh), 1) + self.assertIsNone(mesh.textures) + + self.assertEqual(mesh.faces_packed().shape, (5856, 3)) + self.assertEqual(mesh.verts_packed().shape, (3225, 3)) + mesh_obj = _load(TUTORIAL_DATA_DIR / "cow_mesh/cow.obj") + self.assertClose(mesh.get_bounding_boxes().cpu(), mesh_obj.get_bounding_boxes()) + + mesh.textures = TexturesVertex(0.5 * torch.ones_like(mesh.verts_padded())) + + image = _render(mesh, "cow_gray") + + with Image.open(DATA_DIR / "glb_cow_gray.png") as f: + expected = np.array(f) + + self.assertClose(image, expected) + + # save the mesh to a glb file + glb = DATA_DIR / "cow_write_texturesvertex.glb" + _write(mesh, glb) + + # reload the mesh glb file saved in TexturesVertex format + self.assertTrue(glb.is_file()) + mesh_dash = _load(glb, device=device) + glb.unlink() + self.assertEqual(len(mesh_dash), 1) + + self.assertEqual(mesh_dash.faces_packed().shape, (5856, 3)) + self.assertEqual(mesh_dash.verts_packed().shape, (3225, 3)) + self.assertEqual(mesh_dash.textures.verts_features_list()[0].shape, (3225, 3)) + + # check the re-rendered image with expected + image_dash = _render(mesh, "cow_gray_texturesvertex") + self.assertClose(image_dash, expected) + + def test_save_toy(self): + """ + Construct a simple mesh and save it to a glb file in TexturesVertex mode. + """ + + example = {} + example["POSITION"] = torch.tensor( + [ + [ + [0.0, 0.0, 0.0], + [-1.0, 0.0, 0.0], + [-1.0, 0.0, 1.0], + [0.0, 0.0, 1.0], + [0.0, 1.0, 0.0], + [-1.0, 1.0, 0.0], + [-1.0, 1.0, 1.0], + [0.0, 1.0, 1.0], + ] + ] + ) + example["indices"] = torch.tensor( + [ + [ + [1, 4, 2], + [4, 3, 2], + [3, 7, 2], + [7, 6, 2], + [3, 4, 7], + [4, 8, 7], + [8, 5, 7], + [5, 6, 7], + [5, 2, 6], + [5, 1, 2], + [1, 5, 4], + [5, 8, 4], + ] + ] + ) + example["indices"] -= 1 + example["COLOR_0"] = torch.tensor( + [ + [ + [1.0, 0.0, 0.0], + [1.0, 0.0, 0.0], + [1.0, 0.0, 0.0], + [1.0, 0.0, 0.0], + [1.0, 0.0, 0.0], + [1.0, 0.0, 0.0], + [1.0, 0.0, 0.0], + [1.0, 0.0, 0.0], + ] + ] + ) + # example['prop'] = {'material': + # {'pbrMetallicRoughness': + # {'baseColorFactor': + # torch.tensor([[0.7, 0.7, 1, 0.5]]), + # 'metallicFactor': torch.tensor([1]), + # 'roughnessFactor': torch.tensor([0.1])}, + # 'alphaMode': 'BLEND', + # 'doubleSided': True}} + + texture = TexturesVertex(example["COLOR_0"]) + mesh = Meshes( + verts=example["POSITION"], faces=example["indices"], textures=texture + ) + + glb = DATA_DIR / "example_write_texturesvertex.glb" + _write(mesh, glb) + glb.unlink() diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_laplacian_matrices.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_laplacian_matrices.py new file mode 100644 index 0000000000000000000000000000000000000000..f04c6dfebf2ce6a0cebee01e4a7a1100974a33b8 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_laplacian_matrices.py @@ -0,0 +1,120 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import unittest + +import torch +from pytorch3d.ops import cot_laplacian, laplacian, norm_laplacian +from pytorch3d.structures.meshes import Meshes + +from .common_testing import get_random_cuda_device, TestCaseMixin + + +class TestLaplacianMatrices(TestCaseMixin, unittest.TestCase): + def setUp(self) -> None: + super().setUp() + torch.manual_seed(1) + + def init_mesh(self) -> Meshes: + V, F = 32, 64 + device = get_random_cuda_device() + # random vertices + verts = torch.rand((V, 3), dtype=torch.float32, device=device) + # random valid faces (no self circles, e.g. (v0, v0, v1)) + faces = torch.stack([torch.randperm(V) for f in range(F)], dim=0)[:, :3] + faces = faces.to(device=device) + return Meshes(verts=[verts], faces=[faces]) + + def test_laplacian(self): + mesh = self.init_mesh() + verts = mesh.verts_packed() + edges = mesh.edges_packed() + V, E = verts.shape[0], edges.shape[0] + + L = laplacian(verts, edges) + + Lnaive = torch.zeros((V, V), dtype=torch.float32, device=verts.device) + for e in range(E): + e0, e1 = edges[e] + Lnaive[e0, e1] = 1 + # symetric + Lnaive[e1, e0] = 1 + + deg = Lnaive.sum(1).view(-1, 1) + deg[deg > 0] = 1.0 / deg[deg > 0] + Lnaive = Lnaive * deg + diag = torch.eye(V, dtype=torch.float32, device=mesh.device) + Lnaive.masked_fill_(diag > 0, -1) + + self.assertClose(L.to_dense(), Lnaive) + + def test_cot_laplacian(self): + mesh = self.init_mesh() + verts = mesh.verts_packed() + faces = mesh.faces_packed() + V = verts.shape[0] + + eps = 1e-12 + + L, inv_areas = cot_laplacian(verts, faces, eps=eps) + + Lnaive = torch.zeros((V, V), dtype=torch.float32, device=verts.device) + inv_areas_naive = torch.zeros((V, 1), dtype=torch.float32, device=verts.device) + + for f in faces: + v0 = verts[f[0], :] + v1 = verts[f[1], :] + v2 = verts[f[2], :] + A = (v1 - v2).norm() + B = (v0 - v2).norm() + C = (v0 - v1).norm() + s = 0.5 * (A + B + C) + + face_area = (s * (s - A) * (s - B) * (s - C)).clamp_(min=1e-12).sqrt() + inv_areas_naive[f[0]] += face_area + inv_areas_naive[f[1]] += face_area + inv_areas_naive[f[2]] += face_area + + A2, B2, C2 = A * A, B * B, C * C + cota = (B2 + C2 - A2) / face_area / 4.0 + cotb = (A2 + C2 - B2) / face_area / 4.0 + cotc = (A2 + B2 - C2) / face_area / 4.0 + + Lnaive[f[1], f[2]] += cota + Lnaive[f[2], f[0]] += cotb + Lnaive[f[0], f[1]] += cotc + # symetric + Lnaive[f[2], f[1]] += cota + Lnaive[f[0], f[2]] += cotb + Lnaive[f[1], f[0]] += cotc + + idx = inv_areas_naive > 0 + inv_areas_naive[idx] = 1.0 / inv_areas_naive[idx] + + self.assertClose(inv_areas, inv_areas_naive) + self.assertClose(L.to_dense(), Lnaive) + + def test_norm_laplacian(self): + mesh = self.init_mesh() + verts = mesh.verts_packed() + edges = mesh.edges_packed() + V, E = verts.shape[0], edges.shape[0] + + eps = 1e-12 + + L = norm_laplacian(verts, edges, eps=eps) + + Lnaive = torch.zeros((V, V), dtype=torch.float32, device=verts.device) + for e in range(E): + e0, e1 = edges[e] + v0 = verts[e0] + v1 = verts[e1] + + w01 = 1.0 / ((v0 - v1).norm() + eps) + Lnaive[e0, e1] += w01 + Lnaive[e1, e0] += w01 + + self.assertClose(L.to_dense(), Lnaive) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_mesh_edge_loss.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_mesh_edge_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..c18cad3bc205e95de4b5a720c092e7612ca5b048 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_mesh_edge_loss.py @@ -0,0 +1,107 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import unittest + +import torch +from pytorch3d.loss import mesh_edge_loss +from pytorch3d.structures import Meshes + +from .common_testing import TestCaseMixin +from .test_sample_points_from_meshes import init_meshes + + +class TestMeshEdgeLoss(TestCaseMixin, unittest.TestCase): + def test_empty_meshes(self): + device = torch.device("cuda:0") + target_length = 0 + N = 10 + V = 32 + verts_list = [] + faces_list = [] + for _ in range(N): + vn = torch.randint(3, high=V, size=(1,))[0].item() + verts = torch.rand((vn, 3), dtype=torch.float32, device=device) + faces = torch.tensor([], dtype=torch.int64, device=device) + verts_list.append(verts) + faces_list.append(faces) + mesh = Meshes(verts=verts_list, faces=faces_list) + loss = mesh_edge_loss(mesh, target_length=target_length) + + self.assertClose(loss, torch.tensor([0.0], dtype=torch.float32, device=device)) + self.assertTrue(loss.requires_grad) + + @staticmethod + def mesh_edge_loss_naive(meshes, target_length: float = 0.0): + """ + Naive iterative implementation of mesh loss calculation. + """ + edges_packed = meshes.edges_packed() + verts_packed = meshes.verts_packed() + edge_to_mesh = meshes.edges_packed_to_mesh_idx() + N = len(meshes) + device = meshes.device + valid = meshes.valid + predlosses = torch.zeros((N,), dtype=torch.float32, device=device) + + for b in range(N): + if valid[b] == 0: + continue + mesh_edges = edges_packed[edge_to_mesh == b] + verts_edges = verts_packed[mesh_edges] + num_edges = mesh_edges.size(0) + for e in range(num_edges): + v0, v1 = verts_edges[e, 0], verts_edges[e, 1] + predlosses[b] += ((v0 - v1).norm(dim=0, p=2) - target_length) ** 2.0 + + if num_edges > 0: + predlosses[b] = predlosses[b] / num_edges + + return predlosses.mean() + + def test_mesh_edge_loss_output(self): + """ + Check outputs of tensorized and iterative implementations are the same. + """ + device = torch.device("cuda:0") + target_length = 0.5 + num_meshes = 10 + num_verts = 32 + num_faces = 64 + + verts_list = [] + faces_list = [] + valid = torch.randint(2, size=(num_meshes,)) + + for n in range(num_meshes): + if valid[n]: + vn = torch.randint(3, high=num_verts, size=(1,))[0].item() + fn = torch.randint(vn, high=num_faces, size=(1,))[0].item() + verts = torch.rand((vn, 3), dtype=torch.float32, device=device) + faces = torch.randint( + vn, size=(fn, 3), dtype=torch.int64, device=device + ) + else: + verts = torch.tensor([], dtype=torch.float32, device=device) + faces = torch.tensor([], dtype=torch.int64, device=device) + verts_list.append(verts) + faces_list.append(faces) + meshes = Meshes(verts=verts_list, faces=faces_list) + loss = mesh_edge_loss(meshes, target_length=target_length) + + predloss = TestMeshEdgeLoss.mesh_edge_loss_naive(meshes, target_length) + self.assertClose(loss, predloss) + + @staticmethod + def mesh_edge_loss(num_meshes: int = 10, max_v: int = 100, max_f: int = 300): + meshes = init_meshes(num_meshes, max_v, max_f, device="cuda:0") + torch.cuda.synchronize() + + def compute_loss(): + mesh_edge_loss(meshes, target_length=0.0) + torch.cuda.synchronize() + + return compute_loss diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_mesh_rendering_utils.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_mesh_rendering_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4c5b4f5ad5eda1f16d37ad2289fc194157f3ddc4 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_mesh_rendering_utils.py @@ -0,0 +1,27 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + + +import unittest + +import torch +from pytorch3d.renderer.mesh.utils import _clip_barycentric_coordinates + + +class TestMeshRenderingUtils(unittest.TestCase): + def test_bary_clip(self): + N = 10 + bary = torch.randn(size=(N, 3)) + # randomly make some values negative + bary[bary < 0.3] *= -1.0 + # randomly make some values be greater than 1 + bary[bary > 0.8] *= 2.0 + negative_mask = bary < 0.0 + positive_mask = bary > 1.0 + clipped = _clip_barycentric_coordinates(bary) + self.assertTrue(clipped[negative_mask].sum() == 0) + self.assertTrue(clipped[positive_mask].gt(1.0).sum() == 0) + self.assertTrue(torch.allclose(clipped.sum(dim=-1), torch.ones(N))) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_opengl_utils.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_opengl_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..65542f3914399fa45b61ea11571dce0c2e8c24bb --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_opengl_utils.py @@ -0,0 +1,396 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import ctypes +import os +import sys +import threading +import unittest + +import torch + +os.environ["PYOPENGL_PLATFORM"] = "egl" +import pycuda._driver # noqa +from OpenGL import GL as gl # noqa +from OpenGL.raw.EGL._errors import EGLError # noqa +from pytorch3d.renderer.opengl import _can_import_egl_and_pycuda # noqa +from pytorch3d.renderer.opengl.opengl_utils import ( # noqa + _define_egl_extension, + _egl_convert_to_int_array, + _get_cuda_device, + egl, + EGLContext, + global_device_context_store, +) + +from .common_testing import TestCaseMixin, usesOpengl # noqa + +MAX_EGL_HEIGHT = global_device_context_store.max_egl_height +MAX_EGL_WIDTH = global_device_context_store.max_egl_width + + +def _draw_square(r=1.0, g=0.0, b=1.0, **kwargs) -> torch.Tensor: + gl.glClear(gl.GL_COLOR_BUFFER_BIT) + gl.glColor3f(r, g, b) + x1, x2 = -0.5, 0.5 + y1, y2 = -0.5, 0.5 + gl.glRectf(x1, y1, x2, y2) + out_buffer = gl.glReadPixels( + 0, 0, MAX_EGL_WIDTH, MAX_EGL_HEIGHT, gl.GL_RGB, gl.GL_UNSIGNED_BYTE + ) + image = torch.frombuffer(out_buffer, dtype=torch.uint8).reshape( + MAX_EGL_HEIGHT, MAX_EGL_WIDTH, 3 + ) + return image + + +def _draw_squares_with_context( + cuda_device_id=0, result=None, thread_id=None, **kwargs +) -> None: + context = EGLContext(MAX_EGL_WIDTH, MAX_EGL_HEIGHT, cuda_device_id) + with context.active_and_locked(): + images = [] + for _ in range(3): + images.append(_draw_square(**kwargs).float()) + if result is not None and thread_id is not None: + egl_info = context.get_context_info() + data = {"egl": egl_info, "images": images} + result[thread_id] = data + + +def _draw_squares_with_context_store( + cuda_device_id=0, + result=None, + thread_id=None, + verbose=False, + **kwargs, +) -> None: + device = torch.device(f"cuda:{cuda_device_id}") + context = global_device_context_store.get_egl_context(device) + if verbose: + print(f"In thread {thread_id}, device {cuda_device_id}.") + with context.active_and_locked(): + images = [] + for _ in range(3): + images.append(_draw_square(**kwargs).float()) + if result is not None and thread_id is not None: + egl_info = context.get_context_info() + data = {"egl": egl_info, "images": images} + result[thread_id] = data + + +@usesOpengl +class TestDeviceContextStore(TestCaseMixin, unittest.TestCase): + def test_cuda_context(self): + cuda_context_1 = global_device_context_store.get_cuda_context( + device=torch.device("cuda:0") + ) + cuda_context_2 = global_device_context_store.get_cuda_context( + device=torch.device("cuda:0") + ) + cuda_context_3 = global_device_context_store.get_cuda_context( + device=torch.device("cuda:1") + ) + cuda_context_4 = global_device_context_store.get_cuda_context( + device=torch.device("cuda:1") + ) + self.assertIs(cuda_context_1, cuda_context_2) + self.assertIs(cuda_context_3, cuda_context_4) + self.assertIsNot(cuda_context_1, cuda_context_3) + + def test_egl_context(self): + egl_context_1 = global_device_context_store.get_egl_context( + torch.device("cuda:0") + ) + egl_context_2 = global_device_context_store.get_egl_context( + torch.device("cuda:0") + ) + egl_context_3 = global_device_context_store.get_egl_context( + torch.device("cuda:1") + ) + egl_context_4 = global_device_context_store.get_egl_context( + torch.device("cuda:1") + ) + self.assertIs(egl_context_1, egl_context_2) + self.assertIs(egl_context_3, egl_context_4) + self.assertIsNot(egl_context_1, egl_context_3) + + +@usesOpengl +class TestUtils(TestCaseMixin, unittest.TestCase): + def test_load_extensions(self): + # This should work + _define_egl_extension("eglGetPlatformDisplayEXT", egl.EGLDisplay) + + # And this shouldn't (wrong extension) + with self.assertRaisesRegex(RuntimeError, "Cannot find EGL extension"): + _define_egl_extension("eglFakeExtensionEXT", egl.EGLBoolean) + + def test_get_cuda_device(self): + # This should work + device = _get_cuda_device(0) + self.assertIsNotNone(device) + + with self.assertRaisesRegex(ValueError, "Device 10000 not available"): + _get_cuda_device(10000) + + def test_egl_convert_to_int_array(self): + egl_attributes = {egl.EGL_RED_SIZE: 8} + attribute_array = _egl_convert_to_int_array(egl_attributes) + self.assertEqual(attribute_array._type_, ctypes.c_int) + self.assertEqual(attribute_array._length_, 3) + self.assertEqual(attribute_array[0], egl.EGL_RED_SIZE) + self.assertEqual(attribute_array[1], 8) + self.assertEqual(attribute_array[2], egl.EGL_NONE) + + +@usesOpengl +class TestOpenGLSingleThreaded(TestCaseMixin, unittest.TestCase): + def test_draw_square(self): + context = EGLContext(width=MAX_EGL_WIDTH, height=MAX_EGL_HEIGHT) + with context.active_and_locked(): + rendering_result = _draw_square().float() + expected_result = torch.zeros( + (MAX_EGL_WIDTH, MAX_EGL_HEIGHT, 3), dtype=torch.float + ) + start_px = int(MAX_EGL_WIDTH / 4) + end_px = int(MAX_EGL_WIDTH * 3 / 4) + expected_result[start_px:end_px, start_px:end_px, 0] = 255.0 + expected_result[start_px:end_px, start_px:end_px, 2] = 255.0 + + self.assertTrue(torch.all(expected_result == rendering_result)) + + def test_render_two_squares(self): + # Check that drawing twice doesn't overwrite the initial buffer. + context = EGLContext(width=MAX_EGL_WIDTH, height=MAX_EGL_HEIGHT) + with context.active_and_locked(): + red_square = _draw_square(r=1.0, g=0.0, b=0.0) + blue_square = _draw_square(r=0.0, g=0.0, b=1.0) + + start_px = int(MAX_EGL_WIDTH / 4) + end_px = int(MAX_EGL_WIDTH * 3 / 4) + + self.assertTrue( + torch.all( + red_square[start_px:end_px, start_px:end_px] + == torch.tensor([255, 0, 0]) + ) + ) + self.assertTrue( + torch.all( + blue_square[start_px:end_px, start_px:end_px] + == torch.tensor([0, 0, 255]) + ) + ) + + +@usesOpengl +class TestOpenGLMultiThreaded(TestCaseMixin, unittest.TestCase): + def test_multiple_renders_single_gpu_single_context(self): + _draw_squares_with_context() + + def test_multiple_renders_single_gpu_context_store(self): + _draw_squares_with_context_store() + + def test_render_two_threads_single_gpu(self): + self._render_two_threads_single_gpu(_draw_squares_with_context) + + def test_render_two_threads_single_gpu_context_store(self): + self._render_two_threads_single_gpu(_draw_squares_with_context_store) + + def test_render_two_threads_two_gpus(self): + self._render_two_threads_two_gpus(_draw_squares_with_context) + + def test_render_two_threads_two_gpus_context_store(self): + self._render_two_threads_two_gpus(_draw_squares_with_context_store) + + def _render_two_threads_single_gpu(self, draw_fn): + result = [None] * 2 + thread1 = threading.Thread( + target=draw_fn, + kwargs={ + "cuda_device_id": 0, + "result": result, + "thread_id": 0, + "r": 1.0, + "g": 0.0, + "b": 0.0, + }, + ) + thread2 = threading.Thread( + target=draw_fn, + kwargs={ + "cuda_device_id": 0, + "result": result, + "thread_id": 1, + "r": 0.0, + "g": 1.0, + "b": 0.0, + }, + ) + + thread1.start() + thread2.start() + thread1.join() + thread2.join() + + start_px = int(MAX_EGL_WIDTH / 4) + end_px = int(MAX_EGL_WIDTH * 3 / 4) + red_squares = torch.stack(result[0]["images"], dim=0)[ + :, start_px:end_px, start_px:end_px + ] + green_squares = torch.stack(result[1]["images"], dim=0)[ + :, start_px:end_px, start_px:end_px + ] + self.assertTrue(torch.all(red_squares == torch.tensor([255.0, 0.0, 0.0]))) + self.assertTrue(torch.all(green_squares == torch.tensor([0.0, 255.0, 0.0]))) + + def _render_two_threads_two_gpus(self, draw_fn): + # Contrary to _render_two_threads_two_gpus, this renders in two separate threads + # but on a different GPU each. This means using different EGL contexts and is a + # much less risky endeavour. + result = [None] * 2 + thread1 = threading.Thread( + target=draw_fn, + kwargs={ + "cuda_device_id": 0, + "result": result, + "thread_id": 0, + "r": 1.0, + "g": 0.0, + "b": 0.0, + }, + ) + thread2 = threading.Thread( + target=draw_fn, + kwargs={ + "cuda_device_id": 1, + "result": result, + "thread_id": 1, + "r": 0.0, + "g": 1.0, + "b": 0.0, + }, + ) + thread1.start() + thread2.start() + thread1.join() + thread2.join() + self.assertNotEqual( + result[0]["egl"]["context"].address, result[1]["egl"]["context"].address + ) + + start_px = int(MAX_EGL_WIDTH / 4) + end_px = int(MAX_EGL_WIDTH * 3 / 4) + red_squares = torch.stack(result[0]["images"], dim=0)[ + :, start_px:end_px, start_px:end_px + ] + green_squares = torch.stack(result[1]["images"], dim=0)[ + :, start_px:end_px, start_px:end_px + ] + self.assertTrue(torch.all(red_squares == torch.tensor([255.0, 0.0, 0.0]))) + self.assertTrue(torch.all(green_squares == torch.tensor([0.0, 255.0, 0.0]))) + + def test_render_multi_thread_multi_gpu(self): + # Multiple threads using up multiple GPUs; more threads than GPUs. + # This is certainly not encouraged in practice, but shouldn't fail. Note that + # the context store will only allow one rendering at a time to occur on a + # single GPU, even across threads. + n_gpus = torch.cuda.device_count() + n_threads = 10 + kwargs = { + "r": 1.0, + "g": 0.0, + "b": 0.0, + "verbose": True, + } + + threads = [] + for thread_id in range(n_threads): + kwargs.update( + {"cuda_device_id": thread_id % n_gpus, "thread_id": thread_id} + ) + threads.append( + threading.Thread( + target=_draw_squares_with_context_store, kwargs=dict(kwargs) + ) + ) + + for thread in threads: + thread.start() + for thread in threads: + thread.join() + + +@usesOpengl +class TestOpenGLUtils(TestCaseMixin, unittest.TestCase): + @classmethod + def tearDownClass(cls): + global_device_context_store.set_context_data(torch.device("cuda:0"), None) + + def test_device_context_store(self): + # Most of DCS's functionality is tested in the tests above, test the remainder. + device = torch.device("cuda:0") + global_device_context_store.set_context_data(device, 123) + + self.assertEqual(global_device_context_store.get_context_data(device), 123) + + self.assertEqual( + global_device_context_store.get_context_data(torch.device("cuda:1")), None + ) + + # Check that contexts in store can be manually released (although that's a very + # bad idea! Don't do it manually!) + egl_ctx = global_device_context_store.get_egl_context(device) + cuda_ctx = global_device_context_store.get_cuda_context(device) + egl_ctx.release() + cuda_ctx.detach() + + # Reset the contexts (just for testing! never do this manually!). Then, check + # that first running DeviceContextStore.release() will cause subsequent releases + # to fail (because we already released all the contexts). + global_device_context_store._cuda_contexts = {} + global_device_context_store._egl_contexts = {} + + egl_ctx = global_device_context_store.get_egl_context(device) + cuda_ctx = global_device_context_store.get_cuda_context(device) + global_device_context_store.release() + with self.assertRaisesRegex(EGLError, "EGL_NOT_INITIALIZED"): + egl_ctx.release() + with self.assertRaisesRegex(pycuda._driver.LogicError, "cannot detach"): + cuda_ctx.detach() + + def test_no_egl_error(self): + # Remove EGL, import OpenGL with the wrong backend. This should make it + # impossible to import OpenGL.EGL. + del os.environ["PYOPENGL_PLATFORM"] + modules = list(sys.modules) + for m in modules: + if "OpenGL" in m: + del sys.modules[m] + import OpenGL.GL # noqa + + self.assertFalse(_can_import_egl_and_pycuda()) + + # Import OpenGL back with the right backend. This should get things on track. + modules = list(sys.modules) + for m in modules: + if "OpenGL" in m: + del sys.modules[m] + + os.environ["PYOPENGL_PLATFORM"] = "egl" + self.assertTrue(_can_import_egl_and_pycuda()) + + def test_egl_release_error(self): + # Creating two contexts on the same device will lead to trouble (that's one of + # the reasons behind DeviceContextStore). You can release one of them, + # but you cannot release the same EGL resources twice! + ctx1 = EGLContext(width=100, height=100) + ctx2 = EGLContext(width=100, height=100) + + ctx1.release() + with self.assertRaisesRegex(EGLError, "EGL_NOT_INITIALIZED"): + ctx2.release() diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_points_alignment.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_points_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..7086c9cf2a54f5685d2c9dbedbd51d76334f1813 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_points_alignment.py @@ -0,0 +1,687 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import unittest + +import numpy as np +import torch +from pytorch3d.ops import points_alignment +from pytorch3d.structures.pointclouds import Pointclouds +from pytorch3d.transforms import rotation_conversions + +from .common_testing import get_tests_dir, TestCaseMixin + + +def _apply_pcl_transformation(X, R, T, s=None): + """ + Apply a batch of similarity/rigid transformations, parametrized with + rotation `R`, translation `T` and scale `s`, to an input batch of + point clouds `X`. + """ + if isinstance(X, Pointclouds): + num_points = X.num_points_per_cloud() + X_t = X.points_padded() + else: + X_t = X + + if s is not None: + X_t = s[:, None, None] * X_t + + X_t = torch.bmm(X_t, R) + T[:, None, :] + + if isinstance(X, Pointclouds): + X_list = [x[:n_p] for x, n_p in zip(X_t, num_points)] + X_t = Pointclouds(X_list) + + return X_t + + +class TestICP(TestCaseMixin, unittest.TestCase): + def setUp(self) -> None: + super().setUp() + torch.manual_seed(42) + np.random.seed(42) + trimesh_results_path = get_tests_dir() / "data/icp_data.pth" + self.trimesh_results = torch.load(trimesh_results_path) + + @staticmethod + def iterative_closest_point( + batch_size=10, + n_points_X=100, + n_points_Y=100, + dim=3, + use_pointclouds=False, + estimate_scale=False, + ): + device = torch.device("cuda:0") + + # initialize a ground truth point cloud + X, Y = [ + TestCorrespondingPointsAlignment.init_point_cloud( + batch_size=batch_size, + n_points=n_points, + dim=dim, + device=device, + use_pointclouds=use_pointclouds, + random_pcl_size=True, + fix_seed=i, + ) + for i, n_points in enumerate((n_points_X, n_points_Y)) + ] + + torch.cuda.synchronize() + + def run_iterative_closest_point(): + points_alignment.iterative_closest_point( + X, + Y, + estimate_scale=estimate_scale, + allow_reflection=False, + verbose=False, + max_iterations=100, + relative_rmse_thr=1e-4, + ) + torch.cuda.synchronize() + + return run_iterative_closest_point + + def test_init_transformation(self, batch_size=10): + """ + First runs a full ICP on a random problem. Then takes a given point + in the history of ICP iteration transformations, initializes + a second run of ICP with this transformation and checks whether + both runs ended with the same solution. + """ + + device = torch.device("cuda:0") + + for dim in (2, 3, 11): + for n_points_X in (30, 100): + for n_points_Y in (30, 100): + # initialize ground truth point clouds + X, Y = [ + TestCorrespondingPointsAlignment.init_point_cloud( + batch_size=batch_size, + n_points=n_points, + dim=dim, + device=device, + use_pointclouds=False, + random_pcl_size=True, + ) + for n_points in (n_points_X, n_points_Y) + ] + + # run full icp + ( + converged, + _, + Xt, + (R, T, s), + t_hist, + ) = points_alignment.iterative_closest_point( + X, + Y, + estimate_scale=False, + allow_reflection=False, + verbose=False, + max_iterations=100, + ) + + # start from the solution after the third + # iteration of the previous ICP + t_init = t_hist[min(2, len(t_hist) - 1)] + + # rerun the ICP + ( + converged_init, + _, + Xt_init, + (R_init, T_init, s_init), + t_hist_init, + ) = points_alignment.iterative_closest_point( + X, + Y, + init_transform=t_init, + estimate_scale=False, + allow_reflection=False, + verbose=False, + max_iterations=100, + ) + + # compare transformations and obtained clouds + # check that both sets of transforms are the same + atol = 3e-5 + self.assertClose(R_init, R, atol=atol) + self.assertClose(T_init, T, atol=atol) + self.assertClose(s_init, s, atol=atol) + self.assertClose(Xt_init, Xt, atol=atol) + + def test_heterogeneous_inputs(self, batch_size=7): + """ + Tests whether we get the same result when running ICP on + a set of randomly-sized Pointclouds and on their padded versions. + """ + + torch.manual_seed(14) + device = torch.device("cuda:0") + + for estimate_scale in (True, False): + for max_n_points in (10, 30, 100): + # initialize ground truth point clouds + X_pcl, Y_pcl = [ + TestCorrespondingPointsAlignment.init_point_cloud( + batch_size=batch_size, + n_points=max_n_points, + dim=3, + device=device, + use_pointclouds=True, + random_pcl_size=True, + ) + for _ in range(2) + ] + + # get the padded versions and their num of points + X_padded = X_pcl.points_padded() + Y_padded = Y_pcl.points_padded() + n_points_X = X_pcl.num_points_per_cloud() + n_points_Y = Y_pcl.num_points_per_cloud() + + # run icp with Pointlouds inputs + ( + _, + _, + Xt_pcl, + (R_pcl, T_pcl, s_pcl), + _, + ) = points_alignment.iterative_closest_point( + X_pcl, + Y_pcl, + estimate_scale=estimate_scale, + allow_reflection=False, + verbose=False, + max_iterations=100, + ) + Xt_pcl = Xt_pcl.points_padded() + + # run icp with tensor inputs on each element + # of the batch separately + icp_results = [ + points_alignment.iterative_closest_point( + X_[None, :n_X, :], + Y_[None, :n_Y, :], + estimate_scale=estimate_scale, + allow_reflection=False, + verbose=False, + max_iterations=100, + ) + for X_, Y_, n_X, n_Y in zip( + X_padded, Y_padded, n_points_X, n_points_Y + ) + ] + + # parse out the transformation results + R, T, s = [ + torch.cat([x.RTs[i] for x in icp_results], dim=0) for i in range(3) + ] + + # check that both sets of transforms are the same + atol = 1e-5 + self.assertClose(R_pcl, R, atol=atol) + self.assertClose(T_pcl, T, atol=atol) + self.assertClose(s_pcl, s, atol=atol) + + # compare the transformed point clouds + for pcli in range(batch_size): + nX = n_points_X[pcli] + Xt_ = icp_results[pcli].Xt[0, :nX] + Xt_pcl_ = Xt_pcl[pcli][:nX] + self.assertClose(Xt_pcl_, Xt_, atol=atol) + + def test_compare_with_trimesh(self): + """ + Compares the outputs of `iterative_closest_point` with the results + of `trimesh.registration.icp` from the `trimesh` python package: + https://github.com/mikedh/trimesh + + We have run `trimesh.registration.icp` on several random problems + with different point cloud sizes. The results of trimesh, together with + the randomly generated input clouds are loaded in the constructor of + this class and this test compares the loaded results to our runs. + """ + for n_points_X in (10, 20, 50, 100): + for n_points_Y in (10, 20, 50, 100): + self._compare_with_trimesh(n_points_X=n_points_X, n_points_Y=n_points_Y) + + def _compare_with_trimesh( + self, n_points_X=100, n_points_Y=100, estimate_scale=False + ): + """ + Executes a single test for `iterative_closest_point` for a + specific setting of the inputs / outputs. Compares the result with + the result of the trimesh package on the same input data. + """ + + device = torch.device("cuda:0") + + # load the trimesh results and the initial point clouds for icp + key = (int(n_points_X), int(n_points_Y), int(estimate_scale)) + X, Y, R_trimesh, T_trimesh, s_trimesh = [ + x.to(device) for x in self.trimesh_results[key] + ] + + # run the icp algorithm + ( + converged, + _, + _, + (R_ours, T_ours, s_ours), + _, + ) = points_alignment.iterative_closest_point( + X, + Y, + estimate_scale=estimate_scale, + allow_reflection=False, + verbose=False, + max_iterations=100, + ) + + # check that we have the same transformation + # and that the icp converged + atol = 1e-5 + self.assertClose(R_ours, R_trimesh, atol=atol) + self.assertClose(T_ours, T_trimesh, atol=atol) + self.assertClose(s_ours, s_trimesh, atol=atol) + self.assertTrue(converged) + + +class TestCorrespondingPointsAlignment(TestCaseMixin, unittest.TestCase): + def setUp(self) -> None: + super().setUp() + torch.manual_seed(42) + np.random.seed(42) + + @staticmethod + def random_rotation(batch_size, dim, device=None): + """ + Generates a batch of random `dim`-dimensional rotation matrices. + """ + if dim == 3: + R = rotation_conversions.random_rotations(batch_size, device=device) + else: + # generate random rotation matrices with orthogonalization of + # random normal square matrices, followed by a transformation + # that ensures determinant(R)==1 + H = torch.randn(batch_size, dim, dim, dtype=torch.float32, device=device) + U, _, V = torch.svd(H) + E = torch.eye(dim, dtype=torch.float32, device=device)[None].repeat( + batch_size, 1, 1 + ) + E[:, -1, -1] = torch.det(torch.bmm(U, V.transpose(2, 1))) + R = torch.bmm(torch.bmm(U, E), V.transpose(2, 1)) + assert torch.allclose(torch.det(R), R.new_ones(batch_size), atol=1e-4) + + return R + + @staticmethod + def init_point_cloud( + batch_size=10, + n_points=1000, + dim=3, + device=None, + use_pointclouds=False, + random_pcl_size=True, + fix_seed=None, + ): + """ + Generate a batch of normally distributed point clouds. + """ + + if fix_seed is not None: + # make sure we always generate the same pointcloud + seed = torch.random.get_rng_state() + torch.manual_seed(fix_seed) + + if use_pointclouds: + assert dim == 3, "Pointclouds support only 3-dim points." + # generate a `batch_size` point clouds with number of points + # between 4 and `n_points` + if random_pcl_size: + n_points_per_batch = torch.randint( + low=4, + high=n_points, + size=(batch_size,), + device=device, + dtype=torch.int64, + ) + X_list = [ + torch.randn(int(n_pt), dim, device=device, dtype=torch.float32) + for n_pt in n_points_per_batch + ] + X = Pointclouds(X_list) + else: + X = torch.randn( + batch_size, n_points, dim, device=device, dtype=torch.float32 + ) + X = Pointclouds(list(X)) + else: + X = torch.randn( + batch_size, n_points, dim, device=device, dtype=torch.float32 + ) + + if fix_seed: + torch.random.set_rng_state(seed) + + return X + + @staticmethod + def generate_pcl_transformation( + batch_size=10, scale=False, reflect=False, dim=3, device=None + ): + """ + Generate a batch of random rigid/similarity transformations. + """ + R = TestCorrespondingPointsAlignment.random_rotation( + batch_size, dim, device=device + ) + T = torch.randn(batch_size, dim, dtype=torch.float32, device=device) + if scale: + s = torch.rand(batch_size, dtype=torch.float32, device=device) + 0.1 + else: + s = torch.ones(batch_size, dtype=torch.float32, device=device) + + return R, T, s + + @staticmethod + def generate_random_reflection(batch_size=10, dim=3, device=None): + """ + Generate a batch of reflection matrices of shape (batch_size, dim, dim), + where M_i is an identity matrix with one random entry on the + diagonal equal to -1. + """ + # randomly select one of the dimensions to reflect for each + # element in the batch + dim_to_reflect = torch.randint( + low=0, high=dim, size=(batch_size,), device=device, dtype=torch.int64 + ) + + # convert dim_to_reflect to a batch of reflection matrices M + M = torch.diag_embed( + ( + dim_to_reflect[:, None] + != torch.arange(dim, device=device, dtype=torch.float32) + ).float() + * 2 + - 1, + dim1=1, + dim2=2, + ) + + return M + + @staticmethod + def corresponding_points_alignment( + batch_size=10, + n_points=100, + dim=3, + use_pointclouds=False, + estimate_scale=False, + allow_reflection=False, + reflect=False, + random_weights=False, + ): + device = torch.device("cuda:0") + + # initialize a ground truth point cloud + X = TestCorrespondingPointsAlignment.init_point_cloud( + batch_size=batch_size, + n_points=n_points, + dim=dim, + device=device, + use_pointclouds=use_pointclouds, + random_pcl_size=True, + ) + + # generate the true transformation + R, T, s = TestCorrespondingPointsAlignment.generate_pcl_transformation( + batch_size=batch_size, + scale=estimate_scale, + reflect=reflect, + dim=dim, + device=device, + ) + + # apply the generated transformation to the generated + # point cloud X + X_t = _apply_pcl_transformation(X, R, T, s=s) + + weights = None + if random_weights: + template = X.points_padded() if use_pointclouds else X + weights = torch.rand_like(template[:, :, 0]) + weights = weights / weights.sum(dim=1, keepdim=True) + # zero out some weights as zero weights are a common use case + # this guarantees there are no zero weight + weights *= (weights * template.size()[1] > 0.3).to(weights) + if use_pointclouds: # convert to List[Tensor] + weights = [ + w[:npts] for w, npts in zip(weights, X.num_points_per_cloud()) + ] + + torch.cuda.synchronize() + + def run_corresponding_points_alignment(): + points_alignment.corresponding_points_alignment( + X, + X_t, + weights, + allow_reflection=allow_reflection, + estimate_scale=estimate_scale, + ) + torch.cuda.synchronize() + + return run_corresponding_points_alignment + + def test_corresponding_points_alignment(self, batch_size=10): + """ + Tests whether we can estimate a rigid/similarity motion between + a randomly initialized point cloud and its randomly transformed version. + + The tests are done for all possible combinations + of the following boolean flags: + - estimate_scale ... Estimate also a scaling component of + the transformation. + - reflect ... The ground truth orthonormal part of the generated + transformation is a reflection (det==-1). + - allow_reflection ... If True, the orthonormal matrix of the + estimated transformation is allowed to be + a reflection (det==-1). + - use_pointclouds ... If True, passes the Pointclouds objects + to corresponding_points_alignment. + """ + # run this for several different point cloud sizes + for n_points in (100, 3, 2, 1): + # run this for several different dimensionalities + for dim in range(2, 10): + # switches whether we should use the Pointclouds inputs + use_point_clouds_cases = ( + (True, False) if dim == 3 and n_points > 3 else (False,) + ) + for random_weights in (False, True): + for use_pointclouds in use_point_clouds_cases: + for estimate_scale in (False, True): + for reflect in (False, True): + for allow_reflection in (False, True): + self._test_single_corresponding_points_alignment( + batch_size=10, + n_points=n_points, + dim=dim, + use_pointclouds=use_pointclouds, + estimate_scale=estimate_scale, + reflect=reflect, + allow_reflection=allow_reflection, + random_weights=random_weights, + ) + + def _test_single_corresponding_points_alignment( + self, + batch_size=10, + n_points=100, + dim=3, + use_pointclouds=False, + estimate_scale=False, + reflect=False, + allow_reflection=False, + random_weights=False, + ): + """ + Executes a single test for `corresponding_points_alignment` for a + specific setting of the inputs / outputs. + """ + + device = torch.device("cuda:0") + + # initialize the a ground truth point cloud + X = TestCorrespondingPointsAlignment.init_point_cloud( + batch_size=batch_size, + n_points=n_points, + dim=dim, + device=device, + use_pointclouds=use_pointclouds, + random_pcl_size=True, + ) + + # generate the true transformation + R, T, s = TestCorrespondingPointsAlignment.generate_pcl_transformation( + batch_size=batch_size, + scale=estimate_scale, + reflect=reflect, + dim=dim, + device=device, + ) + + if reflect: + # generate random reflection M and apply to the rotations + M = TestCorrespondingPointsAlignment.generate_random_reflection( + batch_size=batch_size, dim=dim, device=device + ) + R = torch.bmm(M, R) + + weights = None + if random_weights: + template = X.points_padded() if use_pointclouds else X + weights = torch.rand_like(template[:, :, 0]) + weights = weights / weights.sum(dim=1, keepdim=True) + # zero out some weights as zero weights are a common use case + # this guarantees there are no zero weight + weights *= (weights * template.size()[1] > 0.3).to(weights) + if use_pointclouds: # convert to List[Tensor] + weights = [ + w[:npts] for w, npts in zip(weights, X.num_points_per_cloud()) + ] + + # apply the generated transformation to the generated + # point cloud X + X_t = _apply_pcl_transformation(X, R, T, s=s) + + # run the CorrespondingPointsAlignment algorithm + R_est, T_est, s_est = points_alignment.corresponding_points_alignment( + X, + X_t, + weights, + allow_reflection=allow_reflection, + estimate_scale=estimate_scale, + ) + + assert_error_message = ( + f"Corresponding_points_alignment assertion failure for " + f"n_points={n_points}, " + f"dim={dim}, " + f"use_pointclouds={use_pointclouds}, " + f"estimate_scale={estimate_scale}, " + f"reflect={reflect}, " + f"allow_reflection={allow_reflection}," + f"random_weights={random_weights}." + ) + + # if we test the weighted case, check that weights help with noise + if random_weights and not use_pointclouds and n_points >= (dim + 10): + # add noise to 20% points with smallest weight + X_noisy = X_t.clone() + _, mink_idx = torch.topk(-weights, int(n_points * 0.2), dim=1) + mink_idx = mink_idx[:, :, None].expand(-1, -1, X_t.shape[-1]) + X_noisy.scatter_add_( + 1, mink_idx, 0.3 * torch.randn_like(mink_idx, dtype=X_t.dtype) + ) + + def align_and_get_mse(weights_): + R_n, T_n, s_n = points_alignment.corresponding_points_alignment( + X_noisy, + X_t, + weights_, + allow_reflection=allow_reflection, + estimate_scale=estimate_scale, + ) + + X_t_est = _apply_pcl_transformation(X_noisy, R_n, T_n, s=s_n) + + return (((X_t_est - X_t) * weights[..., None]) ** 2).sum( + dim=(1, 2) + ) / weights.sum(dim=-1) + + # check that using weights leads to lower weighted_MSE(X_noisy, X_t) + self.assertTrue( + torch.all(align_and_get_mse(weights) <= align_and_get_mse(None)) + ) + + if reflect and not allow_reflection: + # check that all rotations have det=1 + self._assert_all_close( + torch.det(R_est), + R_est.new_ones(batch_size), + assert_error_message, + atol=2e-5, + ) + + else: + # mask out inputs with too few non-degenerate points for assertions + w = ( + torch.ones_like(R_est[:, 0, 0]) + if weights is None or n_points >= dim + 10 + else (weights > 0.0).all(dim=1).to(R_est) + ) + # check that the estimated tranformation is the same + # as the ground truth + if n_points >= (dim + 1): + # the checks on transforms apply only when + # the problem setup is unambiguous + msg = assert_error_message + self._assert_all_close(R_est, R, msg, w[:, None, None], atol=1e-5) + self._assert_all_close(T_est, T, msg, w[:, None]) + self._assert_all_close(s_est, s, msg, w) + + # check that the orthonormal part of the + # transformation has a correct determinant (+1/-1) + desired_det = R_est.new_ones(batch_size) + if reflect: + desired_det *= -1.0 + self._assert_all_close(torch.det(R_est), desired_det, msg, w, atol=2e-5) + + # check that the transformed point cloud + # X matches X_t + X_t_est = _apply_pcl_transformation(X, R_est, T_est, s=s_est) + self._assert_all_close( + X_t, X_t_est, assert_error_message, w[:, None, None], atol=2e-5 + ) + + def _assert_all_close(self, a_, b_, err_message, weights=None, atol=1e-6): + if isinstance(a_, Pointclouds): + a_ = a_.points_packed() + if isinstance(b_, Pointclouds): + b_ = b_.points_packed() + if weights is None: + self.assertClose(a_, b_, atol=atol, msg=err_message) + else: + self.assertClose(a_ * weights, b_ * weights, atol=atol, msg=err_message) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_raysampling.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_raysampling.py new file mode 100644 index 0000000000000000000000000000000000000000..3946a3514202a10572c53c3a5400afc20db6902e --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_raysampling.py @@ -0,0 +1,639 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import unittest +from typing import Callable + +import torch +from pytorch3d.common.compat import meshgrid_ij +from pytorch3d.ops import eyes +from pytorch3d.renderer import ( + MonteCarloRaysampler, + MultinomialRaysampler, + NDCGridRaysampler, + NDCMultinomialRaysampler, +) +from pytorch3d.renderer.cameras import ( + FoVOrthographicCameras, + FoVPerspectiveCameras, + OrthographicCameras, + PerspectiveCameras, +) +from pytorch3d.renderer.implicit.raysampling import ( + _jiggle_within_stratas, + _safe_multinomial, +) +from pytorch3d.renderer.implicit.utils import ( + ray_bundle_to_ray_points, + ray_bundle_variables_to_ray_points, +) +from pytorch3d.transforms import Rotate + +from .common_testing import TestCaseMixin +from .test_cameras import init_random_cameras + + +class TestNDCRaysamplerConvention(TestCaseMixin, unittest.TestCase): + def setUp(self) -> None: + torch.manual_seed(42) + + def test_ndc_convention( + self, + h=428, + w=760, + ): + device = torch.device("cuda") + + camera = init_random_cameras(PerspectiveCameras, 1, random_z=True).to(device) + + depth_map = torch.ones((1, 1, h, w)).to(device) + + xyz = ray_bundle_to_ray_points( + NDCGridRaysampler( + image_width=w, + image_height=h, + n_pts_per_ray=1, + min_depth=1.0, + max_depth=1.0, + )(camera)._replace(lengths=depth_map[:, 0, ..., None]) + ).view(1, -1, 3) + + # project pointcloud + xy = camera.transform_points(xyz)[:, :, :2].squeeze() + + xy_grid = self._get_ndc_grid(h, w, device) + + self.assertClose( + xy, + xy_grid, + atol=1e-4, + ) + + def _get_ndc_grid(self, h, w, device): + if w >= h: + range_x = w / h + range_y = 1.0 + else: + range_x = 1.0 + range_y = h / w + + half_pix_width = range_x / w + half_pix_height = range_y / h + + min_x = range_x - half_pix_width + max_x = -range_x + half_pix_width + min_y = range_y - half_pix_height + max_y = -range_y + half_pix_height + + y_grid, x_grid = meshgrid_ij( + torch.linspace(min_y, max_y, h, dtype=torch.float32), + torch.linspace(min_x, max_x, w, dtype=torch.float32), + ) + + x_points = x_grid.contiguous().view(-1).to(device) + y_points = y_grid.contiguous().view(-1).to(device) + xy = torch.stack((x_points, y_points), dim=1) + return xy + + +class TestRaysampling(TestCaseMixin, unittest.TestCase): + def setUp(self) -> None: + torch.manual_seed(42) + + @staticmethod + def raysampler( + raysampler_type, + camera_type, + n_pts_per_ray: int, + batch_size: int, + image_width: int, + image_height: int, + ) -> Callable[[], None]: + """ + Used for benchmarks. + """ + device = torch.device("cuda") + + # init raysamplers + raysampler = TestRaysampling.init_raysampler( + raysampler_type=raysampler_type, + min_x=-1.0, + max_x=1.0, + min_y=-1.0, + max_y=1.0, + image_width=image_width, + image_height=image_height, + min_depth=1.0, + max_depth=10.0, + n_pts_per_ray=n_pts_per_ray, + ).to(device) + + # init a batch of random cameras + cameras = init_random_cameras(camera_type, batch_size, random_z=True).to(device) + + def run_raysampler() -> None: + raysampler(cameras=cameras) + torch.cuda.synchronize() + + return run_raysampler + + @staticmethod + def init_raysampler( + raysampler_type, + min_x=-1.0, + max_x=1.0, + min_y=-1.0, + max_y=1.0, + image_width=10, + image_height=20, + min_depth=1.0, + max_depth=10.0, + n_pts_per_ray=10, + n_rays_total=None, + n_rays_per_image=None, + ): + raysampler_params = { + "min_x": min_x, + "max_x": max_x, + "min_y": min_y, + "max_y": max_y, + "n_pts_per_ray": n_pts_per_ray, + "min_depth": min_depth, + "max_depth": max_depth, + "n_rays_total": n_rays_total, + "n_rays_per_image": n_rays_per_image, + } + + if issubclass(raysampler_type, MultinomialRaysampler): + raysampler_params.update( + {"image_width": image_width, "image_height": image_height} + ) + elif issubclass(raysampler_type, MonteCarloRaysampler): + raysampler_params["n_rays_per_image"] = ( + image_width * image_height + if (n_rays_total is None) and (n_rays_per_image is None) + else n_rays_per_image + ) + else: + raise ValueError(str(raysampler_type)) + + if issubclass(raysampler_type, NDCMultinomialRaysampler): + # NDCGridRaysampler does not use min/max_x/y + for k in ("min_x", "max_x", "min_y", "max_y"): + del raysampler_params[k] + + # instantiate the raysampler + raysampler = raysampler_type(**raysampler_params) + + return raysampler + + def test_raysamplers( + self, + batch_size=25, + min_x=-1.0, + max_x=1.0, + min_y=-1.0, + max_y=1.0, + image_width=10, + image_height=20, + min_depth=1.0, + max_depth=10.0, + ): + """ + Tests the shapes and outputs of MC and GridRaysamplers for randomly + generated cameras and different numbers of points per ray. + """ + + device = torch.device("cuda") + + for n_pts_per_ray in (100, 1): + for raysampler_type in ( + MonteCarloRaysampler, + MultinomialRaysampler, + NDCMultinomialRaysampler, + ): + raysampler = TestRaysampling.init_raysampler( + raysampler_type=raysampler_type, + min_x=min_x, + max_x=max_x, + min_y=min_y, + max_y=max_y, + image_width=image_width, + image_height=image_height, + min_depth=min_depth, + max_depth=max_depth, + n_pts_per_ray=n_pts_per_ray, + ) + + if issubclass(raysampler_type, NDCMultinomialRaysampler): + # adjust the gt bounds for NDCGridRaysampler + if image_width >= image_height: + range_x = image_width / image_height + range_y = 1.0 + else: + range_x = 1.0 + range_y = image_height / image_width + + half_pix_width = range_x / image_width + half_pix_height = range_y / image_height + min_x_ = range_x - half_pix_width + max_x_ = -range_x + half_pix_width + min_y_ = range_y - half_pix_height + max_y_ = -range_y + half_pix_height + else: + min_x_ = min_x + max_x_ = max_x + min_y_ = min_y + max_y_ = max_y + + # carry out the test over several camera types + for cam_type in ( + FoVPerspectiveCameras, + FoVOrthographicCameras, + OrthographicCameras, + PerspectiveCameras, + ): + # init a batch of random cameras + cameras = init_random_cameras( + cam_type, batch_size, random_z=True + ).to(device) + + # call the raysampler + ray_bundle = raysampler(cameras=cameras) + + # check the shapes of the raysampler outputs + self._check_raysampler_output_shapes( + raysampler, + ray_bundle, + batch_size, + image_width, + image_height, + n_pts_per_ray, + ) + + # check the points sampled along each ray + self._check_raysampler_ray_points( + raysampler, + cameras, + ray_bundle, + min_x_, + max_x_, + min_y_, + max_y_, + image_width, + image_height, + min_depth, + max_depth, + ) + + # check the output direction vectors + self._check_raysampler_ray_directions( + cameras, raysampler, ray_bundle + ) + + def _check_grid_shape(self, grid, batch_size, spatial_size, n_pts_per_ray, dim): + """ + A helper for checking the desired size of a variable output by a raysampler. + """ + tgt_shape = [ + x for x in [batch_size, *spatial_size, n_pts_per_ray, dim] if x > 0 + ] + self.assertTrue(all(sz1 == sz2 for sz1, sz2 in zip(grid.shape, tgt_shape))) + + def _check_raysampler_output_shapes( + self, + raysampler, + ray_bundle, + batch_size, + image_width, + image_height, + n_pts_per_ray, + ): + """ + Checks the shapes of raysampler outputs. + """ + + if isinstance(raysampler, MultinomialRaysampler): + spatial_size = [image_height, image_width] + elif isinstance(raysampler, MonteCarloRaysampler): + spatial_size = [image_height * image_width] + else: + raise ValueError(str(type(raysampler))) + + self._check_grid_shape(ray_bundle.xys, batch_size, spatial_size, 0, 2) + self._check_grid_shape(ray_bundle.origins, batch_size, spatial_size, 0, 3) + self._check_grid_shape(ray_bundle.directions, batch_size, spatial_size, 0, 3) + self._check_grid_shape( + ray_bundle.lengths, batch_size, spatial_size, n_pts_per_ray, 0 + ) + + def _check_raysampler_ray_points( + self, + raysampler, + cameras, + ray_bundle, + min_x, + max_x, + min_y, + max_y, + image_width, + image_height, + min_depth, + max_depth, + ): + """ + Check rays_points_world and rays_zs outputs of raysamplers. + """ + + batch_size = cameras.R.shape[0] + + # convert to ray points + rays_points_world = ray_bundle_variables_to_ray_points( + ray_bundle.origins, ray_bundle.directions, ray_bundle.lengths + ) + n_pts_per_ray = rays_points_world.shape[-2] + + # check that the outputs if ray_bundle_variables_to_ray_points and + # ray_bundle_to_ray_points match + rays_points_world_ = ray_bundle_to_ray_points(ray_bundle) + self.assertClose(rays_points_world, rays_points_world_) + + # check that the depth of each ray point in camera coords + # matches the expected linearly-spaced depth + depth_expected = torch.linspace( + min_depth, + max_depth, + n_pts_per_ray, + dtype=torch.float32, + device=rays_points_world.device, + ) + ray_points_camera = ( + cameras.get_world_to_view_transform() + .transform_points(rays_points_world.view(batch_size, -1, 3)) + .view(batch_size, -1, n_pts_per_ray, 3) + ) + self.assertClose( + ray_points_camera[..., 2], + depth_expected[None, None, :].expand_as(ray_points_camera[..., 2]), + atol=1e-4, + ) + + # check also that rays_zs is consistent with depth_expected + self.assertClose( + ray_bundle.lengths.view(batch_size, -1, n_pts_per_ray), + depth_expected[None, None, :].expand_as(ray_points_camera[..., 2]), + atol=1e-6, + ) + + # project the world ray points back to screen space + ray_points_projected = cameras.transform_points( + rays_points_world.view(batch_size, -1, 3) + ).view(rays_points_world.shape) + + # check that ray_xy matches rays_points_projected xy + rays_xy_projected = ray_points_projected[..., :2].view( + batch_size, -1, n_pts_per_ray, 2 + ) + self.assertClose( + ray_bundle.xys.view(batch_size, -1, 1, 2).expand_as(rays_xy_projected), + rays_xy_projected, + atol=1e-4, + ) + + # check that projected world points' xy coordinates + # range correctly between [minx/y, max/y] + if isinstance(raysampler, MultinomialRaysampler): + # get the expected coordinates along each grid axis + ys, xs = [ + torch.linspace( + low, high, sz, dtype=torch.float32, device=rays_points_world.device + ) + for low, high, sz in ( + (min_y, max_y, image_height), + (min_x, max_x, image_width), + ) + ] + # compare expected xy with the output xy + for dim, gt_axis in zip( + (0, 1), (xs[None, None, :, None], ys[None, :, None, None]) + ): + self.assertClose( + ray_points_projected[..., dim], + gt_axis.expand_as(ray_points_projected[..., dim]), + atol=1e-4, + ) + + elif isinstance(raysampler, MonteCarloRaysampler): + # check that the randomly sampled locations + # are within the allowed bounds for both x and y axes + for dim, axis_bounds in zip((0, 1), ((min_x, max_x), (min_y, max_y))): + self.assertTrue( + ( + (ray_points_projected[..., dim] <= axis_bounds[1]) + & (ray_points_projected[..., dim] >= axis_bounds[0]) + ).all() + ) + + # also check that x,y along each ray is constant + if n_pts_per_ray > 1: + self.assertClose( + ray_points_projected[..., :2].std(dim=-2), + torch.zeros_like(ray_points_projected[..., 0, :2]), + atol=1e-5, + ) + + else: + raise ValueError(str(type(raysampler))) + + def _check_raysampler_ray_directions(self, cameras, raysampler, ray_bundle): + """ + Check the rays_directions_world output of raysamplers. + """ + + batch_size = cameras.R.shape[0] + n_pts_per_ray = ray_bundle.lengths.shape[-1] + spatial_size = ray_bundle.xys.shape[1:-1] + n_rays_per_image = spatial_size.numel() + + # obtain the ray points in world coords + rays_points_world = cameras.unproject_points( + torch.cat( + ( + ray_bundle.xys.view(batch_size, n_rays_per_image, 1, 2).expand( + batch_size, n_rays_per_image, n_pts_per_ray, 2 + ), + ray_bundle.lengths.view( + batch_size, n_rays_per_image, n_pts_per_ray, 1 + ), + ), + dim=-1, + ).view(batch_size, -1, 3) + ).view(batch_size, -1, n_pts_per_ray, 3) + + # reshape to common testing size + rays_directions_world_normed = torch.nn.functional.normalize( + ray_bundle.directions.view(batch_size, -1, 3), dim=-1 + ) + + # check that the l2-normed difference of all consecutive planes + # of points in world coords matches ray_directions_world + rays_directions_world_ = torch.nn.functional.normalize( + rays_points_world[:, :, -1:] - rays_points_world[:, :, :-1], dim=-1 + ) + self.assertClose( + rays_directions_world_normed[:, :, None].expand_as(rays_directions_world_), + rays_directions_world_, + atol=1e-4, + ) + + # check the ray directions rotated using camera rotation matrix + # match the ray directions of a camera with trivial extrinsics + cameras_trivial_extrinsic = cameras.clone() + cameras_trivial_extrinsic.R = eyes( + N=batch_size, dim=3, dtype=cameras.R.dtype, device=cameras.device + ) + cameras_trivial_extrinsic.T = torch.zeros_like(cameras.T) + + # make sure we get the same random rays in case we call the + # MonteCarloRaysampler twice below + with torch.random.fork_rng(devices=range(torch.cuda.device_count())): + torch.random.manual_seed(42) + ray_bundle_world_fix_seed = raysampler(cameras=cameras) + torch.random.manual_seed(42) + ray_bundle_camera_fix_seed = raysampler(cameras=cameras_trivial_extrinsic) + + rays_directions_camera_fix_seed_ = Rotate( + cameras.R, device=cameras.R.device + ).transform_points(ray_bundle_world_fix_seed.directions.view(batch_size, -1, 3)) + + self.assertClose( + rays_directions_camera_fix_seed_, + ray_bundle_camera_fix_seed.directions.view(batch_size, -1, 3), + atol=1e-5, + ) + + @unittest.skipIf( + torch.__version__[:4] == "1.5.", "non persistent buffer needs PyTorch 1.6" + ) + def test_load_state_different_resolution(self): + # check that we can load the state of one ray sampler into + # another with different image size. + module1 = NDCGridRaysampler( + image_width=20, + image_height=30, + n_pts_per_ray=40, + min_depth=1.2, + max_depth=2.3, + ) + module2 = NDCGridRaysampler( + image_width=22, + image_height=32, + n_pts_per_ray=42, + min_depth=1.2, + max_depth=2.3, + ) + state = module1.state_dict() + module2.load_state_dict(state) + + def test_jiggle(self): + # random data which is in ascending order along the last dimension + scale = 180 + data = scale * torch.cumsum(torch.rand(8, 3, 4, 20), dim=-1) + + out = _jiggle_within_stratas(data) + self.assertTupleEqual(out.shape, data.shape) + + # Check `out` is in ascending order + self.assertGreater((out[..., 1:] - out[..., :-1]).min(), 0) + + self.assertConstant(out[..., :-1] < data[..., 1:], True) + self.assertConstant(data[..., :-1] < out[..., 1:], True) + + jiggles = out - data + # jiggles is random between -scale/2 and scale/2 + self.assertLess(jiggles.min(), -0.4 * scale) + self.assertGreater(jiggles.min(), -0.5 * scale) + self.assertGreater(jiggles.max(), 0.4 * scale) + self.assertLess(jiggles.max(), 0.5 * scale) + + def test_safe_multinomial(self): + mask = [ + [1, 0, 0, 0, 0], + [1, 1, 0, 0, 0], + [1, 1, 1, 0, 0], + [1, 1, 1, 1, 0], + ] + tmask = torch.tensor(mask, dtype=torch.float32) + + for _ in range(5): + random_scalar = torch.rand(1) + samples = _safe_multinomial(tmask * random_scalar, 3) + self.assertTupleEqual(samples.shape, (4, 3)) + + # samples[0] is exactly determined + self.assertConstant(samples[0], 0) + + self.assertGreaterEqual(samples[1].min(), 0) + self.assertLessEqual(samples[1].max(), 1) + + # samples[2] is exactly determined + self.assertSetEqual(set(samples[2].tolist()), {0, 1, 2}) + + # samples[3] has enough sources, so must contain 3 distinct values. + self.assertLessEqual(samples[3].max(), 3) + self.assertEqual(len(set(samples[3].tolist())), 3) + + def test_heterogeneous_sampling(self, batch_size=8): + """ + Test that the output of heterogeneous sampling has the first dimension equal + to n_rays_total and second to 1 and that ray_bundle elements from different + sampled cameras are different and equal for same sampled cameras. + """ + cameras = init_random_cameras(PerspectiveCameras, batch_size, random_z=True) + for n_rays_total in [2, 3, 17, 21, 32]: + for cls in (MultinomialRaysampler, MonteCarloRaysampler): + with self.subTest(cls.__name__ + ", n_rays_total=" + str(n_rays_total)): + raysampler = self.init_raysampler( + cls, n_rays_total=n_rays_total, n_rays_per_image=None + ) + ray_bundle = raysampler(cameras) + + # test weather they are of the correct shape + for attr in ("origins", "directions", "lengths", "xys"): + tensor = getattr(ray_bundle, attr) + assert tensor.shape[:2] == torch.Size( + (n_rays_total, 1) + ), tensor.shape + + # if two camera ids are same than origins should also be the same + # directions and xys are always different and lengths equal + for i1, (origin1, dir1, len1, id1) in enumerate( + zip( + ray_bundle.origins, + ray_bundle.directions, + ray_bundle.lengths, + torch.repeat_interleave( + ray_bundle.camera_ids, ray_bundle.camera_counts + ), + ) + ): + for i2, (origin2, dir2, len2, id2) in enumerate( + zip( + ray_bundle.origins, + ray_bundle.directions, + ray_bundle.lengths, + torch.repeat_interleave( + ray_bundle.camera_ids, ray_bundle.camera_counts + ), + ) + ): + if i1 == i2: + continue + assert torch.allclose( + origin1, origin2, rtol=1e-4, atol=1e-4 + ) == (id1 == id2), (origin1, origin2, id1, id2) + assert not torch.allclose(dir1, dir2), (dir1, dir2) + self.assertClose(len1, len2) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_render_implicit.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_render_implicit.py new file mode 100644 index 0000000000000000000000000000000000000000..dd57abb9f4aef45a1ea890e0b7fda06cc222ccc3 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_render_implicit.py @@ -0,0 +1,415 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import unittest + +import numpy as np +import torch +from pytorch3d.renderer import ( + BlendParams, + EmissionAbsorptionRaymarcher, + ImplicitRenderer, + Materials, + MeshRasterizer, + MeshRenderer, + MonteCarloRaysampler, + MultinomialRaysampler, + NDCMultinomialRaysampler, + PointLights, + RasterizationSettings, + ray_bundle_to_ray_points, + RayBundle, + SoftPhongShader, + TexturesVertex, +) +from pytorch3d.structures import Meshes +from pytorch3d.utils import ico_sphere + +from .common_testing import TestCaseMixin +from .test_render_volumes import init_cameras + + +DEBUG = False +if DEBUG: + import os + import tempfile + + from PIL import Image + + +def spherical_volumetric_function( + ray_bundle: RayBundle, + sphere_centroid: torch.Tensor, + sphere_diameter: float, + **kwargs, +): + """ + Volumetric function of a simple RGB sphere with diameter `sphere_diameter` + and centroid `sphere_centroid`. + """ + # convert the ray bundle to world points + rays_points_world = ray_bundle_to_ray_points(ray_bundle) + batch_size = rays_points_world.shape[0] + + # surface_vectors = vectors from world coords towards the sphere centroid + surface_vectors = ( + rays_points_world.view(batch_size, -1, 3) - sphere_centroid[:, None] + ) + + # the squared distance of each ray point to the centroid of the sphere + surface_dist = ( + (surface_vectors**2) + .sum(-1, keepdim=True) + .view(*rays_points_world.shape[:-1], 1) + ) + + # set all ray densities within the sphere_diameter distance from the centroid to 1 + rays_densities = torch.sigmoid(-100.0 * (surface_dist - sphere_diameter**2)) + + # ray colors are proportional to the normalized surface_vectors + rays_features = ( + torch.nn.functional.normalize( + surface_vectors.view(rays_points_world.shape), dim=-1 + ) + * 0.5 + + 0.5 + ) + + return rays_densities, rays_features + + +class TestRenderImplicit(TestCaseMixin, unittest.TestCase): + def setUp(self) -> None: + super().setUp() + torch.manual_seed(42) + np.random.seed(42) + + @staticmethod + def renderer( + batch_size=10, + raymarcher_type=EmissionAbsorptionRaymarcher, + n_rays_per_image=10, + n_pts_per_ray=10, + sphere_diameter=0.75, + ): + # generate NDC camera extrinsics and intrinsics + cameras = init_cameras(batch_size, image_size=None, ndc=True) + + # get rand offset of the volume + sphere_centroid = torch.randn(batch_size, 3, device=cameras.device) * 0.1 + + # init the mc raysampler + raysampler = MonteCarloRaysampler( + min_x=-1.0, + max_x=1.0, + min_y=-1.0, + max_y=1.0, + n_rays_per_image=n_rays_per_image, + n_pts_per_ray=n_pts_per_ray, + min_depth=0.1, + max_depth=2.0, + ).to(cameras.device) + + # get the raymarcher + raymarcher = raymarcher_type() + + # get the implicit renderer + renderer = ImplicitRenderer(raysampler=raysampler, raymarcher=raymarcher) + + def run_renderer(): + renderer( + cameras=cameras, + volumetric_function=spherical_volumetric_function, + sphere_centroid=sphere_centroid, + sphere_diameter=sphere_diameter, + ) + + return run_renderer + + def test_input_types(self): + """ + Check that ValueErrors are thrown where expected. + """ + # check the constructor + for bad_raysampler in (None, 5, []): + for bad_raymarcher in (None, 5, []): + with self.assertRaises(ValueError): + ImplicitRenderer( + raysampler=bad_raysampler, raymarcher=bad_raymarcher + ) + + # init a trivial renderer + renderer = ImplicitRenderer( + raysampler=NDCMultinomialRaysampler( + image_width=100, + image_height=100, + n_pts_per_ray=10, + min_depth=0.1, + max_depth=1.0, + ), + raymarcher=EmissionAbsorptionRaymarcher(), + ) + + # get default cameras + cameras = init_cameras() + + for bad_volumetric_function in (None, 5, []): + with self.assertRaises(ValueError): + renderer(cameras=cameras, volumetric_function=bad_volumetric_function) + + def test_compare_with_meshes_renderer(self): + self._compare_with_meshes_renderer(image_size=(200, 100)) + self._compare_with_meshes_renderer(image_size=(100, 200)) + + def _compare_with_meshes_renderer( + self, image_size, batch_size=11, sphere_diameter=0.6 + ): + """ + Generate a spherical RGB volumetric function and its corresponding mesh + and check whether MeshesRenderer returns the same images as the + corresponding ImplicitRenderer. + """ + + # generate NDC camera extrinsics and intrinsics + cameras = init_cameras(batch_size, image_size=image_size, ndc=True) + + # get rand offset of the volume + sphere_centroid = torch.randn(batch_size, 3, device=cameras.device) * 0.1 + sphere_centroid.requires_grad = True + + # init the grid raysampler with the ndc grid + raysampler = NDCMultinomialRaysampler( + image_width=image_size[1], + image_height=image_size[0], + n_pts_per_ray=256, + min_depth=0.1, + max_depth=2.0, + ) + + # get the EA raymarcher + raymarcher = EmissionAbsorptionRaymarcher() + + # jitter the camera intrinsics a bit for each render + cameras_randomized = cameras.clone() + cameras_randomized.principal_point = ( + torch.randn_like(cameras.principal_point) * 0.3 + ) + cameras_randomized.focal_length = ( + cameras.focal_length + torch.randn_like(cameras.focal_length) * 0.2 + ) + + # the list of differentiable camera vars + cam_vars = ("R", "T", "focal_length", "principal_point") + # enable the gradient caching for the camera variables + for cam_var in cam_vars: + getattr(cameras_randomized, cam_var).requires_grad = True + + # get the implicit renderer + images_opacities = ImplicitRenderer( + raysampler=raysampler, raymarcher=raymarcher + )( + cameras=cameras_randomized, + volumetric_function=spherical_volumetric_function, + sphere_centroid=sphere_centroid, + sphere_diameter=sphere_diameter, + )[0] + + # check that the renderer does not erase gradients + loss = images_opacities.sum() + loss.backward() + for check_var in ( + *[getattr(cameras_randomized, cam_var) for cam_var in cam_vars], + sphere_centroid, + ): + self.assertIsNotNone(check_var.grad) + + # instantiate the corresponding spherical mesh + ico = ico_sphere(level=4, device=cameras.device).extend(batch_size) + verts = ( + torch.nn.functional.normalize(ico.verts_padded(), dim=-1) * sphere_diameter + + sphere_centroid[:, None] + ) + meshes = Meshes( + verts=verts, + faces=ico.faces_padded(), + textures=TexturesVertex( + verts_features=( + torch.nn.functional.normalize(verts, dim=-1) * 0.5 + 0.5 + ) + ), + ) + + # instantiate the corresponding mesh renderer + lights = PointLights(device=cameras.device, location=[[0.0, 0.0, 0.0]]) + renderer_textured = MeshRenderer( + rasterizer=MeshRasterizer( + cameras=cameras_randomized, + raster_settings=RasterizationSettings( + image_size=image_size, + blur_radius=1e-3, + faces_per_pixel=10, + z_clip_value=None, + perspective_correct=False, + ), + ), + shader=SoftPhongShader( + device=cameras.device, + cameras=cameras_randomized, + lights=lights, + materials=Materials( + ambient_color=((2.0, 2.0, 2.0),), + diffuse_color=((0.0, 0.0, 0.0),), + specular_color=((0.0, 0.0, 0.0),), + shininess=64, + device=cameras.device, + ), + blend_params=BlendParams( + sigma=1e-3, gamma=1e-4, background_color=(0.0, 0.0, 0.0) + ), + ), + ) + + # get the mesh render + images_opacities_meshes = renderer_textured( + meshes, cameras=cameras_randomized, lights=lights + ) + + if DEBUG: + outdir = tempfile.gettempdir() + "/test_implicit_vs_mesh_renderer" + os.makedirs(outdir, exist_ok=True) + + frames = [] + for image_opacity, image_opacity_mesh in zip( + images_opacities, images_opacities_meshes + ): + image, opacity = image_opacity.split([3, 1], dim=-1) + image_mesh, opacity_mesh = image_opacity_mesh.split([3, 1], dim=-1) + diff_image = ( + ((image - image_mesh) * 0.5 + 0.5) + .mean(dim=2, keepdim=True) + .repeat(1, 1, 3) + ) + image_pil = Image.fromarray( + ( + torch.cat( + ( + image, + image_mesh, + diff_image, + opacity.repeat(1, 1, 3), + opacity_mesh.repeat(1, 1, 3), + ), + dim=1, + ) + .detach() + .cpu() + .numpy() + * 255.0 + ).astype(np.uint8) + ) + frames.append(image_pil) + + # export gif + outfile = os.path.join(outdir, "implicit_vs_mesh_render.gif") + frames[0].save( + outfile, + save_all=True, + append_images=frames[1:], + duration=batch_size // 15, + loop=0, + ) + print(f"exported {outfile}") + + # export concatenated frames + outfile_cat = os.path.join(outdir, "implicit_vs_mesh_render.png") + Image.fromarray(np.concatenate([np.array(f) for f in frames], axis=0)).save( + outfile_cat + ) + print(f"exported {outfile_cat}") + + # compare the renders + diff = (images_opacities - images_opacities_meshes).abs().mean(dim=-1) + mu_diff = diff.mean(dim=(1, 2)) + std_diff = diff.std(dim=(1, 2)) + self.assertClose(mu_diff, torch.zeros_like(mu_diff), atol=5e-2) + self.assertClose(std_diff, torch.zeros_like(std_diff), atol=6e-2) + + def test_rotating_gif(self): + self._rotating_gif(image_size=(200, 100)) + self._rotating_gif(image_size=(100, 200)) + + def _rotating_gif(self, image_size, n_frames=50, fps=15, sphere_diameter=0.5): + """ + Render a gif animation of a rotating sphere (runs only if `DEBUG==True`). + """ + + if not DEBUG: + # do not run this if debug is False + return + + # generate camera extrinsics and intrinsics + cameras = init_cameras(n_frames, image_size=image_size) + + # init the grid raysampler + raysampler = MultinomialRaysampler( + min_x=0.5, + max_x=image_size[1] - 0.5, + min_y=0.5, + max_y=image_size[0] - 0.5, + image_width=image_size[1], + image_height=image_size[0], + n_pts_per_ray=256, + min_depth=0.1, + max_depth=2.0, + ) + + # get the EA raymarcher + raymarcher = EmissionAbsorptionRaymarcher() + + # get the implicit render + renderer = ImplicitRenderer(raysampler=raysampler, raymarcher=raymarcher) + + # get the (0) centroid of the sphere + sphere_centroid = torch.zeros(n_frames, 3, device=cameras.device) * 0.1 + + # run the renderer + images_opacities = renderer( + cameras=cameras, + volumetric_function=spherical_volumetric_function, + sphere_centroid=sphere_centroid, + sphere_diameter=sphere_diameter, + )[0] + + # split output to the alpha channel and rendered images + images, opacities = images_opacities[..., :3], images_opacities[..., 3] + + # export the gif + outdir = tempfile.gettempdir() + "/test_implicit_renderer_gifs" + os.makedirs(outdir, exist_ok=True) + frames = [] + for image, opacity in zip(images, opacities): + image_pil = Image.fromarray( + ( + torch.cat( + (image, opacity[..., None].clamp(0.0, 1.0).repeat(1, 1, 3)), + dim=1, + ) + .detach() + .cpu() + .numpy() + * 255.0 + ).astype(np.uint8) + ) + frames.append(image_pil) + outfile = os.path.join(outdir, "rotating_sphere.gif") + frames[0].save( + outfile, + save_all=True, + append_images=frames[1:], + duration=n_frames // fps, + loop=0, + ) + print(f"exported {outfile}") diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_render_meshes_clipped.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_render_meshes_clipped.py new file mode 100644 index 0000000000000000000000000000000000000000..b47eef56488b1104dcfb7727f6080359d5aef791 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_render_meshes_clipped.py @@ -0,0 +1,693 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + + +""" +Checks for mesh rasterization in the case where the camera enters the +inside of the mesh and some mesh faces are partially +behind the image plane. These faces are clipped and then rasterized. +See pytorch3d/renderer/mesh/clip.py for more details about the +clipping process. +""" + +import unittest + +import imageio +import numpy as np +import torch +from pytorch3d.io import save_obj +from pytorch3d.renderer.cameras import ( + FoVPerspectiveCameras, + look_at_view_transform, + PerspectiveCameras, +) +from pytorch3d.renderer.lighting import PointLights +from pytorch3d.renderer.mesh import ( + clip_faces, + ClipFrustum, + convert_clipped_rasterization_to_original_faces, + TexturesUV, +) +from pytorch3d.renderer.mesh.rasterize_meshes import _RasterizeFaceVerts +from pytorch3d.renderer.mesh.rasterizer import MeshRasterizer, RasterizationSettings +from pytorch3d.renderer.mesh.renderer import MeshRenderer +from pytorch3d.renderer.mesh.shader import SoftPhongShader +from pytorch3d.renderer.mesh.textures import TexturesVertex +from pytorch3d.structures.meshes import Meshes +from pytorch3d.utils import torus + +from .common_testing import get_tests_dir, load_rgb_image, TestCaseMixin + + +# If DEBUG=True, save out images generated in the tests for debugging. +# All saved images have prefix DEBUG_ +DEBUG = False +DATA_DIR = get_tests_dir() / "data" + + +class TestRenderMeshesClipping(TestCaseMixin, unittest.TestCase): + def load_cube_mesh_with_texture(self, device="cpu", with_grad: bool = False): + verts = torch.tensor( + [ + [-1, 1, 1], + [1, 1, 1], + [1, -1, 1], + [-1, -1, 1], + [-1, 1, -1], + [1, 1, -1], + [1, -1, -1], + [-1, -1, -1], + ], + device=device, + dtype=torch.float32, + requires_grad=with_grad, + ) + + # all faces correctly wound + faces = torch.tensor( + [ + [0, 1, 4], + [4, 1, 5], + [1, 2, 5], + [5, 2, 6], + [2, 7, 6], + [2, 3, 7], + [3, 4, 7], + [0, 4, 3], + [4, 5, 6], + [4, 6, 7], + ], + device=device, + dtype=torch.int64, + ) + + verts_uvs = torch.tensor( + [ + [ + [0, 1], + [1, 1], + [1, 0], + [0, 0], + [0.204, 0.743], + [0.781, 0.743], + [0.781, 0.154], + [0.204, 0.154], + ] + ], + device=device, + dtype=torch.float, + ) + texture_map = load_rgb_image("room.jpg", DATA_DIR).to(device) + textures = TexturesUV( + maps=[texture_map], faces_uvs=faces.unsqueeze(0), verts_uvs=verts_uvs + ) + mesh = Meshes([verts], [faces], textures=textures) + if with_grad: + return mesh, verts + return mesh + + def debug_cube_mesh_render(self): + """ + End-End debug run of rendering a cube mesh with texture + from decreasing camera distances. The camera starts + outside the cube and enters the inside of the cube. + """ + device = torch.device("cuda:0") + mesh = self.load_cube_mesh_with_texture(device) + raster_settings = RasterizationSettings( + image_size=512, + blur_radius=1e-8, + faces_per_pixel=5, + z_clip_value=1e-2, + perspective_correct=True, + bin_size=0, + ) + + # Only ambient, no diffuse or specular + lights = PointLights( + device=device, + ambient_color=((1.0, 1.0, 1.0),), + diffuse_color=((0.0, 0.0, 0.0),), + specular_color=((0.0, 0.0, 0.0),), + location=[[0.0, 0.0, -3.0]], + ) + + renderer = MeshRenderer( + rasterizer=MeshRasterizer(raster_settings=raster_settings), + shader=SoftPhongShader(device=device, lights=lights), + ) + + # Render the cube by decreasing the distance from the camera until + # the camera enters the cube. Check the output looks correct. + images_list = [] + dists = np.linspace(0.1, 2.5, 20)[::-1] + + for d in dists: + R, T = look_at_view_transform(d, 0, 0) + T[0, 1] -= 0.1 # move down in the y axis + cameras = FoVPerspectiveCameras(device=device, R=R, T=T, fov=90) + images = renderer(mesh, cameras=cameras) + rgb = images[0, ..., :3].cpu().detach() + im = (rgb.numpy() * 255).astype(np.uint8) + images_list.append(im) + + # Save a gif of the output - this should show + # the camera moving inside the cube. + if DEBUG: + gif_filename = ( + "room_original.gif" + if raster_settings.z_clip_value is None + else "room_clipped.gif" + ) + imageio.mimsave(DATA_DIR / gif_filename, images_list, fps=2) + save_obj( + f=DATA_DIR / "cube.obj", + verts=mesh.verts_packed().cpu(), + faces=mesh.faces_packed().cpu(), + ) + + @staticmethod + def clip_faces(meshes): + verts_packed = meshes.verts_packed() + faces_packed = meshes.faces_packed() + face_verts = verts_packed[faces_packed] + mesh_to_face_first_idx = meshes.mesh_to_faces_packed_first_idx() + num_faces_per_mesh = meshes.num_faces_per_mesh() + + frustum = ClipFrustum( + left=-1, + right=1, + top=-1, + bottom=1, + # In the unit tests for each case below the triangles are asummed + # to have already been projected onto the image plane. + perspective_correct=False, + z_clip_value=1e-2, + cull=True, # Cull to frustrum + ) + + clipped_faces = clip_faces( + face_verts, mesh_to_face_first_idx, num_faces_per_mesh, frustum + ) + return clipped_faces + + def test_grad(self): + """ + Check that gradient flow is unaffected when the camera is inside the mesh + """ + device = torch.device("cuda:0") + mesh, verts = self.load_cube_mesh_with_texture(device=device, with_grad=True) + raster_settings = RasterizationSettings( + image_size=512, + blur_radius=1e-5, + faces_per_pixel=5, + z_clip_value=1e-2, + perspective_correct=True, + bin_size=0, + ) + + renderer = MeshRenderer( + rasterizer=MeshRasterizer(raster_settings=raster_settings), + shader=SoftPhongShader(device=device), + ) + dist = 0.4 # Camera is inside the cube + R, T = look_at_view_transform(dist, 0, 0) + cameras = FoVPerspectiveCameras(device=device, R=R, T=T, fov=90) + images = renderer(mesh, cameras=cameras) + images.sum().backward() + + # Check gradients exist + self.assertIsNotNone(verts.grad) + + def test_case_1(self): + """ + Case 1: Single triangle fully in front of the image plane (z=0) + Triangle is not clipped or culled. The triangle is asummed to have + already been projected onto the image plane so no perspective + correction is needed. + """ + device = "cuda:0" + verts = torch.tensor( + [[0.0, 0.0, 1.0], [1.0, 0.0, 1.0], [0.0, 1.0, 1.0]], + dtype=torch.float32, + device=device, + ) + faces = torch.tensor( + [ + [0, 1, 2], + ], + dtype=torch.int64, + device=device, + ) + meshes = Meshes(verts=[verts], faces=[faces]) + clipped_faces = self.clip_faces(meshes) + + self.assertClose(clipped_faces.face_verts, verts[faces]) + self.assertEqual(clipped_faces.mesh_to_face_first_idx.item(), 0) + self.assertEqual(clipped_faces.num_faces_per_mesh.item(), 1) + self.assertIsNone(clipped_faces.faces_clipped_to_unclipped_idx) + self.assertIsNone(clipped_faces.faces_clipped_to_conversion_idx) + self.assertIsNone(clipped_faces.clipped_faces_neighbor_idx) + self.assertIsNone(clipped_faces.barycentric_conversion) + + def test_case_2(self): + """ + Case 2 triangles are fully behind the image plane (z=0) so are completely culled. + Test with a single triangle behind the image plane. + """ + + device = "cuda:0" + verts = torch.tensor( + [[-1.0, 0.0, -1.0], [0.0, 1.0, -1.0], [1.0, 0.0, -1.0]], + dtype=torch.float32, + device=device, + ) + faces = torch.tensor( + [ + [0, 1, 2], + ], + dtype=torch.int64, + device=device, + ) + meshes = Meshes(verts=[verts], faces=[faces]) + clipped_faces = self.clip_faces(meshes) + + zero_t = torch.zeros(size=(1,), dtype=torch.int64, device=device) + self.assertClose( + clipped_faces.face_verts, torch.empty(device=device, size=(0, 3, 3)) + ) + self.assertClose(clipped_faces.mesh_to_face_first_idx, zero_t) + self.assertClose(clipped_faces.num_faces_per_mesh, zero_t) + self.assertClose( + clipped_faces.faces_clipped_to_unclipped_idx, + torch.empty(device=device, dtype=torch.int64, size=(0,)), + ) + self.assertIsNone(clipped_faces.faces_clipped_to_conversion_idx) + self.assertIsNone(clipped_faces.clipped_faces_neighbor_idx) + self.assertIsNone(clipped_faces.barycentric_conversion) + + def test_case_3(self): + """ + Case 3 triangles have exactly two vertices behind the clipping plane (z=0) so are + clipped into a smaller triangle. + + Test with a single triangle parallel to the z axis which intersects with + the image plane. + """ + + device = "cuda:0" + verts = torch.tensor( + [[-1.0, 0.0, -1.0], [0.0, 0.0, 1.0], [1.0, 0.0, -1.0]], + dtype=torch.float32, + device=device, + ) + faces = torch.tensor( + [ + [0, 1, 2], + ], + dtype=torch.int64, + device=device, + ) + meshes = Meshes(verts=[verts], faces=[faces]) + clipped_faces = self.clip_faces(meshes) + + zero_t = torch.zeros(size=(1,), dtype=torch.int64, device=device) + clipped_face_verts = torch.tensor( + [ + [ + [0.4950, 0.0000, 0.0100], + [-0.4950, 0.0000, 0.0100], + [0.0000, 0.0000, 1.0000], + ] + ], + device=device, + dtype=torch.float32, + ) + + # barycentric_conversion[i, :, k] stores the barycentric weights + # in terms of the world coordinates of the original + # (big) triangle for the kth vertex in the clipped (small) triangle. + barycentric_conversion = torch.tensor( + [ + [ + [0.0000, 0.4950, 0.0000], + [0.5050, 0.5050, 1.0000], + [0.4950, 0.0000, 0.0000], + ] + ], + device=device, + dtype=torch.float32, + ) + + self.assertClose(clipped_faces.face_verts, clipped_face_verts) + self.assertEqual(clipped_faces.mesh_to_face_first_idx.item(), 0) + self.assertEqual(clipped_faces.num_faces_per_mesh.item(), 1) + self.assertClose(clipped_faces.faces_clipped_to_unclipped_idx, zero_t) + self.assertClose(clipped_faces.faces_clipped_to_conversion_idx, zero_t) + self.assertClose( + clipped_faces.clipped_faces_neighbor_idx, + zero_t - 1, # default is -1 + ) + self.assertClose(clipped_faces.barycentric_conversion, barycentric_conversion) + + def test_case_4(self): + """ + Case 4 triangles have exactly 1 vertex behind the clipping plane (z=0) so + are clipped into a smaller quadrilateral and then divided into two triangles. + + Test with a single triangle parallel to the z axis which intersects with + the image plane. + """ + + device = "cuda:0" + verts = torch.tensor( + [[0.0, 0.0, -1.0], [-1.0, 0.0, 1.0], [1.0, 0.0, 1.0]], + dtype=torch.float32, + device=device, + ) + faces = torch.tensor( + [ + [0, 1, 2], + ], + dtype=torch.int64, + device=device, + ) + meshes = Meshes(verts=[verts], faces=[faces]) + clipped_faces = self.clip_faces(meshes) + + clipped_face_verts = torch.tensor( + [ + # t1 + [ + [-0.5050, 0.0000, 0.0100], + [-1.0000, 0.0000, 1.0000], + [0.5050, 0.0000, 0.0100], + ], + # t2 + [ + [0.5050, 0.0000, 0.0100], + [-1.0000, 0.0000, 1.0000], + [1.0000, 0.0000, 1.0000], + ], + ], + device=device, + dtype=torch.float32, + ) + + barycentric_conversion = torch.tensor( + [ + [ + [0.4950, 0.0000, 0.4950], + [0.5050, 1.0000, 0.0000], + [0.0000, 0.0000, 0.5050], + ], + [ + [0.4950, 0.0000, 0.0000], + [0.0000, 1.0000, 0.0000], + [0.5050, 0.0000, 1.0000], + ], + ], + device=device, + dtype=torch.float32, + ) + + self.assertClose(clipped_faces.face_verts, clipped_face_verts) + self.assertEqual(clipped_faces.mesh_to_face_first_idx.item(), 0) + self.assertEqual( + clipped_faces.num_faces_per_mesh.item(), 2 + ) # now two faces instead of 1 + self.assertClose( + clipped_faces.faces_clipped_to_unclipped_idx, + torch.tensor([0, 0], device=device, dtype=torch.int64), + ) + # Neighboring face for each of the sub triangles e.g. for t1, neighbor is t2, + # and for t2, neighbor is t1 + self.assertClose( + clipped_faces.clipped_faces_neighbor_idx, + torch.tensor([1, 0], device=device, dtype=torch.int64), + ) + # barycentric_conversion is of shape (F_clipped) + self.assertEqual(clipped_faces.barycentric_conversion.shape[0], 2) + self.assertClose(clipped_faces.barycentric_conversion, barycentric_conversion) + # Index into barycentric_conversion for each clipped face. + self.assertClose( + clipped_faces.faces_clipped_to_conversion_idx, + torch.tensor([0, 1], device=device, dtype=torch.int64), + ) + + def test_mixture_of_cases(self): + """ + Test with two meshes composed of different cases to check all the + indexing is correct. + Case 4 faces are subdivided into two faces which are referred + to as t1 and t2. + """ + device = "cuda:0" + # fmt: off + verts = [ + torch.tensor( + [ + [-1.0, 0.0, -1.0], # noqa: E241, E201 + [ 0.0, 1.0, -1.0], # noqa: E241, E201 + [ 1.0, 0.0, -1.0], # noqa: E241, E201 + [ 0.0, -1.0, -1.0], # noqa: E241, E201 + [-1.0, 0.5, 0.5], # noqa: E241, E201 + [ 1.0, 1.0, 1.0], # noqa: E241, E201 + [ 0.0, -1.0, 1.0], # noqa: E241, E201 + [-1.0, 0.5, -0.5], # noqa: E241, E201 + [ 1.0, 1.0, -1.0], # noqa: E241, E201 + [-1.0, 0.0, 1.0], # noqa: E241, E201 + [ 0.0, 1.0, 1.0], # noqa: E241, E201 + [ 1.0, 0.0, 1.0], # noqa: E241, E201 + ], + dtype=torch.float32, + device=device, + ), + torch.tensor( + [ + [ 0.0, -1.0, -1.0], # noqa: E241, E201 + [-1.0, 0.5, 0.5], # noqa: E241, E201 + [ 1.0, 1.0, 1.0], # noqa: E241, E201 + ], + dtype=torch.float32, + device=device + ) + ] + faces = [ + torch.tensor( + [ + [0, 1, 2], # noqa: E241, E201 Case 2 fully clipped + [3, 4, 5], # noqa: E241, E201 Case 4 clipped and subdivided + [5, 4, 3], # noqa: E241, E201 Repeat of Case 4 + [6, 7, 8], # noqa: E241, E201 Case 3 clipped + [9, 10, 11], # noqa: E241, E201 Case 1 untouched + ], + dtype=torch.int64, + device=device, + ), + torch.tensor( + [ + [0, 1, 2], # noqa: E241, E201 Case 4 + ], + dtype=torch.int64, + device=device, + ), + ] + # fmt: on + meshes = Meshes(verts=verts, faces=faces) + + # Clip meshes + clipped_faces = self.clip_faces(meshes) + + # mesh 1: 4x faces (from Case 4) + 1 (from Case 3) + 1 (from Case 1) + # mesh 2: 2x faces (from Case 4) + self.assertEqual(clipped_faces.face_verts.shape[0], 6 + 2) + + # dummy idx type tensor to avoid having to initialize the dype/device each time + idx = torch.empty(size=(1,), dtype=torch.int64, device=device) + unclipped_idx = idx.new_tensor([1, 1, 2, 2, 3, 4, 5, 5]) + neighbors = idx.new_tensor([1, 0, 3, 2, -1, -1, 7, 6]) + first_idx = idx.new_tensor([0, 6]) + num_faces = idx.new_tensor([6, 2]) + + self.assertClose(clipped_faces.clipped_faces_neighbor_idx, neighbors) + self.assertClose(clipped_faces.faces_clipped_to_unclipped_idx, unclipped_idx) + self.assertClose(clipped_faces.mesh_to_face_first_idx, first_idx) + self.assertClose(clipped_faces.num_faces_per_mesh, num_faces) + + # faces_clipped_to_conversion_idx maps each output face to the + # corresponding row of the barycentric_conversion matrix. + # The barycentric_conversion matrix is composed by + # finding the barycentric conversion weights for case 3 faces + # case 4 (t1) faces and case 4 (t2) faces. These are then + # concatenated. Therefore case 3 faces will be the first rows of + # the barycentric_conversion matrix followed by t1 and then t2. + # Case type of all faces: [4 (t1), 4 (t2), 4 (t1), 4 (t2), 3, 1, 4 (t1), 4 (t2)] + # Based on this information we can calculate the indices into the + # barycentric conversion matrix. + bary_idx = idx.new_tensor([1, 4, 2, 5, 0, -1, 3, 6]) + self.assertClose(clipped_faces.faces_clipped_to_conversion_idx, bary_idx) + + def test_convert_clipped_to_unclipped_case_4(self): + """ + Test with a single case 4 triangle which is clipped into + a quadrilateral and subdivided. + """ + device = "cuda:0" + # fmt: off + verts = torch.tensor( + [ + [-1.0, 0.0, -1.0], # noqa: E241, E201 + [ 0.0, 1.0, -1.0], # noqa: E241, E201 + [ 1.0, 0.0, -1.0], # noqa: E241, E201 + [ 0.0, -1.0, -1.0], # noqa: E241, E201 + [-1.0, 0.5, 0.5], # noqa: E241, E201 + [ 1.0, 1.0, 1.0], # noqa: E241, E201 + [ 0.0, -1.0, 1.0], # noqa: E241, E201 + [-1.0, 0.5, -0.5], # noqa: E241, E201 + [ 1.0, 1.0, -1.0], # noqa: E241, E201 + [-1.0, 0.0, 1.0], # noqa: E241, E201 + [ 0.0, 1.0, 1.0], # noqa: E241, E201 + [ 1.0, 0.0, 1.0], # noqa: E241, E201 + ], + dtype=torch.float32, + device=device, + ) + faces = torch.tensor( + [ + [0, 1, 2], # noqa: E241, E201 Case 2 fully clipped + [3, 4, 5], # noqa: E241, E201 Case 4 clipped and subdivided + [5, 4, 3], # noqa: E241, E201 Repeat of Case 4 + [6, 7, 8], # noqa: E241, E201 Case 3 clipped + [9, 10, 11], # noqa: E241, E201 Case 1 untouched + ], + dtype=torch.int64, + device=device, + ) + # fmt: on + meshes = Meshes(verts=[verts], faces=[faces]) + + # Clip meshes + clipped_faces = self.clip_faces(meshes) + + # 4x faces (from Case 4) + 1 (from Case 3) + 1 (from Case 1) + self.assertEqual(clipped_faces.face_verts.shape[0], 6) + + image_size = (10, 10) + blur_radius = 0.05 + faces_per_pixel = 2 + perspective_correct = True + bin_size = 0 + max_faces_per_bin = 20 + clip_barycentric_coords = False + cull_backfaces = False + + # Rasterize clipped mesh + pix_to_face, zbuf, barycentric_coords, dists = _RasterizeFaceVerts.apply( + clipped_faces.face_verts, + clipped_faces.mesh_to_face_first_idx, + clipped_faces.num_faces_per_mesh, + clipped_faces.clipped_faces_neighbor_idx, + image_size, + blur_radius, + faces_per_pixel, + bin_size, + max_faces_per_bin, + perspective_correct, + clip_barycentric_coords, + cull_backfaces, + ) + + # Convert outputs so they are in terms of the unclipped mesh. + outputs = convert_clipped_rasterization_to_original_faces( + pix_to_face, + barycentric_coords, + clipped_faces, + ) + pix_to_face_unclipped, barycentric_coords_unclipped = outputs + + # In the clipped mesh there are more faces than in the unclipped mesh + self.assertTrue(pix_to_face.max() > pix_to_face_unclipped.max()) + # Unclipped pix_to_face indices must be in the limit of the number + # of faces in the unclipped mesh. + self.assertTrue(pix_to_face_unclipped.max() < faces.shape[0]) + + def test_case_4_no_duplicates(self): + """ + In the case of an simple mesh with one face that is cut by the image + plane into a quadrilateral, there shouldn't be duplicates indices of + the face in the pix_to_face output of rasterization. + """ + for device, bin_size in [("cpu", 0), ("cuda:0", 0), ("cuda:0", None)]: + verts = torch.tensor( + [[0.0, -10.0, 1.0], [-1.0, 2.0, -2.0], [1.0, 5.0, -10.0]], + dtype=torch.float32, + device=device, + ) + faces = torch.tensor( + [ + [0, 1, 2], + ], + dtype=torch.int64, + device=device, + ) + meshes = Meshes(verts=[verts], faces=[faces]) + k = 3 + settings = RasterizationSettings( + image_size=10, + blur_radius=0.05, + faces_per_pixel=k, + z_clip_value=1e-2, + perspective_correct=True, + cull_to_frustum=True, + bin_size=bin_size, + ) + + # The camera is positioned so that the image plane cuts + # the mesh face into a quadrilateral. + R, T = look_at_view_transform(0.2, 0, 0) + cameras = FoVPerspectiveCameras(device=device, R=R, T=T, fov=90) + rasterizer = MeshRasterizer(raster_settings=settings, cameras=cameras) + fragments = rasterizer(meshes) + + p2f = fragments.pix_to_face.reshape(-1, k) + unique_vals, idx_counts = p2f.unique(dim=0, return_counts=True) + # There is only one face in this mesh so if it hits a pixel + # it can only be at position k = 0 + # For any pixel, the values [0, 0, 1] for the top K faces cannot be possible + double_hit = torch.tensor([0, 0, -1], device=device) + check_double_hit = any(torch.allclose(i, double_hit) for i in unique_vals) + self.assertFalse(check_double_hit) + + def test_mesh_outside_frustrum(self): + """ + Test cases: + 1. Where the mesh is completely outside the view + frustrum so all faces are culled and z_clip_value = None. + 2. Where the part of the mesh is in the view frustrum but + the z_clip value = 5.0 so all the visible faces are behind + the clip plane so are culled instead of clipped. + """ + device = "cuda:0" + mesh1 = torus(20.0, 85.0, 32, 16, device=device) + mesh2 = torus(2.0, 3.0, 32, 16, device=device) + for mesh, z_clip in [(mesh1, None), (mesh2, 5.0)]: + tex = TexturesVertex(verts_features=torch.rand_like(mesh.verts_padded())) + mesh.textures = tex + raster_settings = RasterizationSettings( + image_size=512, cull_to_frustum=True, z_clip_value=z_clip + ) + R, T = look_at_view_transform(3.0, 0.0, 0.0) + cameras = PerspectiveCameras(device=device, R=R, T=T) + renderer = MeshRenderer( + rasterizer=MeshRasterizer( + cameras=cameras, raster_settings=raster_settings + ), + shader=SoftPhongShader(cameras=cameras, device=device), + ) + images = renderer(mesh) + # The image should be white. + self.assertClose(images[0, ..., :3], torch.ones_like(images[0, ..., :3])) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_render_multigpu.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_render_multigpu.py new file mode 100644 index 0000000000000000000000000000000000000000..2f2821058bc16a02a1185f9cfe46701064524e56 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_render_multigpu.py @@ -0,0 +1,234 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import unittest + +import torch +import torch.nn as nn +from pytorch3d.renderer import ( + AlphaCompositor, + BlendParams, + HardGouraudShader, + Materials, + MeshRasterizer, + MeshRenderer, + PointLights, + PointsRasterizationSettings, + PointsRasterizer, + PointsRenderer, + RasterizationSettings, + SoftPhongShader, + SplatterPhongShader, + TexturesVertex, +) +from pytorch3d.renderer.cameras import FoVPerspectiveCameras, look_at_view_transform +from pytorch3d.renderer.opengl import MeshRasterizerOpenGL +from pytorch3d.structures import Meshes, Pointclouds +from pytorch3d.utils.ico_sphere import ico_sphere + +from .common_testing import needs_multigpu, TestCaseMixin, usesOpengl + + +# Set the number of GPUS you want to test with +NUM_GPUS = 2 +GPU_LIST = [f"cuda:{idx}" for idx in range(NUM_GPUS)] +print("GPUs: %s" % ", ".join(GPU_LIST)) + + +class TestRenderMeshesMultiGPU(TestCaseMixin, unittest.TestCase): + def _check_mesh_renderer_props_on_device(self, renderer, device): + """ + Helper function to check that all the properties of the mesh + renderer have been moved to the correct device. + """ + # Cameras + self.assertEqual(renderer.rasterizer.cameras.device, device) + self.assertEqual(renderer.rasterizer.cameras.R.device, device) + self.assertEqual(renderer.rasterizer.cameras.T.device, device) + self.assertEqual(renderer.shader.cameras.device, device) + self.assertEqual(renderer.shader.cameras.R.device, device) + self.assertEqual(renderer.shader.cameras.T.device, device) + + # Lights and Materials + self.assertEqual(renderer.shader.lights.device, device) + self.assertEqual(renderer.shader.lights.ambient_color.device, device) + self.assertEqual(renderer.shader.materials.device, device) + self.assertEqual(renderer.shader.materials.ambient_color.device, device) + + def _mesh_renderer_to(self, rasterizer_class, shader_class): + """ + Test moving all the tensors in the mesh renderer to a new device. + """ + + device1 = torch.device("cuda:0") + + R, T = look_at_view_transform(1500, 0.0, 0.0) + + # Init shader settings + materials = Materials(device=device1) + lights = PointLights(device=device1) + lights.location = torch.tensor([0.0, 0.0, +1000.0], device=device1)[None] + + raster_settings = RasterizationSettings( + image_size=128, blur_radius=0.0, faces_per_pixel=1 + ) + cameras = FoVPerspectiveCameras( + device=device1, R=R, T=T, aspect_ratio=1.0, fov=60.0, zfar=100 + ) + rasterizer = rasterizer_class(cameras=cameras, raster_settings=raster_settings) + + blend_params = BlendParams( + 1e-4, + 1e-4, + background_color=torch.zeros(3, dtype=torch.float32, device=device1), + ) + + shader = shader_class( + lights=lights, + cameras=cameras, + materials=materials, + blend_params=blend_params, + ) + renderer = MeshRenderer(rasterizer=rasterizer, shader=shader) + + mesh = ico_sphere(2, device1) + verts_padded = mesh.verts_padded() + textures = TexturesVertex( + verts_features=torch.ones_like(verts_padded, device=device1) + ) + mesh.textures = textures + self._check_mesh_renderer_props_on_device(renderer, device1) + + # Test rendering on cpu + output_images = renderer(mesh) + self.assertEqual(output_images.device, device1) + + # Move renderer and mesh to another device and re render + # This also tests that background_color is correctly moved to + # the new device + device2 = torch.device("cuda:1") + renderer = renderer.to(device2) + mesh = mesh.to(device2) + self._check_mesh_renderer_props_on_device(renderer, device2) + output_images = renderer(mesh) + self.assertEqual(output_images.device, device2) + + @needs_multigpu + def test_mesh_renderer_to(self): + self._mesh_renderer_to(MeshRasterizer, SoftPhongShader) + + @usesOpengl + def test_mesh_renderer_opengl_to(self): + self._mesh_renderer_to(MeshRasterizerOpenGL, SplatterPhongShader) + + def _render_meshes(self, rasterizer_class, shader_class): + test = self + + class Model(nn.Module): + def __init__(self, device): + super(Model, self).__init__() + mesh = ico_sphere(3).to(device) + self.register_buffer("faces", mesh.faces_padded()) + self.renderer = self.init_render(device) + + def init_render(self, device): + cameras = FoVPerspectiveCameras().to(device) + raster_settings = RasterizationSettings( + image_size=128, blur_radius=0.0, faces_per_pixel=1 + ) + lights = PointLights( + ambient_color=((1.0, 1.0, 1.0),), + diffuse_color=((0, 0.0, 0),), + specular_color=((0.0, 0, 0),), + location=((0.0, 0.0, 1e5),), + ).to(device) + renderer = MeshRenderer( + rasterizer=rasterizer_class( + cameras=cameras, raster_settings=raster_settings + ), + shader=shader_class(cameras=cameras, lights=lights), + ) + return renderer + + def forward(self, verts, texs): + batch_size = verts.size(0) + self.renderer = self.renderer.to(verts.device) + tex = TexturesVertex(verts_features=texs) + faces = self.faces.expand(batch_size, -1, -1).to(verts.device) + mesh = Meshes(verts, faces, tex).to(verts.device) + + test._check_mesh_renderer_props_on_device(self.renderer, verts.device) + img_render = self.renderer(mesh) + return img_render[:, :, :, :3] + + # Make sure we use all GPUs in GPU_LIST by making the batch size 4 x GPU count. + verts = ico_sphere(3).verts_padded().expand(len(GPU_LIST) * 4, 642, 3) + texs = verts.new_ones(verts.shape) + model = Model(device=GPU_LIST[0]) + model = nn.DataParallel(model, device_ids=GPU_LIST) + + # Test a few iterations + for _ in range(100): + model(verts, texs) + + @needs_multigpu + def test_render_meshes(self): + self._render_meshes(MeshRasterizer, HardGouraudShader) + + # @unittest.skip("Multi-GPU OpenGL training is currently not supported.") + @usesOpengl + def test_render_meshes_opengl(self): + self._render_meshes(MeshRasterizerOpenGL, SplatterPhongShader) + + +class TestRenderPointsMultiGPU(TestCaseMixin, unittest.TestCase): + def _check_points_renderer_props_on_device(self, renderer, device): + """ + Helper function to check that all the properties have + been moved to the correct device. + """ + # Cameras + self.assertEqual(renderer.rasterizer.cameras.device, device) + self.assertEqual(renderer.rasterizer.cameras.R.device, device) + self.assertEqual(renderer.rasterizer.cameras.T.device, device) + + def test_points_renderer_to(self): + """ + Test moving all the tensors in the points renderer to a new device. + """ + + device1 = torch.device("cpu") + + R, T = look_at_view_transform(1500, 0.0, 0.0) + + raster_settings = PointsRasterizationSettings( + image_size=256, radius=0.001, points_per_pixel=1 + ) + cameras = FoVPerspectiveCameras( + device=device1, R=R, T=T, aspect_ratio=1.0, fov=60.0, zfar=100 + ) + rasterizer = PointsRasterizer(cameras=cameras, raster_settings=raster_settings) + + renderer = PointsRenderer(rasterizer=rasterizer, compositor=AlphaCompositor()) + + mesh = ico_sphere(2, device1) + verts_padded = mesh.verts_padded() + pointclouds = Pointclouds( + points=verts_padded, features=torch.randn_like(verts_padded) + ) + self._check_points_renderer_props_on_device(renderer, device1) + + # Test rendering on cpu + output_images = renderer(pointclouds) + self.assertEqual(output_images.device, device1) + + # Move renderer and pointclouds to another device and re render + device2 = torch.device("cuda:0") + renderer = renderer.to(device2) + pointclouds = pointclouds.to(device2) + self._check_points_renderer_props_on_device(renderer, device2) + output_images = renderer(pointclouds) + self.assertEqual(output_images.device, device2) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_render_volumes.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_render_volumes.py new file mode 100644 index 0000000000000000000000000000000000000000..67660ede5a2dfd6400d0fb92cd69e9df6ba239df --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_render_volumes.py @@ -0,0 +1,716 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import unittest +from typing import Optional, Tuple + +import numpy as np +import torch +from pytorch3d.ops import knn_points +from pytorch3d.renderer import ( + AbsorptionOnlyRaymarcher, + AlphaCompositor, + EmissionAbsorptionRaymarcher, + MonteCarloRaysampler, + MultinomialRaysampler, + NDCMultinomialRaysampler, + PerspectiveCameras, + PointsRasterizationSettings, + PointsRasterizer, + PointsRenderer, + RayBundle, + VolumeRenderer, + VolumeSampler, +) +from pytorch3d.renderer.implicit.utils import _validate_ray_bundle_variables +from pytorch3d.structures import Pointclouds, Volumes + +from .common_testing import TestCaseMixin +from .test_points_to_volumes import init_uniform_y_rotations + + +DEBUG = False +if DEBUG: + import os + import tempfile + + from PIL import Image + + +ZERO_TRANSLATION = torch.zeros(1, 3) + + +def init_boundary_volume( + batch_size: int, + volume_size: Tuple[int, int, int], + border_offset: int = 2, + shape: str = "cube", + volume_translation: torch.Tensor = ZERO_TRANSLATION, +): + """ + Generate a volume with sides colored with distinct colors. + """ + + device = torch.device("cuda") + + # first center the volume for the purpose of generating the canonical shape + volume_translation_tmp = (0.0, 0.0, 0.0) + + # set the voxel size to 1 / (volume_size-1) + volume_voxel_size = 1 / (volume_size[0] - 1.0) + + # colors of the sides of the cube + clr_sides = torch.tensor( + [ + [1.0, 1.0, 1.0], + [1.0, 0.0, 0.0], + [1.0, 0.0, 1.0], + [1.0, 1.0, 0.0], + [0.0, 1.0, 0.0], + [0.0, 1.0, 1.0], + ], + dtype=torch.float32, + device=device, + ) + + # get the coord grid of the volume + coord_grid = Volumes( + densities=torch.zeros(1, 1, *volume_size, device=device), + voxel_size=volume_voxel_size, + volume_translation=volume_translation_tmp, + ).get_coord_grid()[0] + + # extract the boundary points and their colors of the cube + if shape == "cube": + boundary_points, boundary_colors = [], [] + for side, clr_side in enumerate(clr_sides): + first = side % 2 + dim = side // 2 + slices = [slice(border_offset, -border_offset, 1)] * 3 + slices[dim] = int(border_offset * (2 * first - 1)) + slices.append(slice(0, 3, 1)) + boundary_points_ = coord_grid[slices].reshape(-1, 3) + boundary_points.append(boundary_points_) + boundary_colors.append(clr_side[None].expand_as(boundary_points_)) + # set the internal part of the volume to be completely opaque + volume_densities = torch.zeros(*volume_size, device=device) + volume_densities[[slice(border_offset, -border_offset, 1)] * 3] = 1.0 + boundary_points, boundary_colors = [ + torch.cat(p, dim=0) for p in [boundary_points, boundary_colors] + ] + # color the volume voxels with the nearest boundary points' color + _, idx, _ = knn_points( + coord_grid.view(1, -1, 3), boundary_points.view(1, -1, 3) + ) + volume_colors = ( + boundary_colors[idx.view(-1)].view(*volume_size, 3).permute(3, 0, 1, 2) + ) + + elif shape == "sphere": + # set all voxels within a certain distance from the origin to be opaque + volume_densities = ( + coord_grid.norm(dim=-1) + <= 0.5 * volume_voxel_size * (volume_size[0] - border_offset) + ).float() + # color each voxel with the standrd spherical color + volume_colors = ( + (torch.nn.functional.normalize(coord_grid, dim=-1) + 1.0) * 0.5 + ).permute(3, 0, 1, 2) + + else: + raise ValueError(shape) + + volume_voxel_size = torch.ones((batch_size, 1), device=device) * volume_voxel_size + volume_translation = volume_translation.expand(batch_size, 3) + volumes = Volumes( + densities=volume_densities[None, None].expand(batch_size, 1, *volume_size), + features=volume_colors[None].expand(batch_size, 3, *volume_size), + voxel_size=volume_voxel_size, + volume_translation=volume_translation, + ) + + return volumes, volume_voxel_size, volume_translation + + +def init_cameras( + batch_size: int = 10, + image_size: Optional[Tuple[int, int]] = (50, 50), + ndc: bool = False, +): + """ + Initialize a batch of cameras whose extrinsics rotate the cameras around + the world's y axis. + Depending on whether we want an NDC-space (`ndc==True`) or a screen-space camera, + the camera's focal length and principal point are initialized accordingly: + For `ndc==False`, p0=focal_length=image_size/2. + For `ndc==True`, focal_length=1.0, p0 = 0.0. + The the z-coordinate of the translation vector of each camera is fixed to 1.5. + """ + device = torch.device("cuda:0") + + # trivial rotations + R = init_uniform_y_rotations(batch_size=batch_size, device=device) + + # move camera 1.5 m away from the scene center + T = torch.zeros((batch_size, 3), device=device) + T[:, 2] = 1.5 + + if ndc: + p0 = torch.zeros(batch_size, 2, device=device) + focal = torch.ones(batch_size, device=device) + else: + p0 = torch.ones(batch_size, 2, device=device) + p0[:, 0] *= image_size[1] * 0.5 + p0[:, 1] *= image_size[0] * 0.5 + focal = max(*image_size) * torch.ones(batch_size, device=device) + + # convert to a Camera object + cameras = PerspectiveCameras(focal, p0, R=R, T=T, device=device) + return cameras + + +class TestRenderVolumes(TestCaseMixin, unittest.TestCase): + def setUp(self) -> None: + super().setUp() + torch.manual_seed(42) + np.random.seed(42) + + @staticmethod + def renderer( + volume_size=(25, 25, 25), + batch_size=10, + shape="sphere", + raymarcher_type=EmissionAbsorptionRaymarcher, + n_rays_per_image=10, + n_pts_per_ray=10, + ): + # get the volumes + volumes = init_boundary_volume( + volume_size=volume_size, batch_size=batch_size, shape=shape + )[0] + + # init the mc raysampler + raysampler = MonteCarloRaysampler( + min_x=-1.0, + max_x=1.0, + min_y=-1.0, + max_y=1.0, + n_rays_per_image=n_rays_per_image, + n_pts_per_ray=n_pts_per_ray, + min_depth=0.1, + max_depth=2.0, + ).to(volumes.device) + + # get the raymarcher + raymarcher = raymarcher_type() + + renderer = VolumeRenderer( + raysampler=raysampler, raymarcher=raymarcher, sample_mode="bilinear" + ) + + # generate NDC camera extrinsics and intrinsics + cameras = init_cameras(batch_size, image_size=None, ndc=True) + + def run_renderer(): + renderer(cameras=cameras, volumes=volumes) + + return run_renderer + + def test_input_types(self, batch_size: int = 10): + """ + Check that ValueErrors are thrown where expected. + """ + # check the constructor + for bad_raysampler in (None, 5, []): + for bad_raymarcher in (None, 5, []): + with self.assertRaises(ValueError): + VolumeRenderer(raysampler=bad_raysampler, raymarcher=bad_raymarcher) + + raysampler = NDCMultinomialRaysampler( + image_width=100, + image_height=100, + n_pts_per_ray=10, + min_depth=0.1, + max_depth=1.0, + ) + + # init a trivial renderer + renderer = VolumeRenderer( + raysampler=raysampler, raymarcher=EmissionAbsorptionRaymarcher() + ) + + # get cameras + cameras = init_cameras(batch_size=batch_size) + + # get volumes + volumes = init_boundary_volume(volume_size=(10, 10, 10), batch_size=batch_size)[ + 0 + ] + + # different batch sizes for cameras / volumes + with self.assertRaises(ValueError): + renderer(cameras=cameras, volumes=volumes[:-1]) + + # ray checks for VolumeSampler + volume_sampler = VolumeSampler(volumes=volumes) + n_rays = 100 + for bad_ray_bundle in ( + ( + torch.rand(batch_size, n_rays, 3), + torch.rand(batch_size, n_rays + 1, 3), + torch.rand(batch_size, n_rays, 10), + ), + ( + torch.rand(batch_size + 1, n_rays, 3), + torch.rand(batch_size, n_rays, 3), + torch.rand(batch_size, n_rays, 10), + ), + ( + torch.rand(batch_size, n_rays, 3), + torch.rand(batch_size, n_rays, 2), + torch.rand(batch_size, n_rays, 10), + ), + ( + torch.rand(batch_size, n_rays, 3), + torch.rand(batch_size, n_rays, 3), + torch.rand(batch_size, n_rays), + ), + ): + ray_bundle = RayBundle( + **dict( + zip( + ("origins", "directions", "lengths"), + [r.to(cameras.device) for r in bad_ray_bundle], + ) + ), + xys=None, + ) + with self.assertRaises(ValueError): + volume_sampler(ray_bundle) + + # check also explicitly the ray bundle validation function + with self.assertRaises(ValueError): + _validate_ray_bundle_variables(*bad_ray_bundle) + + def test_compare_with_pointclouds_renderer( + self, batch_size=11, volume_size=(30, 30, 30), image_size=(200, 250) + ): + """ + Generate a volume and its corresponding point cloud and check whether + PointsRenderer returns the same images as the corresponding VolumeRenderer. + """ + + # generate NDC camera extrinsics and intrinsics + cameras = init_cameras(batch_size, image_size=image_size, ndc=True) + + # init the boundary volume + for shape in ("sphere", "cube"): + if not DEBUG and shape == "cube": + # do not run numeric checks for the cube as the + # differences in rendering equations make the renders incomparable + continue + + # get rand offset of the volume + volume_translation = torch.randn(batch_size, 3) * 0.1 + # volume_translation[2] = 0.1 + volumes = init_boundary_volume( + volume_size=volume_size, + batch_size=batch_size, + shape=shape, + volume_translation=volume_translation, + )[0] + + # convert the volumes to a pointcloud + points = [] + points_features = [] + for densities_one, features_one, grid_one in zip( + volumes.densities(), + volumes.features(), + volumes.get_coord_grid(world_coordinates=True), + ): + opaque = densities_one.view(-1) > 1e-4 + points.append(grid_one.view(-1, 3)[opaque]) + points_features.append(features_one.reshape(3, -1).t()[opaque]) + pointclouds = Pointclouds(points, features=points_features) + + # init the grid raysampler with the ndc grid + coord_range = 1.0 + half_pix_size = coord_range / max(*image_size) + raysampler = NDCMultinomialRaysampler( + image_width=image_size[1], + image_height=image_size[0], + n_pts_per_ray=256, + min_depth=0.1, + max_depth=2.0, + ) + + # get the EA raymarcher + raymarcher = EmissionAbsorptionRaymarcher() + + # jitter the camera intrinsics a bit for each render + cameras_randomized = cameras.clone() + cameras_randomized.principal_point = ( + torch.randn_like(cameras.principal_point) * 0.3 + ) + cameras_randomized.focal_length = ( + cameras.focal_length + torch.randn_like(cameras.focal_length) * 0.2 + ) + + # get the volumetric render + images = VolumeRenderer( + raysampler=raysampler, raymarcher=raymarcher, sample_mode="bilinear" + )(cameras=cameras_randomized, volumes=volumes)[0][..., :3] + + # instantiate the points renderer + point_radius = 6 * half_pix_size + points_renderer = PointsRenderer( + rasterizer=PointsRasterizer( + cameras=cameras_randomized, + raster_settings=PointsRasterizationSettings( + image_size=image_size, radius=point_radius, points_per_pixel=10 + ), + ), + compositor=AlphaCompositor(), + ) + + # get the point render + images_pts = points_renderer(pointclouds) + + if shape == "sphere": + diff = (images - images_pts).abs().mean(dim=-1) + mu_diff = diff.mean(dim=(1, 2)) + std_diff = diff.std(dim=(1, 2)) + self.assertClose(mu_diff, torch.zeros_like(mu_diff), atol=3e-2) + self.assertClose(std_diff, torch.zeros_like(std_diff), atol=6e-2) + + if DEBUG: + outdir = tempfile.gettempdir() + "/test_volume_vs_pts_renderer" + os.makedirs(outdir, exist_ok=True) + + frames = [] + for image, image_pts in zip(images, images_pts): + diff_image = ( + ((image - image_pts) * 0.5 + 0.5) + .mean(dim=2, keepdim=True) + .repeat(1, 1, 3) + ) + image_pil = Image.fromarray( + ( + torch.cat((image, image_pts, diff_image), dim=1) + .detach() + .cpu() + .numpy() + * 255.0 + ).astype(np.uint8) + ) + frames.append(image_pil) + + # export gif + outfile = os.path.join(outdir, f"volume_vs_pts_render_{shape}.gif") + frames[0].save( + outfile, + save_all=True, + append_images=frames[1:], + duration=batch_size // 15, + loop=0, + ) + print(f"exported {outfile}") + + # export concatenated frames + outfile_cat = os.path.join(outdir, f"volume_vs_pts_render_{shape}.png") + Image.fromarray( + np.concatenate([np.array(f) for f in frames], axis=0) + ).save(outfile_cat) + print(f"exported {outfile_cat}") + + def test_monte_carlo_rendering( + self, n_frames=20, volume_size=(30, 30, 30), image_size=(40, 50) + ): + """ + Tests that rendering with the MonteCarloRaysampler matches the + rendering with MultinomialRaysampler sampled at the corresponding + MonteCarlo locations. + """ + volumes = init_boundary_volume( + volume_size=volume_size, batch_size=n_frames, shape="sphere" + )[0] + + # generate camera extrinsics and intrinsics + cameras = init_cameras(n_frames, image_size=image_size) + + # init the grid raysampler + raysampler_multinomial = MultinomialRaysampler( + min_x=0.5, + max_x=image_size[1] - 0.5, + min_y=0.5, + max_y=image_size[0] - 0.5, + image_width=image_size[1], + image_height=image_size[0], + n_pts_per_ray=256, + min_depth=0.5, + max_depth=2.0, + ) + + # init the mc raysampler + raysampler_mc = MonteCarloRaysampler( + min_x=0.5, + max_x=image_size[1] - 0.5, + min_y=0.5, + max_y=image_size[0] - 0.5, + n_rays_per_image=3000, + n_pts_per_ray=256, + min_depth=0.5, + max_depth=2.0, + ) + + # get the EA raymarcher + raymarcher = EmissionAbsorptionRaymarcher() + + # get both mc and grid renders + ( + (images_opacities_mc, ray_bundle_mc), + (images_opacities_grid, ray_bundle_grid), + ) = [ + VolumeRenderer( + raysampler=raysampler_multinomial, + raymarcher=raymarcher, + sample_mode="bilinear", + )(cameras=cameras, volumes=volumes) + for raysampler in (raysampler_mc, raysampler_multinomial) + ] + + # convert the mc sampling locations to [-1, 1] + sample_loc = ray_bundle_mc.xys.clone() + sample_loc[..., 0] = 2 * (sample_loc[..., 0] / image_size[1]) - 1 + sample_loc[..., 1] = 2 * (sample_loc[..., 1] / image_size[0]) - 1 + + # sample the grid render at the mc locations + images_opacities_mc_ = torch.nn.functional.grid_sample( + images_opacities_grid.permute(0, 3, 1, 2), sample_loc, align_corners=False + ) + + # check that the samples are the same + self.assertClose( + images_opacities_mc.permute(0, 3, 1, 2), images_opacities_mc_, atol=1e-4 + ) + + def test_rotating_gif(self): + self._rotating_gif(image_size=(200, 100)) + self._rotating_gif(image_size=(100, 200)) + + def _rotating_gif( + self, image_size, n_frames=50, fps=15, volume_size=(100, 100, 100) + ): + """ + Render a gif animation of a rotating cube/sphere (runs only if `DEBUG==True`). + """ + + if not DEBUG: + # do not run this if debug is False + return + + for shape in ("sphere", "cube"): + for sample_mode in ("bilinear", "nearest"): + volumes = init_boundary_volume( + volume_size=volume_size, batch_size=n_frames, shape=shape + )[0] + + # generate camera extrinsics and intrinsics + cameras = init_cameras(n_frames, image_size=image_size) + + # init the grid raysampler + raysampler = MultinomialRaysampler( + min_x=0.5, + max_x=image_size[1] - 0.5, + min_y=0.5, + max_y=image_size[0] - 0.5, + image_width=image_size[1], + image_height=image_size[0], + n_pts_per_ray=256, + min_depth=0.5, + max_depth=2.0, + ) + + # get the EA raymarcher + raymarcher = EmissionAbsorptionRaymarcher() + + # initialize the renderer + renderer = VolumeRenderer( + raysampler=raysampler, + raymarcher=raymarcher, + sample_mode=sample_mode, + ) + + # run the renderer + images_opacities = renderer(cameras=cameras, volumes=volumes)[0] + + # split output to the alpha channel and rendered images + images, opacities = images_opacities[..., :3], images_opacities[..., 3] + + # export the gif + outdir = tempfile.gettempdir() + "/test_volume_renderer_gifs" + os.makedirs(outdir, exist_ok=True) + frames = [] + for image, opacity in zip(images, opacities): + image_pil = Image.fromarray( + ( + torch.cat( + (image, opacity[..., None].repeat(1, 1, 3)), dim=1 + ) + .detach() + .cpu() + .numpy() + * 255.0 + ).astype(np.uint8) + ) + frames.append(image_pil) + outfile = os.path.join(outdir, f"{shape}_{sample_mode}.gif") + frames[0].save( + outfile, + save_all=True, + append_images=frames[1:], + duration=n_frames // fps, + loop=0, + ) + print(f"exported {outfile}") + + def test_rotating_cube_volume_render(self): + """ + Generates 4 renders of 4 sides of a volume representing a 3D cube. + Since each side of the cube is homogeneously colored with + a different color, this should result in 4 images of homogeneous color + with the depth of each pixel equal to a constant. + """ + + # batch_size = 4 sides of the cube + batch_size = 4 + image_size = (50, 40) + + for volume_size in ([25, 25, 25],): + for sample_mode in ("bilinear", "nearest"): + volume_translation = torch.zeros(4, 3) + volume_translation.requires_grad = True + volumes, volume_voxel_size, _ = init_boundary_volume( + volume_size=volume_size, + batch_size=batch_size, + shape="cube", + volume_translation=volume_translation, + ) + + # generate camera extrinsics and intrinsics + cameras = init_cameras(batch_size, image_size=image_size) + + # enable the gradient caching for the camera variables + # the list of differentiable camera vars + cam_vars = ("R", "T", "focal_length", "principal_point") + for cam_var in cam_vars: + getattr(cameras, cam_var).requires_grad = True + # enable the grad for volume vars as well + volumes.features().requires_grad = True + volumes.densities().requires_grad = True + + raysampler = MultinomialRaysampler( + min_x=0.5, + max_x=image_size[1] - 0.5, + min_y=0.5, + max_y=image_size[0] - 0.5, + image_width=image_size[1], + image_height=image_size[0], + n_pts_per_ray=128, + min_depth=0.01, + max_depth=3.0, + ) + + raymarcher = EmissionAbsorptionRaymarcher() + renderer = VolumeRenderer( + raysampler=raysampler, + raymarcher=raymarcher, + sample_mode=sample_mode, + ) + images_opacities = renderer(cameras=cameras, volumes=volumes)[0] + images, opacities = images_opacities[..., :3], images_opacities[..., 3] + + # check that the renderer does not erase gradients + loss = images_opacities.sum() + loss.backward() + for check_var in ( + *[getattr(cameras, cam_var) for cam_var in cam_vars], + volumes.features(), + volumes.densities(), + volume_translation, + ): + self.assertIsNotNone(check_var.grad) + + # ao opacities should be exactly the same as the ea ones + # we can further get the ea opacities from a feature-less + # version of our volumes + raymarcher_ao = AbsorptionOnlyRaymarcher() + renderer_ao = VolumeRenderer( + raysampler=raysampler, + raymarcher=raymarcher_ao, + sample_mode=sample_mode, + ) + volumes_featureless = Volumes( + densities=volumes.densities(), + volume_translation=volume_translation, + voxel_size=volume_voxel_size, + ) + opacities_ao = renderer_ao( + cameras=cameras, volumes=volumes_featureless + )[0][..., 0] + self.assertClose(opacities, opacities_ao) + + # colors of the sides of the cube + gt_clr_sides = torch.tensor( + [ + [1.0, 0.0, 0.0], + [0.0, 1.0, 1.0], + [1.0, 1.0, 1.0], + [0.0, 1.0, 0.0], + ], + dtype=torch.float32, + device=images.device, + ) + + if DEBUG: + outdir = tempfile.gettempdir() + "/test_volume_renderer" + os.makedirs(outdir, exist_ok=True) + for imidx, (image, opacity) in enumerate(zip(images, opacities)): + for image_ in (image, opacity): + image_pil = Image.fromarray( + (image_.detach().cpu().numpy() * 255.0).astype(np.uint8) + ) + outfile = ( + outdir + + f"/rgb_{sample_mode}" + + f"_{str(volume_size).replace(' ', '')}" + + f"_{imidx:003d}" + ) + if image_ is image: + outfile += "_rgb.png" + else: + outfile += "_opacity.png" + image_pil.save(outfile) + print(f"exported {outfile}") + + border = 10 + for image, opacity, gt_color in zip(images, opacities, gt_clr_sides): + image_crop = image[border:-border, border:-border] + opacity_crop = opacity[border:-border, border:-border] + + # check mean and std difference from gt + err = ( + (image_crop - gt_color[None, None].expand_as(image_crop)) + .abs() + .mean(dim=-1) + ) + zero = err.new_zeros(1)[0] + self.assertClose(err.mean(), zero, atol=1e-2) + self.assertClose(err.std(), zero, atol=1e-2) + + err_opacity = (opacity_crop - 1.0).abs() + self.assertClose(err_opacity.mean(), zero, atol=1e-2) + self.assertClose(err_opacity.std(), zero, atol=1e-2) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_rendering_utils.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_rendering_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d9730daa01799d818e6eaae79b643f5d81b49c90 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_rendering_utils.py @@ -0,0 +1,271 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + + +import unittest + +import numpy as np +import torch +from pytorch3d.common.compat import meshgrid_ij +from pytorch3d.ops import eyes +from pytorch3d.renderer import ( + AlphaCompositor, + PerspectiveCameras, + PointsRasterizationSettings, + PointsRasterizer, + PointsRenderer, +) +from pytorch3d.renderer.utils import ( + ndc_grid_sample, + ndc_to_grid_sample_coords, + TensorProperties, +) +from pytorch3d.structures import Pointclouds + +from .common_testing import TestCaseMixin + + +# Example class for testing +class TensorPropertiesTestClass(TensorProperties): + def __init__(self, x=None, y=None, device="cpu"): + super().__init__(device=device, x=x, y=y) + + def clone(self): + other = TensorPropertiesTestClass() + return super().clone(other) + + +class TestTensorProperties(TestCaseMixin, unittest.TestCase): + def test_init(self): + example = TensorPropertiesTestClass(x=10.0, y=(100.0, 200.0)) + # Check kwargs set as attributes + converted to tensors + self.assertTrue(torch.is_tensor(example.x)) + self.assertTrue(torch.is_tensor(example.y)) + # Check broadcasting + self.assertTrue(example.x.shape == (2,)) + self.assertTrue(example.y.shape == (2,)) + self.assertTrue(len(example) == 2) + + def test_to(self): + # Check to method + example = TensorPropertiesTestClass(x=10.0, y=(100.0, 200.0)) + device = torch.device("cuda:0") + new_example = example.to(device=device) + self.assertEqual(new_example.device, device) + + example_cpu = example.cpu() + self.assertEqual(example_cpu.device, torch.device("cpu")) + + example_gpu = example.cuda() + self.assertEqual(example_gpu.device.type, "cuda") + self.assertIsNotNone(example_gpu.device.index) + + def test_clone(self): + # Check clone method + example = TensorPropertiesTestClass(x=10.0, y=(100.0, 200.0)) + new_example = example.clone() + self.assertSeparate(example.x, new_example.x) + self.assertSeparate(example.y, new_example.y) + + def test_get_set(self): + # Test getitem returns an accessor which can be used to modify + # attributes at a particular index + example = TensorPropertiesTestClass(x=10.0, y=(100.0, 200.0, 300.0)) + + # update y1 + example[1].y = 5.0 + self.assertTrue(example.y[1] == 5.0) + + # Get item and get value + ex0 = example[0] + self.assertTrue(ex0.y == 100.0) + + def test_empty_input(self): + example = TensorPropertiesTestClass(x=(), y=()) + self.assertTrue(len(example) == 0) + self.assertTrue(example.isempty()) + + def test_gather_props(self): + N = 4 + x = torch.randn((N, 3, 4)) + y = torch.randn((N, 5)) + test_class = TensorPropertiesTestClass(x=x, y=y) + + S = 15 + idx = torch.tensor(np.random.choice(N, S)) + test_class_gathered = test_class.gather_props(idx) + + self.assertTrue(test_class_gathered.x.shape == (S, 3, 4)) + self.assertTrue(test_class_gathered.y.shape == (S, 5)) + + for i in range(N): + inds = idx == i + if inds.sum() > 0: + # Check the gathered points in the output have the same value from + # the input. + self.assertClose(test_class_gathered.x[inds].mean(dim=0), x[i, ...]) + self.assertClose(test_class_gathered.y[inds].mean(dim=0), y[i, ...]) + + def test_ndc_grid_sample_rendering(self): + """ + Use PyTorch3D point renderer to render a colored point cloud, then + sample the image at the locations of the point projections with + `ndc_grid_sample`. Finally, assert that the sampled colors are equal to the + original point cloud colors. + + Note that, in order to ensure correctness, we use a nearest-neighbor + assignment point renderer (i.e. no soft splatting). + """ + + # generate a bunch of 3D points on a regular grid lying in the z-plane + n_grid_pts = 10 + grid_scale = 0.9 + z_plane = 2.0 + image_size = [128, 128] + point_radius = 0.015 + n_pts = n_grid_pts * n_grid_pts + pts = torch.stack( + meshgrid_ij( + [torch.linspace(-grid_scale, grid_scale, n_grid_pts)] * 2, + ), + dim=-1, + ) + pts = torch.cat([pts, z_plane * torch.ones_like(pts[..., :1])], dim=-1) + pts = pts.reshape(1, n_pts, 3) + + # color the points randomly + pts_colors = torch.rand(1, n_pts, 3) + + # make trivial rendering cameras + cameras = PerspectiveCameras( + R=eyes(dim=3, N=1), + device=pts.device, + T=torch.zeros(1, 3, dtype=torch.float32, device=pts.device), + ) + + # render the point cloud + pcl = Pointclouds(points=pts, features=pts_colors) + renderer = NearestNeighborPointsRenderer( + rasterizer=PointsRasterizer( + cameras=cameras, + raster_settings=PointsRasterizationSettings( + image_size=image_size, + radius=point_radius, + points_per_pixel=1, + ), + ), + compositor=AlphaCompositor(), + ) + im_render = renderer(pcl) + + # sample the render at projected pts + pts_proj = cameras.transform_points(pcl.points_padded())[..., :2] + pts_colors_sampled = ndc_grid_sample( + im_render, + pts_proj, + mode="nearest", + align_corners=False, + ).permute(0, 2, 1) + + # assert that the samples are the same as original points + self.assertClose(pts_colors, pts_colors_sampled, atol=1e-4) + + def test_ndc_to_grid_sample_coords(self): + """ + Test the conversion from ndc to grid_sample coords by comparing + to known conversion results. + """ + + # square image tests + image_size_square = [100, 100] + xy_ndc_gs_square = torch.FloatTensor( + [ + # 4 corners + [[-1.0, -1.0], [1.0, 1.0]], + [[1.0, 1.0], [-1.0, -1.0]], + [[1.0, -1.0], [-1.0, 1.0]], + [[1.0, 1.0], [-1.0, -1.0]], + # center + [[0.0, 0.0], [0.0, 0.0]], + ] + ) + + # non-batched version + for xy_ndc, xy_gs in xy_ndc_gs_square: + xy_gs_predicted = ndc_to_grid_sample_coords( + xy_ndc, + image_size_square, + ) + self.assertClose(xy_gs_predicted, xy_gs) + + # batched version + xy_ndc, xy_gs = xy_ndc_gs_square[:, 0], xy_ndc_gs_square[:, 1] + xy_gs_predicted = ndc_to_grid_sample_coords( + xy_ndc, + image_size_square, + ) + self.assertClose(xy_gs_predicted, xy_gs) + + # non-square image tests + image_size = [100, 200] + xy_ndc_gs = torch.FloatTensor( + [ + # 4 corners + [[-2.0, -1.0], [1.0, 1.0]], + [[2.0, -1.0], [-1.0, 1.0]], + [[-2.0, 1.0], [1.0, -1.0]], + [[2.0, 1.0], [-1.0, -1.0]], + # center + [[0.0, 0.0], [0.0, 0.0]], + # non-corner points + [[4.0, 0.5], [-2.0, -0.5]], + [[1.0, -0.5], [-0.5, 0.5]], + ] + ) + + # check both H > W and W > H + for flip_axes in [False, True]: + # non-batched version + for xy_ndc, xy_gs in xy_ndc_gs: + xy_gs_predicted = ndc_to_grid_sample_coords( + xy_ndc.flip(dims=(-1,)) if flip_axes else xy_ndc, + list(reversed(image_size)) if flip_axes else image_size, + ) + self.assertClose( + xy_gs_predicted, + xy_gs.flip(dims=(-1,)) if flip_axes else xy_gs, + ) + + # batched version + xy_ndc, xy_gs = xy_ndc_gs[:, 0], xy_ndc_gs[:, 1] + xy_gs_predicted = ndc_to_grid_sample_coords( + xy_ndc.flip(dims=(-1,)) if flip_axes else xy_ndc, + list(reversed(image_size)) if flip_axes else image_size, + ) + self.assertClose( + xy_gs_predicted, + xy_gs.flip(dims=(-1,)) if flip_axes else xy_gs, + ) + + +class NearestNeighborPointsRenderer(PointsRenderer): + """ + A class for rendering a batch of points by a trivial nearest + neighbor assignment. + """ + + def forward(self, point_clouds, **kwargs) -> torch.Tensor: + fragments = self.rasterizer(point_clouds, **kwargs) + # set all weights trivially to one + dists2 = fragments.dists.permute(0, 3, 1, 2) + weights = torch.ones_like(dists2) + images = self.compositor( + fragments.idx.long().permute(0, 3, 1, 2), + weights, + point_clouds.features_packed().permute(1, 0), + **kwargs, + ) + return images diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_rotation_conversions.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_rotation_conversions.py new file mode 100644 index 0000000000000000000000000000000000000000..1ed99453a6bb735be6e274530c01a1c3203e0ce8 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_rotation_conversions.py @@ -0,0 +1,306 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + + +import itertools +import math +import unittest +from typing import Optional, Union + +import numpy as np +import torch +from pytorch3d.transforms.rotation_conversions import ( + axis_angle_to_matrix, + axis_angle_to_quaternion, + euler_angles_to_matrix, + matrix_to_axis_angle, + matrix_to_euler_angles, + matrix_to_quaternion, + matrix_to_rotation_6d, + quaternion_apply, + quaternion_multiply, + quaternion_to_axis_angle, + quaternion_to_matrix, + random_quaternions, + random_rotation, + random_rotations, + rotation_6d_to_matrix, +) + +from .common_testing import TestCaseMixin + + +class TestRandomRotation(unittest.TestCase): + def setUp(self) -> None: + super().setUp() + torch.manual_seed(1) + + def test_random_rotation_invariant(self): + """The image of the x-axis isn't biased among quadrants.""" + N = 1000 + base = random_rotation() + quadrants = list(itertools.product([False, True], repeat=3)) + + matrices = random_rotations(N) + transformed = torch.matmul(base, matrices) + transformed2 = torch.matmul(matrices, base) + + for k, results in enumerate([matrices, transformed, transformed2]): + counts = {i: 0 for i in quadrants} + for j in range(N): + counts[tuple(i.item() > 0 for i in results[j, 0])] += 1 + average = N / 8.0 + counts_tensor = torch.tensor(list(counts.values())) + chisquare_statistic = torch.sum( + (counts_tensor - average) * (counts_tensor - average) / average + ) + # The 0.1 significance level for chisquare(8-1) is + # scipy.stats.chi2(7).ppf(0.9) == 12.017. + self.assertLess(chisquare_statistic, 12, (counts, chisquare_statistic, k)) + + +class TestRotationConversion(TestCaseMixin, unittest.TestCase): + def setUp(self) -> None: + super().setUp() + torch.manual_seed(1) + + def test_from_quat(self): + """quat -> mtx -> quat""" + data = random_quaternions(13, dtype=torch.float64) + mdata = matrix_to_quaternion(quaternion_to_matrix(data)) + self._assert_quaternions_close(data, mdata) + + def test_to_quat(self): + """mtx -> quat -> mtx""" + data = random_rotations(13, dtype=torch.float64) + mdata = quaternion_to_matrix(matrix_to_quaternion(data)) + self.assertClose(data, mdata) + + def test_quat_grad_exists(self): + """Quaternion calculations are differentiable.""" + rotation = random_rotation() + rotation.requires_grad = True + modified = quaternion_to_matrix(matrix_to_quaternion(rotation)) + [g] = torch.autograd.grad(modified.sum(), rotation) + self.assertTrue(torch.isfinite(g).all()) + + def _tait_bryan_conventions(self): + return map("".join, itertools.permutations("XYZ")) + + def _proper_euler_conventions(self): + letterpairs = itertools.permutations("XYZ", 2) + return (l0 + l1 + l0 for l0, l1 in letterpairs) + + def _all_euler_angle_conventions(self): + return itertools.chain( + self._tait_bryan_conventions(), self._proper_euler_conventions() + ) + + def test_conventions(self): + """The conventions listings have the right length.""" + all = list(self._all_euler_angle_conventions()) + self.assertEqual(len(all), 12) + self.assertEqual(len(set(all)), 12) + + def test_from_euler(self): + """euler -> mtx -> euler""" + n_repetitions = 10 + # tolerance is how much we keep the middle angle away from the extreme + # allowed values which make the calculation unstable (Gimbal lock). + tolerance = 0.04 + half_pi = math.pi / 2 + data = torch.zeros(n_repetitions, 3) + data.uniform_(-math.pi, math.pi) + + data[:, 1].uniform_(-half_pi + tolerance, half_pi - tolerance) + for convention in self._tait_bryan_conventions(): + matrices = euler_angles_to_matrix(data, convention) + mdata = matrix_to_euler_angles(matrices, convention) + self.assertClose(data, mdata) + + data[:, 1] += half_pi + for convention in self._proper_euler_conventions(): + matrices = euler_angles_to_matrix(data, convention) + mdata = matrix_to_euler_angles(matrices, convention) + self.assertClose(data, mdata) + + def test_to_euler(self): + """mtx -> euler -> mtx""" + data = random_rotations(13, dtype=torch.float64) + for convention in self._all_euler_angle_conventions(): + euler_angles = matrix_to_euler_angles(data, convention) + mdata = euler_angles_to_matrix(euler_angles, convention) + self.assertClose(data, mdata) + + def test_euler_grad_exists(self): + """Euler angle calculations are differentiable.""" + rotation = random_rotation(dtype=torch.float64) + rotation.requires_grad = True + for convention in self._all_euler_angle_conventions(): + euler_angles = matrix_to_euler_angles(rotation, convention) + mdata = euler_angles_to_matrix(euler_angles, convention) + [g] = torch.autograd.grad(mdata.sum(), rotation) + self.assertTrue(torch.isfinite(g).all()) + + def test_quaternion_multiplication(self): + """Quaternion and matrix multiplication are equivalent.""" + a = random_quaternions(15, torch.float64).reshape((3, 5, 4)) + b = random_quaternions(21, torch.float64).reshape((7, 3, 1, 4)) + ab = quaternion_multiply(a, b) + self.assertEqual(ab.shape, (7, 3, 5, 4)) + a_matrix = quaternion_to_matrix(a) + b_matrix = quaternion_to_matrix(b) + ab_matrix = torch.matmul(a_matrix, b_matrix) + ab_from_matrix = matrix_to_quaternion(ab_matrix) + self._assert_quaternions_close(ab, ab_from_matrix) + + def test_matrix_to_quaternion_corner_case(self): + """Check no bad gradients from sqrt(0).""" + matrix = torch.eye(3, requires_grad=True) + target = torch.Tensor([0.984808, 0, 0.174, 0]) + + optimizer = torch.optim.Adam([matrix], lr=0.05) + optimizer.zero_grad() + q = matrix_to_quaternion(matrix) + loss = torch.sum((q - target) ** 2) + loss.backward() + optimizer.step() + + self.assertClose(matrix, matrix, msg="Result has non-finite values") + delta = 1e-2 + self.assertLess( + matrix.trace(), + 3.0 - delta, + msg="Identity initialisation unchanged by a gradient step", + ) + + def test_matrix_to_quaternion_by_pi(self): + # We check that rotations by pi around each of the 26 + # nonzero vectors containing nothing but 0, 1 and -1 + # are mapped to the right quaternions. + # This is representative across the directions. + options = [0.0, -1.0, 1.0] + axes = [ + torch.tensor(vec) + for vec in itertools.islice( # exclude [0, 0, 0] + itertools.product(options, options, options), 1, None + ) + ] + + axes = torch.nn.functional.normalize(torch.stack(axes), dim=-1) + # Rotation by pi around unit vector x is given by + # the matrix 2 x x^T - Id. + R = 2 * torch.matmul(axes[..., None], axes[..., None, :]) - torch.eye(3) + quats_hat = matrix_to_quaternion(R) + R_hat = quaternion_to_matrix(quats_hat) + self.assertClose(R, R_hat, atol=1e-3) + + def test_from_axis_angle(self): + """axis_angle -> mtx -> axis_angle""" + n_repetitions = 20 + data = torch.rand(n_repetitions, 3) + matrices = axis_angle_to_matrix(data) + self.assertClose(data, matrix_to_axis_angle(matrices), atol=2e-6) + self.assertClose(data, matrix_to_axis_angle(matrices, fast=True), atol=2e-6) + matrices = axis_angle_to_matrix(data, fast=True) + mdata = matrix_to_axis_angle(matrices) + self.assertClose(data, mdata, atol=2e-6) + + def test_from_axis_angle_has_grad(self): + n_repetitions = 20 + data = torch.rand(n_repetitions, 3, requires_grad=True) + matrices = axis_angle_to_matrix(data) + mdata = matrix_to_axis_angle(matrices) + quats = axis_angle_to_quaternion(data) + mdata2 = quaternion_to_axis_angle(quats) + (grad,) = torch.autograd.grad(mdata.sum() + mdata2.sum(), data) + self.assertTrue(torch.isfinite(grad).all()) + + def test_to_axis_angle(self): + """mtx -> axis_angle -> mtx""" + data = random_rotations(13, dtype=torch.float64) + euler_angles = matrix_to_axis_angle(data) + euler_angles_fast = matrix_to_axis_angle(data) + self.assertClose(data, axis_angle_to_matrix(euler_angles)) + self.assertClose(data, axis_angle_to_matrix(euler_angles_fast)) + self.assertClose(data, axis_angle_to_matrix(euler_angles, fast=True)) + + def test_quaternion_application(self): + """Applying a quaternion is the same as applying the matrix.""" + quaternions = random_quaternions(3, torch.float64) + quaternions.requires_grad = True + matrices = quaternion_to_matrix(quaternions) + points = torch.randn(3, 3, dtype=torch.float64, requires_grad=True) + transform1 = quaternion_apply(quaternions, points) + transform2 = torch.matmul(matrices, points[..., None])[..., 0] + self.assertClose(transform1, transform2) + + [p, q] = torch.autograd.grad(transform1.sum(), [points, quaternions]) + self.assertTrue(torch.isfinite(p).all()) + self.assertTrue(torch.isfinite(q).all()) + + def test_6d(self): + """Converting to 6d and back""" + r = random_rotations(13, dtype=torch.float64) + + # 6D representation is not unique, + # but we implement it by taking the first two rows of the matrix + r6d = matrix_to_rotation_6d(r) + self.assertClose(r6d, r[:, :2, :].reshape(-1, 6)) + + # going to 6D and back should not change the matrix + r_hat = rotation_6d_to_matrix(r6d) + self.assertClose(r_hat, r) + + # moving the second row R2 in the span of (R1, R2) should not matter + r6d[:, 3:] += 2 * r6d[:, :3] + r6d[:, :3] *= 3.0 + r_hat = rotation_6d_to_matrix(r6d) + self.assertClose(r_hat, r) + + # check that we map anything to a valid rotation + r6d = torch.rand(13, 6) + r6d[:4, :] *= 3.0 + r6d[4:8, :] -= 0.5 + r = rotation_6d_to_matrix(r6d) + self.assertClose( + torch.matmul(r, r.permute(0, 2, 1)), torch.eye(3).expand_as(r), atol=1e-6 + ) + + def test_scriptable(self): + torch.jit.script(axis_angle_to_matrix) + torch.jit.script(axis_angle_to_quaternion) + torch.jit.script(euler_angles_to_matrix) + torch.jit.script(matrix_to_axis_angle) + torch.jit.script(matrix_to_euler_angles) + torch.jit.script(matrix_to_quaternion) + torch.jit.script(matrix_to_rotation_6d) + torch.jit.script(quaternion_apply) + torch.jit.script(quaternion_multiply) + torch.jit.script(quaternion_to_matrix) + torch.jit.script(quaternion_to_axis_angle) + torch.jit.script(random_quaternions) + torch.jit.script(random_rotation) + torch.jit.script(random_rotations) + torch.jit.script(random_quaternions) + torch.jit.script(rotation_6d_to_matrix) + + def _assert_quaternions_close( + self, + input: Union[torch.Tensor, np.ndarray], + other: Union[torch.Tensor, np.ndarray], + *, + rtol: float = 1e-05, + atol: float = 1e-08, + equal_nan: bool = False, + msg: Optional[str] = None, + ): + self.assertEqual(np.shape(input), np.shape(other)) + dot = (input * other).sum(-1) + ones = torch.ones_like(dot) + self.assertClose( + dot.abs(), ones, rtol=rtol, atol=atol, equal_nan=equal_nan, msg=msg + ) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_so3.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_so3.py new file mode 100644 index 0000000000000000000000000000000000000000..617cd3130861ea5ed83355776dd08fd6551885af --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_so3.py @@ -0,0 +1,281 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + + +import math +import unittest + +import numpy as np +import torch +from pytorch3d.transforms.so3 import ( + hat, + so3_exp_map, + so3_log_map, + so3_relative_angle, + so3_rotation_angle, +) + +from .common_testing import TestCaseMixin + + +class TestSO3(TestCaseMixin, unittest.TestCase): + def setUp(self) -> None: + super().setUp() + torch.manual_seed(42) + np.random.seed(42) + + @staticmethod + def init_log_rot(batch_size: int = 10): + """ + Initialize a list of `batch_size` 3-dimensional vectors representing + randomly generated logarithms of rotation matrices. + """ + device = torch.device("cuda:0") + log_rot = torch.randn((batch_size, 3), dtype=torch.float32, device=device) + return log_rot + + @staticmethod + def init_rot(batch_size: int = 10): + """ + Randomly generate a batch of `batch_size` 3x3 rotation matrices. + """ + device = torch.device("cuda:0") + + # TODO(dnovotny): replace with random_rotation from random_rotation.py + rot = [] + for _ in range(batch_size): + r = torch.linalg.qr(torch.randn((3, 3), device=device))[0] + f = torch.randint(2, (3,), device=device, dtype=torch.float32) + if f.sum() % 2 == 0: + f = 1 - f + rot.append(r * (2 * f - 1).float()) + rot = torch.stack(rot) + + return rot + + def test_determinant(self): + """ + Tests whether the determinants of 3x3 rotation matrices produced + by `so3_exp_map` are (almost) equal to 1. + """ + log_rot = TestSO3.init_log_rot(batch_size=30) + Rs = so3_exp_map(log_rot) + dets = torch.det(Rs) + self.assertClose(dets, torch.ones_like(dets), atol=1e-4) + + def test_cross(self): + """ + For a pair of randomly generated 3-dimensional vectors `a` and `b`, + tests whether a matrix product of `hat(a)` and `b` equals the result + of a cross product between `a` and `b`. + """ + device = torch.device("cuda:0") + a, b = torch.randn((2, 100, 3), dtype=torch.float32, device=device) + hat_a = hat(a) + cross = torch.bmm(hat_a, b[:, :, None])[:, :, 0] + torch_cross = torch.cross(a, b, dim=1) + self.assertClose(torch_cross, cross, atol=1e-4) + + def test_bad_so3_input_value_err(self): + """ + Tests whether `so3_exp_map` and `so3_log_map` correctly return + a ValueError if called with an argument of incorrect shape or, in case + of `so3_exp_map`, unexpected trace. + """ + device = torch.device("cuda:0") + log_rot = torch.randn(size=[5, 4], device=device) + with self.assertRaises(ValueError) as err: + so3_exp_map(log_rot) + self.assertTrue("Input tensor shape has to be Nx3." in str(err.exception)) + + rot = torch.randn(size=[5, 3, 5], device=device) + with self.assertRaises(ValueError) as err: + so3_log_map(rot) + self.assertTrue("Input has to be a batch of 3x3 Tensors." in str(err.exception)) + + def test_so3_exp_singularity(self, batch_size: int = 100): + """ + Tests whether the `so3_exp_map` is robust to the input vectors + the norms of which are close to the numerically unstable region + (vectors with low l2-norms). + """ + # generate random log-rotations with a tiny angle + log_rot = TestSO3.init_log_rot(batch_size=batch_size) + log_rot_small = log_rot * 1e-6 + log_rot_small.requires_grad = True + R = so3_exp_map(log_rot_small) + # tests whether all outputs are finite + self.assertTrue(torch.isfinite(R).all()) + # tests whether the gradient is not None and all finite + loss = R.sum() + loss.backward() + self.assertIsNotNone(log_rot_small.grad) + self.assertTrue(torch.isfinite(log_rot_small.grad).all()) + + def test_so3_log_singularity(self, batch_size: int = 100): + """ + Tests whether the `so3_log_map` is robust to the input matrices + who's rotation angles are close to the numerically unstable region + (i.e. matrices with low rotation angles). + """ + # generate random rotations with a tiny angle + device = torch.device("cuda:0") + identity = torch.eye(3, device=device) + rot180 = identity * torch.tensor([[1.0, -1.0, -1.0]], device=device) + r = [identity, rot180] + # add random rotations and random almost orthonormal matrices + r.extend( + [ + torch.linalg.qr(identity + torch.randn_like(identity) * 1e-4)[0] + + float(i > batch_size // 2) * (0.5 - torch.rand_like(identity)) * 1e-3 + # this adds random noise to the second half + # of the random orthogonal matrices to generate + # near-orthogonal matrices + for i in range(batch_size - 2) + ] + ) + r = torch.stack(r) + r.requires_grad = True + # the log of the rotation matrix r + r_log = so3_log_map(r, cos_bound=1e-4, eps=1e-2) + # tests whether all outputs are finite + self.assertTrue(torch.isfinite(r_log).all()) + # tests whether the gradient is not None and all finite + loss = r.sum() + loss.backward() + self.assertIsNotNone(r.grad) + self.assertTrue(torch.isfinite(r.grad).all()) + + def test_so3_log_to_exp_to_log_to_exp(self, batch_size: int = 100): + """ + Check that + `so3_exp_map(so3_log_map(so3_exp_map(log_rot))) + == so3_exp_map(log_rot)` + for a randomly generated batch of rotation matrix logarithms `log_rot`. + Unlike `test_so3_log_to_exp_to_log`, this test checks the + correctness of converting a `log_rot` which contains values > math.pi. + """ + log_rot = 2.0 * TestSO3.init_log_rot(batch_size=batch_size) + # check also the singular cases where rot. angle = {0, 2pi} + log_rot[:2] = 0 + log_rot[1, 0] = 2.0 * math.pi - 1e-6 + rot = so3_exp_map(log_rot, eps=1e-4) + rot_ = so3_exp_map(so3_log_map(rot, eps=1e-4, cos_bound=1e-6), eps=1e-6) + self.assertClose(rot, rot_, atol=0.01) + angles = so3_relative_angle(rot, rot_, cos_bound=1e-6) + self.assertClose(angles, torch.zeros_like(angles), atol=0.01) + + def test_so3_log_to_exp_to_log(self, batch_size: int = 100): + """ + Check that `so3_log_map(so3_exp_map(log_rot))==log_rot` for + a randomly generated batch of rotation matrix logarithms `log_rot`. + """ + log_rot = TestSO3.init_log_rot(batch_size=batch_size) + # check also the singular cases where rot. angle = 0 + log_rot[:1] = 0 + log_rot_ = so3_log_map(so3_exp_map(log_rot)) + self.assertClose(log_rot, log_rot_, atol=1e-4) + + def test_so3_exp_to_log_to_exp(self, batch_size: int = 100): + """ + Check that `so3_exp_map(so3_log_map(R))==R` for + a batch of randomly generated rotation matrices `R`. + """ + rot = TestSO3.init_rot(batch_size=batch_size) + non_singular = (so3_rotation_angle(rot) - math.pi).abs() > 1e-2 + rot = rot[non_singular] + rot_ = so3_exp_map(so3_log_map(rot, eps=1e-8, cos_bound=1e-8), eps=1e-8) + self.assertClose(rot_, rot, atol=0.1) + angles = so3_relative_angle(rot, rot_, cos_bound=1e-4) + self.assertClose(angles, torch.zeros_like(angles), atol=0.1) + + def test_so3_cos_relative_angle(self, batch_size: int = 100): + """ + Check that `so3_relative_angle(R1, R2, cos_angle=False).cos()` + is the same as `so3_relative_angle(R1, R2, cos_angle=True)` for + batches of randomly generated rotation matrices `R1` and `R2`. + """ + rot1 = TestSO3.init_rot(batch_size=batch_size) + rot2 = TestSO3.init_rot(batch_size=batch_size) + angles = so3_relative_angle(rot1, rot2, cos_angle=False).cos() + angles_ = so3_relative_angle(rot1, rot2, cos_angle=True) + self.assertClose(angles, angles_, atol=1e-4) + + def test_so3_cos_angle(self, batch_size: int = 100): + """ + Check that `so3_rotation_angle(R, cos_angle=False).cos()` + is the same as `so3_rotation_angle(R, cos_angle=True)` for + a batch of randomly generated rotation matrices `R`. + """ + rot = TestSO3.init_rot(batch_size=batch_size) + angles = so3_rotation_angle(rot, cos_angle=False).cos() + angles_ = so3_rotation_angle(rot, cos_angle=True) + self.assertClose(angles, angles_, atol=1e-4) + + def test_so3_cos_bound(self, batch_size: int = 100): + """ + Checks that for an identity rotation `R=I`, the so3_rotation_angle returns + non-finite gradients when `cos_bound=None` and finite gradients + for `cos_bound > 0.0`. + """ + # generate random rotations with a tiny angle to generate cases + # with the gradient singularity + device = torch.device("cuda:0") + identity = torch.eye(3, device=device) + rot180 = identity * torch.tensor([[1.0, -1.0, -1.0]], device=device) + r = [identity, rot180] + r.extend( + [ + torch.linalg.qr(identity + torch.randn_like(identity) * 1e-4)[0] + for _ in range(batch_size - 2) + ] + ) + r = torch.stack(r) + r.requires_grad = True + for is_grad_finite in (True, False): + # clear the gradients and decide the cos_bound: + # for is_grad_finite we run so3_rotation_angle with cos_bound + # set to a small float, otherwise we set to 0.0 + r.grad = None + cos_bound = 1e-4 if is_grad_finite else 0.0 + # compute the angles of r + angles = so3_rotation_angle(r, cos_bound=cos_bound) + # tests whether all outputs are finite in both cases + self.assertTrue(torch.isfinite(angles).all()) + # compute the gradients + loss = angles.sum() + loss.backward() + # tests whether the gradient is not None for both cases + self.assertIsNotNone(r.grad) + if is_grad_finite: + # all grad values have to be finite + self.assertTrue(torch.isfinite(r.grad).all()) + + def test_scriptable(self): + torch.jit.script(so3_exp_map) + torch.jit.script(so3_log_map) + + @staticmethod + def so3_expmap(batch_size: int = 10): + log_rot = TestSO3.init_log_rot(batch_size=batch_size) + torch.cuda.synchronize() + + def compute_rots(): + so3_exp_map(log_rot) + torch.cuda.synchronize() + + return compute_rots + + @staticmethod + def so3_logmap(batch_size: int = 10): + log_rot = TestSO3.init_rot(batch_size=batch_size) + torch.cuda.synchronize() + + def compute_logs(): + so3_log_map(log_rot) + torch.cuda.synchronize() + + return compute_logs diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_struct_utils.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_struct_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..67b3b27bbff83205fc68de4e08cadfff70aafa75 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_struct_utils.py @@ -0,0 +1,226 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + + +import unittest + +import torch +from pytorch3d.structures import utils as struct_utils + +from .common_testing import TestCaseMixin + + +class TestStructUtils(TestCaseMixin, unittest.TestCase): + def setUp(self) -> None: + super().setUp() + torch.manual_seed(43) + + def _check_list_to_padded_slices(self, x, x_padded, ndim): + N = len(x) + for i in range(N): + slices = [i] + for dim in range(ndim): + if x[i].nelement() == 0 and x[i].ndim == 1: + slice_ = slice(0, 0, 1) + else: + slice_ = slice(0, x[i].shape[dim], 1) + slices.append(slice_) + if x[i].nelement() == 0 and x[i].ndim == 1: + x_correct = x[i].new_zeros(*[[0] * ndim]) + else: + x_correct = x[i] + self.assertClose(x_padded[slices], x_correct) + + def test_list_to_padded(self): + device = torch.device("cuda:0") + N = 5 + K = 20 + for ndim in [1, 2, 3, 4]: + x = [] + for _ in range(N): + dims = torch.randint(K, size=(ndim,)).tolist() + x.append(torch.rand(dims, device=device)) + + # set 0th element to an empty 1D tensor + x[0] = torch.tensor([], dtype=x[0].dtype, device=device) + + # set 1st element to an empty tensor with correct number of dims + x[1] = x[1].new_zeros(*[[0] * ndim]) + + pad_size = [K] * ndim + x_padded = struct_utils.list_to_padded( + x, pad_size=pad_size, pad_value=0.0, equisized=False + ) + + for dim in range(ndim): + self.assertEqual(x_padded.shape[dim + 1], K) + + self._check_list_to_padded_slices(x, x_padded, ndim) + + # check for no pad size (defaults to max dimension) + x_padded = struct_utils.list_to_padded(x, pad_value=0.0, equisized=False) + max_sizes = ( + max( + (0 if (y.nelement() == 0 and y.ndim == 1) else y.shape[dim]) + for y in x + ) + for dim in range(ndim) + ) + for dim, max_size in enumerate(max_sizes): + self.assertEqual(x_padded.shape[dim + 1], max_size) + + self._check_list_to_padded_slices(x, x_padded, ndim) + + # check for equisized + x = [torch.rand((K, *([10] * (ndim - 1))), device=device) for _ in range(N)] + x_padded = struct_utils.list_to_padded(x, equisized=True) + self.assertClose(x_padded, torch.stack(x, 0)) + + # catch ValueError for invalid dimensions + pad_size = [K] * (ndim + 1) + with self.assertRaisesRegex(ValueError, "Pad size must"): + struct_utils.list_to_padded( + x, pad_size=pad_size, pad_value=0.0, equisized=False + ) + + # invalid input tensor dimensions + x = [] + ndim = 3 + for _ in range(N): + dims = torch.randint(K, size=(ndim,)).tolist() + x.append(torch.rand(dims, device=device)) + pad_size = [K] * 2 + with self.assertRaisesRegex(ValueError, "Pad size must"): + x_padded = struct_utils.list_to_padded( + x, pad_size=pad_size, pad_value=0.0, equisized=False + ) + + def test_padded_to_list(self): + device = torch.device("cuda:0") + N = 5 + K = 20 + ndim = 2 + + for ndim in (2, 3, 4): + dims = [K] * ndim + x = torch.rand([N] + dims, device=device) + + x_list = struct_utils.padded_to_list(x) + for i in range(N): + self.assertClose(x_list[i], x[i]) + + split_size = torch.randint(1, K, size=(N, ndim)).unbind(0) + x_list = struct_utils.padded_to_list(x, split_size) + for i in range(N): + slices = [i] + for dim in range(ndim): + slices.append(slice(0, split_size[i][dim], 1)) + self.assertClose(x_list[i], x[slices]) + + # split size is a list of ints + split_size = [int(z) for z in torch.randint(1, K, size=(N,)).unbind(0)] + x_list = struct_utils.padded_to_list(x, split_size) + for i in range(N): + self.assertClose(x_list[i], x[i][: split_size[i]]) + + def test_padded_to_packed(self): + device = torch.device("cuda:0") + N = 5 + K = 20 + ndim = 2 + dims = [K] * ndim + x = torch.rand([N] + dims, device=device) + + # Case 1: no split_size or pad_value provided + # Check output is just the flattened input. + x_packed = struct_utils.padded_to_packed(x) + self.assertTrue(x_packed.shape == (x.shape[0] * x.shape[1], x.shape[2])) + self.assertClose(x_packed, x.reshape(-1, K)) + + # Case 2: pad_value is provided. + # Check each section of the packed tensor matches the + # corresponding unpadded elements of the padded tensor. + # Check that only rows where all the values are padded + # are removed in the conversion to packed. + pad_value = -1 + x_list = [] + split_size = [] + for _ in range(N): + dim = torch.randint(K, size=(1,)).item() + # Add some random values in the input which are the same as the pad_value. + # These should not be filtered out. + x_list.append( + torch.randint(low=pad_value, high=10, size=(dim, K), device=device) + ) + split_size.append(dim) + x_padded = struct_utils.list_to_padded(x_list, pad_value=pad_value) + x_packed = struct_utils.padded_to_packed(x_padded, pad_value=pad_value) + curr = 0 + for i in range(N): + self.assertClose(x_packed[curr : curr + split_size[i], ...], x_list[i]) + self.assertClose(torch.cat(x_list), x_packed) + curr += split_size[i] + + # Case 3: split_size is provided. + # Check each section of the packed tensor matches the corresponding + # unpadded elements. + x_packed = struct_utils.padded_to_packed(x_padded, split_size=split_size) + curr = 0 + for i in range(N): + self.assertClose(x_packed[curr : curr + split_size[i], ...], x_list[i]) + self.assertClose(torch.cat(x_list), x_packed) + curr += split_size[i] + + # Case 4: split_size of the wrong shape is provided. + # Raise an error. + split_size = torch.randint(1, K, size=(2 * N,)).view(N, 2).unbind(0) + with self.assertRaisesRegex(ValueError, "1-dimensional"): + x_packed = struct_utils.padded_to_packed(x_padded, split_size=split_size) + + split_size = torch.randint(1, K, size=(2 * N,)).view(N * 2).tolist() + with self.assertRaisesRegex( + ValueError, "same length as inputs first dimension" + ): + x_packed = struct_utils.padded_to_packed(x_padded, split_size=split_size) + + # Case 5: both pad_value and split_size are provided. + # Raise an error. + with self.assertRaisesRegex(ValueError, "Only one of"): + x_packed = struct_utils.padded_to_packed( + x_padded, split_size=split_size, pad_value=-1 + ) + + # Case 6: Input has more than 3 dims. + # Raise an error. + x = torch.rand((N, K, K, K, K), device=device) + split_size = torch.randint(1, K, size=(N,)).tolist() + with self.assertRaisesRegex(ValueError, "Supports only"): + struct_utils.padded_to_packed(x, split_size=split_size) + + def test_list_to_packed(self): + device = torch.device("cuda:0") + N = 5 + K = 20 + x, x_dims = [], [] + dim2 = torch.randint(K, size=(1,)).item() + for _ in range(N): + dim1 = torch.randint(K, size=(1,)).item() + x_dims.append(dim1) + x.append(torch.rand([dim1, dim2], device=device)) + + out = struct_utils.list_to_packed(x) + x_packed = out[0] + num_items = out[1] + item_packed_first_idx = out[2] + item_packed_to_list_idx = out[3] + + cur = 0 + for i in range(N): + self.assertTrue(num_items[i] == x_dims[i]) + self.assertTrue(item_packed_first_idx[i] == cur) + self.assertTrue(item_packed_to_list_idx[cur : cur + x_dims[i]].eq(i).all()) + self.assertClose(x_packed[cur : cur + x_dims[i]], x[i]) + cur += x_dims[i] diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_symeig3x3.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_symeig3x3.py new file mode 100644 index 0000000000000000000000000000000000000000..29a2f955915dd478698f2fa0ea817ad1f687058d --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_symeig3x3.py @@ -0,0 +1,264 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + + +import unittest + +import torch +from pytorch3d.common.workaround import symeig3x3 +from pytorch3d.transforms.rotation_conversions import random_rotations + +from .common_testing import get_random_cuda_device, TestCaseMixin + + +class TestSymEig3x3(TestCaseMixin, unittest.TestCase): + TEST_BATCH_SIZE = 1024 + + @staticmethod + def create_random_sym3x3(device, n): + random_3x3 = torch.randn((n, 3, 3), device=device) + random_3x3_T = torch.transpose(random_3x3, 1, 2) + random_sym_3x3 = (random_3x3 * random_3x3_T).contiguous() + + return random_sym_3x3 + + @staticmethod + def create_diag_sym3x3(device, n, noise=0.0): + # Create purly diagonal matrices + random_diag_3x3 = torch.randn((n, 3), device=device).diag_embed() + + # Make them 'almost' diagonal + random_diag_3x3 += noise * TestSymEig3x3.create_random_sym3x3(device, n) + + return random_diag_3x3 + + def setUp(self) -> None: + super().setUp() + torch.manual_seed(42) + + self._gpu = get_random_cuda_device() + self._cpu = torch.device("cpu") + + def test_is_eigen_gpu(self): + test_input = self.create_random_sym3x3(self._gpu, n=self.TEST_BATCH_SIZE) + + self._test_is_eigen(test_input) + + def test_is_eigen_cpu(self): + test_input = self.create_random_sym3x3(self._cpu, n=self.TEST_BATCH_SIZE) + + self._test_is_eigen(test_input) + + def _test_is_eigen(self, test_input, atol=1e-04, rtol=1e-02): + """ + Verify that values and vectors produced are really eigenvalues and eigenvectors + and can restore the original input matrix with good precision + """ + eigenvalues, eigenvectors = symeig3x3(test_input, eigenvectors=True) + + self.assertClose( + test_input, + eigenvectors @ eigenvalues.diag_embed() @ eigenvectors.transpose(-2, -1), + atol=atol, + rtol=rtol, + ) + + def test_eigenvectors_are_orthonormal_gpu(self): + test_input = self.create_random_sym3x3(self._gpu, n=self.TEST_BATCH_SIZE) + + self._test_eigenvectors_are_orthonormal(test_input) + + def test_eigenvectors_are_orthonormal_cpu(self): + test_input = self.create_random_sym3x3(self._cpu, n=self.TEST_BATCH_SIZE) + + self._test_eigenvectors_are_orthonormal(test_input) + + def _test_eigenvectors_are_orthonormal(self, test_input): + """ + Verify that eigenvectors are an orthonormal set + """ + eigenvalues, eigenvectors = symeig3x3(test_input, eigenvectors=True) + + batched_eye = torch.zeros_like(test_input) + batched_eye[..., :, :] = torch.eye(3, device=batched_eye.device) + + self.assertClose( + batched_eye, eigenvectors @ eigenvectors.transpose(-2, -1), atol=1e-06 + ) + + def test_is_not_nan_or_inf_gpu(self): + test_input = self.create_random_sym3x3(self._gpu, n=self.TEST_BATCH_SIZE) + + self._test_is_not_nan_or_inf(test_input) + + def test_is_not_nan_or_inf_cpu(self): + test_input = self.create_random_sym3x3(self._cpu, n=self.TEST_BATCH_SIZE) + + self._test_is_not_nan_or_inf(test_input) + + def _test_is_not_nan_or_inf(self, test_input): + eigenvalues, eigenvectors = symeig3x3(test_input, eigenvectors=True) + + self.assertTrue(torch.isfinite(eigenvalues).all()) + self.assertTrue(torch.isfinite(eigenvectors).all()) + + def test_degenerate_inputs_gpu(self): + self._test_degenerate_inputs(self._gpu) + + def test_degenerate_inputs_cpu(self): + self._test_degenerate_inputs(self._cpu) + + def _test_degenerate_inputs(self, device): + """ + Test degenerate case when input matrices are diagonal or near-diagonal + """ + + # Purely diagonal case + test_input = self.create_diag_sym3x3(device, self.TEST_BATCH_SIZE) + + self._test_is_not_nan_or_inf(test_input) + self._test_is_eigen(test_input) + self._test_eigenvectors_are_orthonormal(test_input) + + # Almost-diagonal case + test_input = self.create_diag_sym3x3(device, self.TEST_BATCH_SIZE, noise=1e-4) + + self._test_is_not_nan_or_inf(test_input) + self._test_is_eigen(test_input) + self._test_eigenvectors_are_orthonormal(test_input) + + def test_gradients_cpu(self): + self._test_gradients(self._cpu) + + def test_gradients_gpu(self): + self._test_gradients(self._gpu) + + def _test_gradients(self, device): + """ + Tests if gradients pass though without any problems (infs, nans etc) and + also performs gradcheck (compares numerical and analytical gradients) + """ + test_random_input = self.create_random_sym3x3(device, n=16) + test_diag_input = self.create_diag_sym3x3(device, n=16) + test_almost_diag_input = self.create_diag_sym3x3(device, n=16, noise=1e-4) + + test_input = torch.cat( + (test_random_input, test_diag_input, test_almost_diag_input) + ) + test_input.requires_grad = True + + with torch.autograd.detect_anomaly(): + eigenvalues, eigenvectors = symeig3x3(test_input, eigenvectors=True) + + loss = eigenvalues.mean() + eigenvectors.mean() + loss.backward() + + test_random_input.requires_grad = True + # Inputs are converted to double to increase the precision of gradcheck. + torch.autograd.gradcheck( + symeig3x3, test_random_input.double(), eps=1e-6, atol=1e-2, rtol=1e-2 + ) + + def _test_eigenvalues_and_eigenvectors( + self, test_eigenvectors, test_eigenvalues, atol=1e-04, rtol=1e-04 + ): + test_input = ( + test_eigenvectors.transpose(-2, -1) + @ test_eigenvalues.diag_embed() + @ test_eigenvectors + ) + + test_eigenvalues_sorted, _ = torch.sort(test_eigenvalues, dim=-1) + + eigenvalues, eigenvectors = symeig3x3(test_input, eigenvectors=True) + + self.assertClose( + test_eigenvalues_sorted, + eigenvalues, + atol=atol, + rtol=rtol, + ) + + self._test_is_not_nan_or_inf(test_input) + self._test_is_eigen(test_input, atol=atol, rtol=rtol) + self._test_eigenvectors_are_orthonormal(test_input) + + def test_degenerate_eigenvalues_gpu(self): + self._test_degenerate_eigenvalues(self._gpu) + + def test_degenerate_eigenvalues_cpu(self): + self._test_degenerate_eigenvalues(self._cpu) + + def _test_degenerate_eigenvalues(self, device): + """ + Test degenerate eigenvalues like zero-valued and with 2-/3-multiplicity + """ + # Error tolerances for degenerate values are increased as things might become + # numerically unstable + deg_atol = 1e-3 + deg_rtol = 1.0 + + # Construct random orthonormal sets + test_eigenvecs = random_rotations(n=self.TEST_BATCH_SIZE, device=device) + + # Construct random eigenvalues + test_eigenvals = torch.randn( + (self.TEST_BATCH_SIZE, 3), device=test_eigenvecs.device + ) + self._test_eigenvalues_and_eigenvectors( + test_eigenvecs, test_eigenvals, atol=deg_atol, rtol=deg_rtol + ) + + # First eigenvalue is always 0.0 here: [0.0 X Y] + test_eigenvals_with_zero = test_eigenvals.clone() + test_eigenvals_with_zero[..., 0] = 0.0 + self._test_eigenvalues_and_eigenvectors( + test_eigenvecs, test_eigenvals_with_zero, atol=deg_atol, rtol=deg_rtol + ) + + # First two eigenvalues are always the same here: [X X Y] + test_eigenvals_with_multiplicity2 = test_eigenvals.clone() + test_eigenvals_with_multiplicity2[..., 1] = test_eigenvals_with_multiplicity2[ + ..., 0 + ] + self._test_eigenvalues_and_eigenvectors( + test_eigenvecs, + test_eigenvals_with_multiplicity2, + atol=deg_atol, + rtol=deg_rtol, + ) + + # All three eigenvalues are the same here: [X X X] + test_eigenvals_with_multiplicity3 = test_eigenvals_with_multiplicity2.clone() + test_eigenvals_with_multiplicity3[..., 2] = test_eigenvals_with_multiplicity2[ + ..., 0 + ] + self._test_eigenvalues_and_eigenvectors( + test_eigenvecs, + test_eigenvals_with_multiplicity3, + atol=deg_atol, + rtol=deg_rtol, + ) + + def test_more_dimensions(self): + """ + Tests if function supports arbitrary leading dimensions + """ + repeat = 4 + + test_input = self.create_random_sym3x3(self._cpu, n=16) + test_input_4d = test_input[None, ...].expand((repeat,) + test_input.shape) + + eigenvalues, eigenvectors = symeig3x3(test_input, eigenvectors=True) + eigenvalues_4d, eigenvectors_4d = symeig3x3(test_input_4d, eigenvectors=True) + + eigenvalues_4d_gt = eigenvalues[None, ...].expand((repeat,) + eigenvalues.shape) + eigenvectors_4d_gt = eigenvectors[None, ...].expand( + (repeat,) + eigenvectors.shape + ) + + self.assertClose(eigenvalues_4d_gt, eigenvalues_4d) + self.assertClose(eigenvectors_4d_gt, eigenvectors_4d) diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_volumes.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_volumes.py new file mode 100644 index 0000000000000000000000000000000000000000..23cbe323b28e1c79ab86c4cb3672f8c6862a27c2 --- /dev/null +++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/pytorch3d/tests/test_volumes.py @@ -0,0 +1,966 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import copy +import itertools +import random +import unittest + +import numpy as np +import torch +from pytorch3d.structures.volumes import VolumeLocator, Volumes +from pytorch3d.transforms import Scale + +from .common_testing import TestCaseMixin + + +class TestVolumes(TestCaseMixin, unittest.TestCase): + def setUp(self) -> None: + np.random.seed(42) + torch.manual_seed(42) + random.seed(42) + + @staticmethod + def _random_volume_list( + num_volumes, min_size, max_size, num_channels, device, rand_sizes=None + ): + """ + Init a list of `num_volumes` random tensors of size [num_channels, *rand_size]. + If `rand_sizes` is None, rand_size is a 3D long vector sampled + from [min_size, max_size]. Otherwise, rand_size should be a list + [rand_size_1, rand_size_2, ..., rand_size_num_volumes] where each + `rand_size_i` denotes the size of the corresponding `i`-th tensor. + """ + if rand_sizes is None: + rand_sizes = [ + [random.randint(min_size, vs) for vs in max_size] + for _ in range(num_volumes) + ] + + volume_list = [ + torch.randn( + size=[num_channels, *rand_size], device=device, dtype=torch.float32 + ) + for rand_size in rand_sizes + ] + + return volume_list, rand_sizes + + def _check_indexed_volumes(self, v, selected, indices): + for selectedIdx, index in indices: + self.assertClose(selected.densities()[selectedIdx], v.densities()[index]) + self.assertClose( + v.locator._local_to_world_transform.get_matrix()[index], + selected.locator._local_to_world_transform.get_matrix()[selectedIdx], + ) + if selected.features() is not None: + self.assertClose(selected.features()[selectedIdx], v.features()[index]) + + def test_get_item( + self, + num_volumes=5, + num_channels=4, + volume_size=(10, 13, 8), + dtype=torch.float32, + ): + device = torch.device("cuda:0") + + # make sure we have at least 3 volumes to prevent indexing crash + num_volumes = max(num_volumes, 3) + + features = torch.randn( + size=[num_volumes, num_channels, *volume_size], + device=device, + dtype=torch.float32, + ) + densities = torch.randn( + size=[num_volumes, 1, *volume_size], device=device, dtype=torch.float32 + ) + + features_list, rand_sizes = TestVolumes._random_volume_list( + num_volumes, 3, volume_size, num_channels, device + ) + densities_list, _ = TestVolumes._random_volume_list( + num_volumes, 3, volume_size, 1, device, rand_sizes=rand_sizes + ) + + volume_translation = -torch.randn(num_volumes, 3).type_as(features) + voxel_size = torch.rand(num_volumes, 1).type_as(features) + 0.5 + + for features_, densities_ in zip( + (None, features, features_list), (densities, densities, densities_list) + ): + # init the volume structure + v = Volumes( + features=features_, + densities=densities_, + volume_translation=volume_translation, + voxel_size=voxel_size, + ) + + # int index + index = 1 + v_selected = v[index] + self.assertEqual(len(v_selected), 1) + self._check_indexed_volumes(v, v_selected, [(0, 1)]) + + # list index + index = [1, 2] + v_selected = v[index] + self.assertEqual(len(v_selected), len(index)) + self._check_indexed_volumes(v, v_selected, enumerate(index)) + + # slice index + index = slice(0, 2, 1) + v_selected = v[0:2] + self.assertEqual(len(v_selected), 2) + self._check_indexed_volumes(v, v_selected, [(0, 0), (1, 1)]) + + # bool tensor + index = (torch.rand(num_volumes) > 0.5).to(device) + index[:2] = True # make sure smth is selected + v_selected = v[index] + self.assertEqual(len(v_selected), index.sum()) + self._check_indexed_volumes( + v, + v_selected, + zip( + torch.arange(index.sum()), + torch.nonzero(index, as_tuple=False).squeeze(), + ), + ) + + # int tensor + index = torch.tensor([1, 2], dtype=torch.int64, device=device) + v_selected = v[index] + self.assertEqual(len(v_selected), index.numel()) + self._check_indexed_volumes(v, v_selected, enumerate(index.tolist())) + + # invalid index + index = torch.tensor([1, 0, 1], dtype=torch.float32, device=device) + with self.assertRaises(IndexError): + v_selected = v[index] + index = 1.2 # floating point index + with self.assertRaises(IndexError): + v_selected = v[index] + + def test_locator_init(self, batch_size=9, resolution=(3, 5, 7)): + with self.subTest("VolumeLocator init with all sizes equal"): + grid_sizes = [resolution for _ in range(batch_size)] + locator_tuple = VolumeLocator( + batch_size=batch_size, grid_sizes=resolution, device=torch.device("cpu") + ) + locator_list = VolumeLocator( + batch_size=batch_size, grid_sizes=grid_sizes, device=torch.device("cpu") + ) + locator_tensor = VolumeLocator( + batch_size=batch_size, + grid_sizes=torch.tensor(grid_sizes), + device=torch.device("cpu"), + ) + expected_grid_sizes = torch.tensor(grid_sizes) + expected_resolution = resolution + assert torch.allclose(expected_grid_sizes, locator_tuple._grid_sizes) + assert torch.allclose(expected_grid_sizes, locator_list._grid_sizes) + assert torch.allclose(expected_grid_sizes, locator_tensor._grid_sizes) + self.assertEqual(expected_resolution, locator_tuple._resolution) + self.assertEqual(expected_resolution, locator_list._resolution) + self.assertEqual(expected_resolution, locator_tensor._resolution) + + with self.subTest("VolumeLocator with different sizes in different grids"): + grid_sizes_list = [ + torch.randint(low=1, high=42, size=(3,)) for _ in range(batch_size) + ] + grid_sizes_tensor = torch.cat([el[None] for el in grid_sizes_list]) + locator_list = VolumeLocator( + batch_size=batch_size, + grid_sizes=grid_sizes_list, + device=torch.device("cpu"), + ) + locator_tensor = VolumeLocator( + batch_size=batch_size, + grid_sizes=grid_sizes_tensor, + device=torch.device("cpu"), + ) + expected_grid_sizes = grid_sizes_tensor + expected_resolution = tuple(torch.max(expected_grid_sizes, dim=0).values) + assert torch.allclose(expected_grid_sizes, locator_list._grid_sizes) + assert torch.allclose(expected_grid_sizes, locator_tensor._grid_sizes) + self.assertEqual(expected_resolution, locator_list._resolution) + self.assertEqual(expected_resolution, locator_tensor._resolution) + + def test_coord_transforms(self, num_volumes=3, num_channels=4, dtype=torch.float32): + """ + Test the correctness of the conversion between the internal + Transform3D Volumes.VolumeLocator._local_to_world_transform and the initialization + from the translation and voxel_size. + """ + + device = torch.device("cuda:0") + + # try for 10 sets of different random sizes/centers/voxel_sizes + for _ in range(10): + size = torch.randint(high=10, size=(3,), low=3).tolist() + + densities = torch.randn( + size=[num_volumes, num_channels, *size], + device=device, + dtype=torch.float32, + ) + + # init the transformation params + volume_translation = torch.randn(num_volumes, 3) + voxel_size = torch.rand(num_volumes, 3) * 3.0 + 0.5 + + # get the corresponding Transform3d object + local_offset = torch.tensor(list(size), dtype=torch.float32, device=device)[ + [2, 1, 0] + ][None].repeat(num_volumes, 1) + local_to_world_transform = ( + Scale(0.5 * local_offset - 0.5, device=device) + .scale(voxel_size) + .translate(-volume_translation) + ) + + # init the volume structures with the scale and translation, + # then get the coord grid in world coords + v_trans_vs = Volumes( + densities=densities, + voxel_size=voxel_size, + volume_translation=volume_translation, + ) + grid_rot_trans_vs = v_trans_vs.get_coord_grid(world_coordinates=True) + + # map the default local coords to the world coords + # with local_to_world_transform + v_default = Volumes(densities=densities) + grid_default_local = v_default.get_coord_grid(world_coordinates=False) + grid_default_world = local_to_world_transform.transform_points( + grid_default_local.view(num_volumes, -1, 3) + ).view(num_volumes, *size, 3) + + # check that both grids are the same + self.assertClose(grid_rot_trans_vs, grid_default_world, atol=1e-5) + + # check that the transformations are the same + self.assertClose( + v_trans_vs.get_local_to_world_coords_transform().get_matrix(), + local_to_world_transform.get_matrix(), + atol=1e-5, + ) + + def test_coord_grid_convention( + self, num_volumes=3, num_channels=4, dtype=torch.float32 + ): + """ + Check that for a trivial volume with spatial size DxHxW=5x7x5: + 1) xyz_world=(0, 0, 0) lands right in the middle of the volume + with xyz_local=(0, 0, 0). + 2) xyz_world=(-2, 3, 2) results in xyz_local=(-1, 1, -1). + 3) The centeral voxel of the volume coordinate grid + has coords x_world=(0, 0, 0) and x_local=(0, 0, 0) + 4) grid_sampler(world_coordinate_grid, local_coordinate_grid) + is the same as world_coordinate_grid itself. I.e. the local coordinate + grid matches the grid_sampler coordinate convention. + """ + + device = torch.device("cuda:0") + + densities = torch.randn( + size=[num_volumes, num_channels, 5, 7, 5], + device=device, + dtype=torch.float32, + ) + v_trivial = Volumes(densities=densities) + + # check the case with x_world=(0,0,0) + pts_world = torch.zeros(num_volumes, 1, 3, device=device, dtype=torch.float32) + pts_local = v_trivial.world_to_local_coords(pts_world) + pts_local_expected = torch.zeros_like(pts_local) + self.assertClose(pts_local, pts_local_expected) + + # check the case with x_world=(-2, 3, -2) + pts_world = torch.tensor([-2, 3, -2], device=device, dtype=torch.float32)[ + None, None + ].repeat(num_volumes, 1, 1) + pts_local = v_trivial.world_to_local_coords(pts_world) + pts_local_expected = torch.tensor( + [-1, 1, -1], device=device, dtype=torch.float32 + )[None, None].repeat(num_volumes, 1, 1) + self.assertClose(pts_local, pts_local_expected) + + # check that the central voxel has coords x_world=(0, 0, 0) and x_local(0, 0, 0) + grid_world = v_trivial.get_coord_grid(world_coordinates=True) + grid_local = v_trivial.get_coord_grid(world_coordinates=False) + for grid in (grid_world, grid_local): + x0 = grid[0, :, :, 2, 0] + y0 = grid[0, :, 3, :, 1] + z0 = grid[0, 2, :, :, 2] + for coord_line in (x0, y0, z0): + self.assertClose(coord_line, torch.zeros_like(coord_line), atol=1e-7) + + # resample grid_world using grid_sampler with local coords + # -> make sure the resampled version is the same as original + grid_world_resampled = torch.nn.functional.grid_sample( + grid_world.permute(0, 4, 1, 2, 3), grid_local, align_corners=True + ).permute(0, 2, 3, 4, 1) + self.assertClose(grid_world_resampled, grid_world, atol=1e-7) + + for align_corners in [True, False]: + v_trivial = Volumes(densities=densities, align_corners=align_corners) + + # check the case with x_world=(0,0,0) + pts_world = torch.zeros( + num_volumes, 1, 3, device=device, dtype=torch.float32 + ) + pts_local = v_trivial.world_to_local_coords(pts_world) + pts_local_expected = torch.zeros_like(pts_local) + self.assertClose(pts_local, pts_local_expected) + + # check the case with x_world=(-2, 3, -2) + pts_world_tuple = [-2, 3, -2] + pts_world = torch.tensor( + pts_world_tuple, device=device, dtype=torch.float32 + )[None, None].repeat(num_volumes, 1, 1) + pts_local = v_trivial.world_to_local_coords(pts_world) + pts_local_expected = torch.tensor( + [-1, 1, -1], device=device, dtype=torch.float32 + )[None, None].repeat(num_volumes, 1, 1) + self.assertClose(pts_local, pts_local_expected) + + # # check that the central voxel has coords x_world=(0, 0, 0) and x_local(0, 0, 0) + grid_world = v_trivial.get_coord_grid(world_coordinates=True) + grid_local = v_trivial.get_coord_grid(world_coordinates=False) + for grid in (grid_world, grid_local): + x0 = grid[0, :, :, 2, 0] + y0 = grid[0, :, 3, :, 1] + z0 = grid[0, 2, :, :, 2] + for coord_line in (x0, y0, z0): + self.assertClose( + coord_line, torch.zeros_like(coord_line), atol=1e-7 + ) + + # resample grid_world using grid_sampler with local coords + # -> make sure the resampled version is the same as original + grid_world_resampled = torch.nn.functional.grid_sample( + grid_world.permute(0, 4, 1, 2, 3), + grid_local, + align_corners=align_corners, + ).permute(0, 2, 3, 4, 1) + self.assertClose(grid_world_resampled, grid_world, atol=1e-7) + + def test_coord_grid_convention_heterogeneous( + self, num_channels=4, dtype=torch.float32 + ): + """ + Check that for a list of 2 trivial volumes with + spatial sizes DxHxW=(5x7x5, 3x5x5): + 1) xyz_world=(0, 0, 0) lands right in the middle of the volume + with xyz_local=(0, 0, 0). + 2) xyz_world=((-2, 3, -2), (-2, -2, 1)) results + in xyz_local=((-1, 1, -1), (-1, -1, 1)). + 3) The centeral voxel of the volume coordinate grid + has coords x_world=(0, 0, 0) and x_local=(0, 0, 0) + 4) grid_sampler(world_coordinate_grid, local_coordinate_grid) + is the same as world_coordinate_grid itself. I.e. the local coordinate + grid matches the grid_sampler coordinate convention. + """ + + device = torch.device("cuda:0") + + sizes = [(5, 7, 5), (3, 5, 5)] + + densities_list = [ + torch.randn(size=[num_channels, *size], device=device, dtype=torch.float32) + for size in sizes + ] + + # init the volume + v_trivial = Volumes(densities=densities_list) + + # check the border point locations + pts_world = torch.tensor( + [[-2.0, 3.0, -2.0], [-2.0, -2.0, 1.0]], device=device, dtype=torch.float32 + )[:, None] + pts_local = v_trivial.world_to_local_coords(pts_world) + pts_local_expected = torch.tensor( + [[-1.0, 1.0, -1.0], [-1.0, -1.0, 1.0]], device=device, dtype=torch.float32 + )[:, None] + self.assertClose(pts_local, pts_local_expected) + + # check that the central voxel has coords x_world=(0, 0, 0) and x_local(0, 0, 0) + grid_world = v_trivial.get_coord_grid(world_coordinates=True) + grid_local = v_trivial.get_coord_grid(world_coordinates=False) + for grid in (grid_world, grid_local): + x0 = grid[0, :, :, 2, 0] + y0 = grid[0, :, 3, :, 1] + z0 = grid[0, 2, :, :, 2] + for coord_line in (x0, y0, z0): + self.assertClose(coord_line, torch.zeros_like(coord_line), atol=1e-7) + x0 = grid[1, :, :, 2, 0] + y0 = grid[1, :, 2, :, 1] + z0 = grid[1, 1, :, :, 2] + for coord_line in (x0, y0, z0): + self.assertClose(coord_line, torch.zeros_like(coord_line), atol=1e-7) + + # resample grid_world using grid_sampler with local coords + # -> make sure the resampled version is the same as original + for grid_world_, grid_local_, size in zip(grid_world, grid_local, sizes): + grid_world_crop = grid_world_[: size[0], : size[1], : size[2], :][None] + grid_local_crop = grid_local_[: size[0], : size[1], : size[2], :][None] + grid_world_crop_resampled = torch.nn.functional.grid_sample( + grid_world_crop.permute(0, 4, 1, 2, 3), + grid_local_crop, + align_corners=True, + ).permute(0, 2, 3, 4, 1) + self.assertClose(grid_world_crop_resampled, grid_world_crop, atol=1e-7) + + def test_coord_grid_transforms( + self, num_volumes=3, num_channels=4, dtype=torch.float32 + ): + """ + Test whether conversion between local-world coordinates of the + volume returns correct results. + """ + + device = torch.device("cuda:0") + + # try for 10 sets of different random sizes/centers/voxel_sizes + for _ in range(10): + size = torch.randint(high=10, size=(3,), low=3).tolist() + + center = torch.randn(num_volumes, 3, dtype=torch.float32, device=device) + voxel_size = torch.rand(1, dtype=torch.float32, device=device) * 5.0 + 0.5 + + for densities in ( + torch.randn( + size=[num_volumes, num_channels, *size], + device=device, + dtype=torch.float32, + ), + TestVolumes._random_volume_list( + num_volumes, 3, size, num_channels, device, rand_sizes=None + )[0], + ): + # init the volume structure + v = Volumes( + densities=densities, + voxel_size=voxel_size, + volume_translation=-center, + ) + + # get local coord grid + grid_local = v.get_coord_grid(world_coordinates=False) + + # convert from world to local to world + grid_world = v.get_coord_grid(world_coordinates=True) + grid_local_2 = v.world_to_local_coords(grid_world) + grid_world_2 = v.local_to_world_coords(grid_local_2) + + # assertions on shape and values of grid_world and grid_local + self.assertClose(grid_world, grid_world_2, atol=1e-5) + self.assertClose(grid_local, grid_local_2, atol=1e-5) + + # check that the individual slices of the location grid have + # constant values along expected dimensions + for plane_dim in (1, 2, 3): + for grid_plane in grid_world.split(1, dim=plane_dim): + grid_coord_dim = {1: 2, 2: 1, 3: 0}[plane_dim] + grid_coord_plane = grid_plane.squeeze()[..., grid_coord_dim] + # check that all elements of grid_coord_plane are + # the same for each batch element + self.assertClose( + grid_coord_plane.reshape(num_volumes, -1).max(dim=1).values, + grid_coord_plane.reshape(num_volumes, -1).min(dim=1).values, + ) + + def test_clone( + self, num_volumes=3, num_channels=4, size=(6, 8, 10), dtype=torch.float32 + ): + """ + Test cloning of a `Volumes` object + """ + + device = torch.device("cuda:0") + + features = torch.randn( + size=[num_volumes, num_channels, *size], device=device, dtype=torch.float32 + ) + densities = torch.rand( + size=[num_volumes, 1, *size], device=device, dtype=torch.float32 + ) + + for has_features in (True, False): + v = Volumes( + densities=densities, features=features if has_features else None + ) + vnew = v.clone() + vnew._densities.data[0, 0, 0, 0, 0] += 1.0 + self.assertNotAlmostEqual( + float( + (vnew.densities()[0, 0, 0, 0, 0] - v.densities()[0, 0, 0, 0, 0]) + .abs() + .max() + ), + 0.0, + ) + + if has_features: + vnew._features.data[0, 0, 0, 0, 0] += 1.0 + self.assertNotAlmostEqual( + float( + (vnew.features()[0, 0, 0, 0, 0] - v.features()[0, 0, 0, 0, 0]) + .abs() + .max() + ), + 0.0, + ) + + def _check_vars_on_device(self, v, desired_device): + for var_name, var in vars(v).items(): + if var_name != "device": + if var is not None: + self.assertTrue( + var.device.type == desired_device.type, + (var_name, var.device, desired_device), + ) + else: + self.assertTrue(var.type == desired_device.type) + + def test_to( + self, num_volumes=3, num_channels=4, size=(6, 8, 10), dtype=torch.float32 + ): + """ + Test the moving of the volumes from/to gpu and cpu + """ + + features = torch.randn( + size=[num_volumes, num_channels, *size], dtype=torch.float32 + ) + densities = torch.rand(size=[num_volumes, 1, *size], dtype=dtype) + volumes = Volumes(densities=densities, features=features) + locator = VolumeLocator( + batch_size=5, grid_sizes=(3, 5, 7), device=volumes.device + ) + + for name, obj in (("VolumeLocator", locator), ("Volumes", volumes)): + with self.subTest(f"Moving {name} from/to gpu and cpu"): + # Test support for str and torch.device + cpu_device = torch.device("cpu") + + converted_obj = obj.to("cpu") + self.assertEqual(cpu_device, converted_obj.device) + self.assertEqual(cpu_device, obj.device) + self.assertIs(obj, converted_obj) + + converted_obj = obj.to(cpu_device) + self.assertEqual(cpu_device, converted_obj.device) + self.assertEqual(cpu_device, obj.device) + self.assertIs(obj, converted_obj) + + cuda_device = torch.device("cuda:0") + + converted_obj = obj.to("cuda:0") + self.assertEqual(cuda_device, converted_obj.device) + self.assertEqual(cpu_device, obj.device) + self.assertIsNot(obj, converted_obj) + + converted_obj = obj.to(cuda_device) + self.assertEqual(cuda_device, converted_obj.device) + self.assertEqual(cpu_device, obj.device) + self.assertIsNot(obj, converted_obj) + + with self.subTest("Test device placement of internal tensors of Volumes"): + features = features.to(cuda_device) + densities = features.to(cuda_device) + + for features_ in (features, None): + volumes = Volumes(densities=densities, features=features_) + + cpu_volumes = volumes.cpu() + cuda_volumes = cpu_volumes.cuda() + cuda_volumes2 = cuda_volumes.cuda() + cpu_volumes2 = cuda_volumes2.cpu() + + for volumes1, volumes2 in itertools.combinations( + (volumes, cpu_volumes, cpu_volumes2, cuda_volumes, cuda_volumes2), 2 + ): + if volumes1 is cuda_volumes and volumes2 is cuda_volumes2: + # checks that we do not copy if the devices stay the same + assert_fun = self.assertIs + else: + assert_fun = self.assertSeparate + assert_fun(volumes1._densities, volumes2._densities) + if features_ is not None: + assert_fun(volumes1._features, volumes2._features) + for volumes_ in (volumes1, volumes2): + if volumes_ in (cpu_volumes, cpu_volumes2): + self._check_vars_on_device(volumes_, cpu_device) + else: + self._check_vars_on_device(volumes_, cuda_device) + + with self.subTest("Test device placement of internal tensors of VolumeLocator"): + for device1, device2 in itertools.combinations( + (torch.device("cpu"), torch.device("cuda:0")), 2 + ): + locator = locator.to(device1) + locator = locator.to(device2) + self.assertEqual(locator._grid_sizes.device, device2) + self.assertEqual(locator._local_to_world_transform.device, device2) + + def _check_padded(self, x_pad, x_list, grid_sizes): + """ + Check that padded tensors x_pad are the same as x_list tensors. + """ + num_volumes = len(x_list) + for i in range(num_volumes): + self.assertClose( + x_pad[i][:, : grid_sizes[i][0], : grid_sizes[i][1], : grid_sizes[i][2]], + x_list[i], + ) + + def test_feature_density_setters(self): + """ + Tests getters and setters for padded/list representations. + """ + + device = torch.device("cuda:0") + diff_device = torch.device("cpu") + + num_volumes = 30 + num_channels = 4 + K = 20 + + densities = [] + features = [] + grid_sizes = [] + diff_grid_sizes = [] + + for _ in range(num_volumes): + grid_size = torch.randint(K - 1, size=(3,)).long() + 1 + densities.append( + torch.rand((1, *grid_size), device=device, dtype=torch.float32) + ) + features.append( + torch.rand( + (num_channels, *grid_size), device=device, dtype=torch.float32 + ) + ) + grid_sizes.append(grid_size) + + diff_grid_size = ( + copy.deepcopy(grid_size) + torch.randint(2, size=(3,)).long() + 1 + ) + diff_grid_sizes.append(diff_grid_size) + grid_sizes = torch.stack(grid_sizes).to(device) + diff_grid_sizes = torch.stack(diff_grid_sizes).to(device) + + volumes = Volumes(densities=densities, features=features) + self.assertClose(volumes.get_grid_sizes(), grid_sizes) + + # test the getters + features_padded = volumes.features() + densities_padded = volumes.densities() + features_list = volumes.features_list() + densities_list = volumes.densities_list() + for x_pad, x_list in zip( + (densities_padded, features_padded, densities_padded, features_padded), + (densities_list, features_list, densities, features), + ): + self._check_padded(x_pad, x_list, grid_sizes) + + # test feature setters + features_new = [ + torch.rand((num_channels, *grid_size), device=device, dtype=torch.float32) + for grid_size in grid_sizes + ] + volumes._set_features(features_new) + features_new_list = volumes.features_list() + features_new_padded = volumes.features() + for x_pad, x_list in zip( + (features_new_padded, features_new_padded), + (features_new, features_new_list), + ): + self._check_padded(x_pad, x_list, grid_sizes) + + # wrong features to update + bad_features_new = [ + [ + torch.rand( + (num_channels, *grid_size), device=diff_device, dtype=torch.float32 + ) + for grid_size in diff_grid_sizes + ], + torch.rand( + (num_volumes, num_channels, K + 1, K, K), + device=device, + dtype=torch.float32, + ), + None, + ] + for bad_features_new_ in bad_features_new: + with self.assertRaises(ValueError): + volumes._set_densities(bad_features_new_) + + # test density setters + densities_new = [ + torch.rand((1, *grid_size), device=device, dtype=torch.float32) + for grid_size in grid_sizes + ] + volumes._set_densities(densities_new) + densities_new_list = volumes.densities_list() + densities_new_padded = volumes.densities() + for x_pad, x_list in zip( + (densities_new_padded, densities_new_padded), + (densities_new, densities_new_list), + ): + self._check_padded(x_pad, x_list, grid_sizes) + + # wrong densities to update + bad_densities_new = [ + [ + torch.rand((1, *grid_size), device=diff_device, dtype=torch.float32) + for grid_size in diff_grid_sizes + ], + torch.rand( + (num_volumes, 1, K + 1, K, K), device=device, dtype=torch.float32 + ), + None, + ] + for bad_densities_new_ in bad_densities_new: + with self.assertRaises(ValueError): + volumes._set_densities(bad_densities_new_) + + # test update_padded + volumes = Volumes(densities=densities, features=features) + volumes_updated = volumes.update_padded( + densities_new, new_features=features_new + ) + densities_new_list = volumes_updated.densities_list() + densities_new_padded = volumes_updated.densities() + features_new_list = volumes_updated.features_list() + features_new_padded = volumes_updated.features() + for x_pad, x_list in zip( + ( + densities_new_padded, + densities_new_padded, + features_new_padded, + features_new_padded, + ), + (densities_new, densities_new_list, features_new, features_new_list), + ): + self._check_padded(x_pad, x_list, grid_sizes) + self.assertIs(volumes.get_grid_sizes(), volumes_updated.get_grid_sizes()) + self.assertIs( + volumes.get_local_to_world_coords_transform(), + volumes_updated.get_local_to_world_coords_transform(), + ) + self.assertIs(volumes.device, volumes_updated.device) + + def test_constructor_for_padded_lists(self): + """ + Tests constructor for padded/list representations. + """ + + device = torch.device("cuda:0") + diff_device = torch.device("cpu") + + num_volumes = 3 + num_channels = 4 + size = (6, 8, 10) + diff_size = (6, 8, 11) + + # good ways to define densities + ok_densities = [ + torch.randn( + size=[num_volumes, 1, *size], device=device, dtype=torch.float32 + ).unbind(0), + torch.randn( + size=[num_volumes, 1, *size], device=device, dtype=torch.float32 + ), + ] + + # bad ways to define features + bad_features = [ + torch.randn( + size=[num_volumes + 1, num_channels, *size], + device=device, + dtype=torch.float32, + ).unbind(0), # list with diff batch size + torch.randn( + size=[num_volumes + 1, num_channels, *size], + device=device, + dtype=torch.float32, + ), # diff batch size + torch.randn( + size=[num_volumes, num_channels, *diff_size], + device=device, + dtype=torch.float32, + ).unbind(0), # list with different size + torch.randn( + size=[num_volumes, num_channels, *diff_size], + device=device, + dtype=torch.float32, + ), # different size + torch.randn( + size=[num_volumes, num_channels, *size], + device=diff_device, + dtype=torch.float32, + ), # different device + torch.randn( + size=[num_volumes, num_channels, *size], + device=diff_device, + dtype=torch.float32, + ).unbind(0), # list with different device + ] + + # good ways to define features + ok_features = [ + torch.randn( + size=[num_volumes, num_channels, *size], + device=device, + dtype=torch.float32, + ).unbind(0), # list of features of correct size + torch.randn( + size=[num_volumes, num_channels, *size], + device=device, + dtype=torch.float32, + ), + ] + + for densities in ok_densities: + for features in bad_features: + self.assertRaises( + ValueError, Volumes, densities=densities, features=features + ) + for features in ok_features: + Volumes(densities=densities, features=features) + + def test_constructor( + self, num_volumes=3, num_channels=4, size=(6, 8, 10), dtype=torch.float32 + ): + """ + Test different ways of calling the `Volumes` constructor + """ + + device = torch.device("cuda:0") + + # all ways to define features + features = [ + torch.randn( + size=[num_volumes, num_channels, *size], + device=device, + dtype=torch.float32, + ), # padded tensor + torch.randn( + size=[num_volumes, num_channels, *size], + device=device, + dtype=torch.float32, + ).unbind(0), # list of features + None, # no features + ] + + # bad ways to define features + bad_features = [ + torch.randn( + size=[num_volumes, num_channels, 2, *size], + device=device, + dtype=torch.float32, + ), # 6 dims + torch.randn( + size=[num_volumes, *size], device=device, dtype=torch.float32 + ), # 4 dims + torch.randn( + size=[num_volumes, *size], device=device, dtype=torch.float32 + ).unbind(0), # list of 4 dim tensors + ] + + # all ways to define densities + densities = [ + torch.randn( + size=[num_volumes, 1, *size], device=device, dtype=torch.float32 + ), # padded tensor + torch.randn( + size=[num_volumes, 1, *size], device=device, dtype=torch.float32 + ).unbind(0), # list of densities + ] + + # bad ways to define densities + bad_densities = [ + None, # omitted + torch.randn( + size=[num_volumes, 1, 1, *size], device=device, dtype=torch.float32 + ), # 6-dim tensor + torch.randn( + size=[num_volumes, 1, 1, *size], device=device, dtype=torch.float32 + ).unbind(0), # list of 5-dim densities + ] + + # all possible ways to define the voxels sizes + vox_sizes = [ + torch.Tensor([1.0, 1.0, 1.0]), + [1.0, 1.0, 1.0], + torch.Tensor([1.0, 1.0, 1.0])[None].repeat(num_volumes, 1), + torch.Tensor([1.0])[None].repeat(num_volumes, 1), + 1.0, + torch.Tensor([1.0]), + ] + + # all possible ways to define the volume translations + vol_translations = [ + torch.Tensor([1.0, 1.0, 1.0]), + [1.0, 1.0, 1.0], + torch.Tensor([1.0, 1.0, 1.0])[None].repeat(num_volumes, 1), + ] + + # wrong ways to define voxel sizes + bad_vox_sizes = [ + torch.Tensor([1.0, 1.0, 1.0, 1.0]), + [1.0, 1.0, 1.0, 1.0], + torch.Tensor([]), + None, + ] + + # wrong ways to define the volume translations + bad_vol_translations = [ + torch.Tensor([1.0, 1.0]), + [1.0, 1.0], + 1.0, + torch.Tensor([1.0, 1.0, 1.0])[None].repeat(num_volumes + 1, 1), + ] + + def zip_with_ok_indicator(good, bad): + return zip([*good, *bad], [*([True] * len(good)), *([False] * len(bad))]) + + for features_, features_ok in zip_with_ok_indicator(features, bad_features): + for densities_, densities_ok in zip_with_ok_indicator( + densities, bad_densities + ): + for vox_size, size_ok in zip_with_ok_indicator( + vox_sizes, bad_vox_sizes + ): + for vol_translation, trans_ok in zip_with_ok_indicator( + vol_translations, bad_vol_translations + ): + if ( + size_ok and trans_ok and features_ok and densities_ok + ): # if all entries are good we check that this doesnt throw + Volumes( + features=features_, + densities=densities_, + voxel_size=vox_size, + volume_translation=vol_translation, + ) + + else: # otherwise we check for ValueError + self.assertRaises( + ValueError, + Volumes, + features=features_, + densities=densities_, + voxel_size=vox_size, + volume_translation=vol_translation, + )