diff --git a/project/models/face_anon_simple/src/diffusers/py.typed b/project/models/deprecated_deep_privacy2/.gitattributes
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/py.typed
rename to project/models/deprecated_deep_privacy2/.gitattributes
diff --git a/project/models/deprecated_deep_privacy2/.gitignore b/project/models/deprecated_deep_privacy2/.gitignore
new file mode 100644
index 0000000..273a286
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/.gitignore
@@ -0,0 +1,54 @@
+# FILES
+*.yaml
+*.pkl
+*.flist
+*.zip
+*.out
+*.npy
+*.gz
+*.ckpt
+*.pth
+*.log
+*.pyc
+*.csv
+*.yml
+*.ods
+*.ods#
+*.json
+build_docker.sh
+
+# Images / Videos
+#*.png
+#*.jpg
+*.jpeg
+*.m4a
+*.mkv
+*.mp4
+
+# Directories created by inpaintron
+.cache/
+test_examples/
+.vscode
+__pycache__
+.debug/
+**/.ipynb_checkpoints/**
+outputs/
+
+
+# From pip setup
+build/
+*.egg-info
+*.egg
+.npm/
+
+# From dockerfile
+.bash_history
+.viminfo
+.local/
+*.pickle
+*.onnx
+
+
+sbatch_files/
+figures/
+image_dump/
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/=8.1.0 b/project/models/deprecated_deep_privacy2/=8.1.0
new file mode 100644
index 0000000..b41bb6b
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/=8.1.0
@@ -0,0 +1,6 @@
+Collecting av
+ Using cached av-15.0.0.tar.gz (3.8 MB)
+ Installing build dependencies: started
+ Installing build dependencies: finished with status 'done'
+ Getting requirements to build wheel: started
+ Getting requirements to build wheel: finished with status 'error'
diff --git a/project/models/deprecated_deep_privacy2/CHANGELOG.md b/project/models/deprecated_deep_privacy2/CHANGELOG.md
new file mode 100644
index 0000000..4a6b38c
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/CHANGELOG.md
@@ -0,0 +1,13 @@
+# Changelog
+
+## 23.03.2023
+- Quality of life improvements
+- Add support for refined keypoints for the FDH dataset.
+- Add FDF128 dataset loader with webdataset.
+- Support for using detector and anonymizer from DeepPrivacy1.
+- Update visualization of keypoints
+- Fix bug for upsampling/downsampling in the anonymization pipeline.
+- Support for keypoint-guided face anonymization.
+- Add ViTPose + Mask-RCNN detection model for keypoint-guided full-body anonymization.
+- Set caching of detections to False as default, as it can produce unexpected behaviour. For example, using a different score threshold requires re-run of detector.
+- Add Gradio Demos for face and body anonymization
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/Dockerfile b/project/models/deprecated_deep_privacy2/Dockerfile
new file mode 100644
index 0000000..60e1dc4
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/Dockerfile
@@ -0,0 +1,50 @@
+FROM nvcr.io/nvidia/pytorch:22.08-py3
+ARG BASE_IMAGE=nvcr.io/nvidia/pytorch:24.03-py3 # new variable
+FROM ${BASE_IMAGE}
+ARG UID=1000
+ARG UNAME=testuser
+ARG WANDB_API_KEY
+RUN useradd -ms /bin/bash -u $UID $UNAME && \
+ mkdir -p /home/${UNAME} &&\
+ chown -R $UID /home/${UNAME}
+WORKDIR /home/${UNAME}
+ENV DEBIAN_FRONTEND="noninteractive"
+ENV WANDB_API_KEY=$WANDB_API_KEY
+ENV TORCH_HOME=/home/${UNAME}/.cache
+
+# OPTIONAL - DeepPrivacy2 uses these environment variables to set directories outside the current working directory
+#ENV BASE_DATASET_DIR=/work/haakohu/datasets
+#ENV BASE_OUTPUT_DIR=/work/haakohu/outputs
+#ENV FBA_METRICS_CACHE=/work/haakohu/metrics_cache
+
+RUN apt-get update && apt-get install ffmpeg libsm6 libxext6 qt5-default -y
+RUN pip install git+https://github.com/facebookresearch/detectron2@96c752ce821a3340e27edd51c28a00665dd32a30#subdirectory=projects/DensePose
+COPY setup.py setup.py
+RUN pip install \
+ numpy>=1.20 \
+ matplotlib \
+ cython \
+ tensorboard \
+ tqdm \
+ ninja==1.10.2 \
+ opencv-python-headless==4.5.5.64 \
+ ftfy==6.1.3 \
+ moviepy \
+ pyspng \
+ git+https://github.com/hukkelas/DSFD-Pytorch-Inference \
+ wandb \
+ termcolor \
+ git+https://github.com/hukkelas/torch_ops.git \
+ git+https://github.com/wmuron/motpy@c77f85d27e371c0a298e9a88ca99292d9b9cbe6b \
+ fast_pytorch_kmeans \
+ einops_exts \
+ einops \
+ regex \
+ setuptools==59.5.0 \
+ resize_right==0.0.2 \
+ pillow \
+ scipy==1.7.1 \
+ webdataset==0.2.26 \
+ scikit-image \
+ timm==0.6.7
+RUN pip install --no-deps torch_fidelity==0.3.0 clip@git+https://github.com/openai/CLIP.git@b46f5ac7587d2e1862f8b7b1573179d80dcdd620
diff --git a/project/models/deprecated_deep_privacy2/LICENSE b/project/models/deprecated_deep_privacy2/LICENSE
new file mode 100644
index 0000000..261eeb9
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/project/models/deprecated_deep_privacy2/anonymize.py b/project/models/deprecated_deep_privacy2/anonymize.py
new file mode 100644
index 0000000..40dc7ff
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/anonymize.py
@@ -0,0 +1,367 @@
+import cv2
+import torch
+import tops
+import tqdm
+import click
+import hashlib
+import numpy as np
+from dp2 import utils
+from PIL import Image
+from tops import logger
+from pathlib import Path
+from typing import Optional
+import moviepy.editor as mp
+from tops.config import instantiate
+from detectron2.data.detection_utils import _apply_exif_orientation
+from dp2.utils.bufferless_video_capture import BufferlessVideoCapture
+
+
+def show_video(video_path):
+ video_cap = cv2.VideoCapture(str(video_path))
+ while video_cap.isOpened():
+ ret, frame = video_cap.read()
+ cv2.imshow("Frame", frame)
+ key = cv2.waitKey(25)
+ if key == ord("q"):
+ break
+ video_cap.release()
+ cv2.destroyAllWindows()
+
+
+class ImageIndexTracker:
+ def __init__(self, fn) -> None:
+ self.fn = fn
+ self.idx = 0
+
+ def fl_image(self, frame):
+ self.idx += 1
+ return self.fn(frame, self.idx - 1)
+
+
+def anonymize_video(
+ video_path,
+ output_path: Path,
+ anonymizer,
+ visualize: bool,
+ max_res: int,
+ start_time: int,
+ fps: int,
+ end_time: int,
+ visualize_detection: bool,
+ track: bool,
+ synthesis_kwargs,
+ **kwargs,
+):
+ video = mp.VideoFileClip(str(video_path))
+ if track:
+ anonymizer.initialize_tracker(video.fps)
+
+ def process_frame(frame, idx):
+ frame = np.array(resize(Image.fromarray(frame), max_res))
+ cache_id = hashlib.md5(frame).hexdigest()
+ frame = utils.im2torch(frame, to_float=False, normalize=False)[0]
+ cache_id_ = cache_id + str(idx)
+ synthesis_kwargs["cache_id"] = cache_id_
+ if visualize_detection:
+ anonymized = anonymizer.visualize_detection(frame, cache_id=cache_id_)
+ else:
+ anonymized = anonymizer(frame, **synthesis_kwargs)
+ anonymized = utils.im2numpy(anonymized)
+ if visualize:
+ cv2.imshow("frame", anonymized[:, :, ::-1])
+ key = cv2.waitKey(1)
+ if key == ord("q"):
+ exit()
+ return anonymized
+
+ video: mp.VideoClip = video.subclip(start_time, end_time)
+
+ if fps is not None:
+ video = video.set_fps(fps)
+
+ video = video.fl_image(ImageIndexTracker(process_frame).fl_image)
+ if str(output_path).endswith(".avi"):
+ output_path = str(output_path).replace(".avi", ".mp4")
+ if not output_path.parent.exists():
+ output_path.parent.mkdir(parents=True)
+ video.write_videofile(str(output_path))
+
+
+def resize(frame: Image.Image, max_res):
+ if max_res is None:
+ return frame
+ f = max(*[x / max_res for x in frame.size], 1)
+ if f == 1:
+ return frame
+ new_shape = [int(x / f) for x in frame.size]
+ return frame.resize(new_shape, resample=Image.BILINEAR)
+
+
+def anonymize_image(
+ image_path,
+ output_path: Path,
+ visualize: bool,
+ anonymizer,
+ max_res: int,
+ visualize_detection: bool,
+ synthesis_kwargs,
+ **kwargs,
+):
+ with Image.open(image_path) as im:
+ im = _apply_exif_orientation(im)
+ orig_im_mode = im.mode
+
+ im = im.convert("RGB")
+ im = resize(im, max_res)
+ im = np.array(im)
+ md5_ = hashlib.md5(im).hexdigest()
+ im = utils.im2torch(np.array(im), to_float=False, normalize=False)[0]
+ synthesis_kwargs["cache_id"] = md5_
+ if visualize_detection:
+ im_ = anonymizer.visualize_detection(tops.to_cuda(im), cache_id=md5_)
+ else:
+ im_ = anonymizer(im, **synthesis_kwargs)
+ im_ = utils.im2numpy(im_)
+ if visualize:
+ while True:
+ cv2.imshow("frame", im_[:, :, ::-1])
+ key = cv2.waitKey(0)
+ if key == ord("q"):
+ break
+ elif key == ord("u"):
+ im_ = utils.im2numpy(anonymizer(im, **synthesis_kwargs))
+ im = Image.fromarray(im_).convert(orig_im_mode)
+ if output_path is not None:
+ output_path.parent.mkdir(exist_ok=True, parents=True)
+ im.save(output_path, optimize=False, quality=100)
+ print(f"Saved to: {output_path}")
+
+
+def anonymize_file(input_path: Path, output_path: Optional[Path], **kwargs):
+ if output_path is not None and output_path.is_file():
+ logger.warn(f"Overwriting previous file: {output_path}")
+ if tops.is_image(input_path):
+ anonymize_image(input_path, output_path, **kwargs)
+ elif tops.is_video(input_path):
+ anonymize_video(input_path, output_path, **kwargs)
+ else:
+ logger.log(f"Filepath not a video or image file: {input_path}")
+
+
+def anonymize_directory(input_dir: Path, output_dir: Path, **kwargs):
+ for childname in tqdm.tqdm(input_dir.iterdir()):
+ childpath = input_dir.joinpath(childname.name)
+ output_path = output_dir.joinpath(childname.name)
+ if not childpath.is_file():
+ anonymize_directory(childpath, output_path, **kwargs)
+ else:
+ assert childpath.is_file()
+ anonymize_file(childpath, output_path, **kwargs)
+
+
+def anonymize_webcam(
+ anonymizer,
+ max_res: int,
+ synthesis_kwargs,
+ visualize_detection,
+ track: bool,
+ **kwargs,
+):
+ import time
+
+ cap = BufferlessVideoCapture(0, width=1920, height=1080)
+ t = time.time()
+ frames = 0
+ if track:
+ anonymizer.initialize_tracker(fps=5) # FPS used for tracking objects
+ while True:
+ # Capture frame-by-frame
+ ret, frame = cap.read()
+ frame = Image.fromarray(frame[:, :, ::-1])
+ frame = resize(frame, max_res)
+ frame = np.array(frame)
+ im = utils.im2torch(np.array(frame), to_float=False, normalize=False)[0]
+ if visualize_detection:
+ im_ = anonymizer.visualize_detection(tops.to_cuda(im))
+ else:
+ im_ = anonymizer(im, **synthesis_kwargs)
+ im_ = utils.im2numpy(im_)
+
+ frames += 1
+ delta = time.time() - t
+ fps = "?"
+ if delta > 1e-6:
+ fps = frames / delta
+ print(f"FPS: {fps:.3f}", end="\r")
+ cv2.imshow("frame", im_[:, :, ::-1])
+ if cv2.waitKey(1) & 0xFF == ord("q"):
+ break
+
+
+@click.command()
+@click.argument("config_path", type=click.Path(exists=True))
+@click.option(
+ "-i",
+ "--input_path",
+ help="Input path. Accepted inputs: images, videos, directories.",
+)
+@click.option(
+ "-o",
+ "--output_path",
+ default=None,
+ type=click.Path(),
+ help="Output path to save. Can be directory or file.",
+)
+@click.option(
+ "-v", "--visualize", default=False, is_flag=True, help="Visualize the result"
+)
+@click.option(
+ "--max-res", default=None, type=int, help="Maximum resolution of height/wideo"
+)
+@click.option(
+ "--start-time",
+ "--st",
+ default=0,
+ type=int,
+ help="Start time (second) for vide anonymization",
+)
+@click.option(
+ "--end-time",
+ "--et",
+ default=None,
+ type=int,
+ help="End time (second) for vide anonymization",
+)
+@click.option("--fps", default=None, type=int, help="FPS for anonymization")
+@click.option(
+ "--detection-score-threshold",
+ "--dst",
+ default=0.3,
+ type=click.FloatRange(0, 1),
+ help="Detection threshold, threshold applied for all detection models.",
+)
+@click.option(
+ "--visualize-detection",
+ "--vd",
+ default=False,
+ is_flag=True,
+ help="Visualize only detections without running anonymization.",
+)
+@click.option(
+ "--multi-modal-truncation",
+ "--mt",
+ default=False,
+ is_flag=True,
+ help="Enable multi-modal truncation proposed by: https://arxiv.org/pdf/2202.12211.pdf",
+)
+@click.option(
+ "--cache",
+ default=False,
+ is_flag=True,
+ help="Enable detection caching. Will save and load detections from cache.",
+)
+@click.option(
+ "--amp",
+ default=True,
+ is_flag=True,
+ help="Use automatic mixed precision for generator forward pass",
+)
+@click.option(
+ "-t",
+ "--truncation_value",
+ default=0,
+ type=click.FloatRange(0, 1),
+ help="Latent interpolation truncation value.",
+)
+@click.option(
+ "--track",
+ default=False,
+ is_flag=True,
+ help="Track detections over frames. Will use the same latent variable (z) for tracked identities.",
+)
+@click.option(
+ "--seed", default=0, type=int, help="Set random seed for generating images."
+)
+@click.option(
+ "--person-generator",
+ default=None,
+ help="Config path to unconditional person generator",
+ type=click.Path(),
+)
+@click.option(
+ "--cse-person-generator",
+ default=None,
+ help="Config path to CSE-guided person generator",
+ type=click.Path(),
+)
+@click.option(
+ "--webcam", default=False, is_flag=True, help="Read image from webcam feed."
+)
+@click.option(
+ "--text-prompt",
+ default=None,
+ type=str,
+ help="Text prompt for attribute guided anonymization. Requires the validation dataset downloaded.",
+)
+@click.option(
+ "--text-prompt-strength",
+ default=0.5,
+ type=float,
+ help="Strength for attribute-guided anonymization",
+)
+def anonymize_path(
+ config_path,
+ input_path,
+ output_path,
+ detection_score_threshold: float,
+ visualize_detection: bool,
+ cache: bool,
+ seed: int,
+ person_generator: str,
+ cse_person_generator: str,
+ webcam: bool,
+ **kwargs,
+):
+ """
+ config_path: Specify the path to the anonymization model to use.
+ """
+ tops.set_seed(seed)
+ cfg = utils.load_config(config_path)
+ if person_generator is not None:
+ cfg.anonymizer.person_G_cfg = person_generator
+ if cse_person_generator is not None:
+ cfg.anonymizer.cse_person_G_cfg = cse_person_generator
+ cfg.detector.score_threshold = detection_score_threshold
+ utils.print_config(cfg)
+
+ anonymizer = instantiate(cfg.anonymizer, load_cache=cache)
+ synthesis_kwargs = [
+ "amp",
+ "multi_modal_truncation",
+ "truncation_value",
+ "text_prompt",
+ "text_prompt_strength",
+ ]
+ synthesis_kwargs = {k: kwargs.pop(k) for k in synthesis_kwargs}
+
+ kwargs["anonymizer"] = anonymizer
+ kwargs["visualize_detection"] = visualize_detection
+ kwargs["synthesis_kwargs"] = synthesis_kwargs
+
+ if webcam:
+ anonymize_webcam(**kwargs)
+ return
+ input_path = Path(input_path)
+ output_path = Path(output_path) if output_path is not None else None
+ if output_path is None and not kwargs["visualize"]:
+ logger.log("Output path not set. Setting visualize to True")
+ kwargs["visualize"] = True
+ if input_path.is_dir():
+ assert output_path is None or not output_path.is_file()
+ anonymize_directory(input_path, output_path, **kwargs)
+ else:
+ anonymize_file(input_path, output_path, **kwargs)
+
+
+if __name__ == "__main__":
+ anonymize_path()
diff --git a/project/models/deprecated_deep_privacy2/attribute_guided_demo.py b/project/models/deprecated_deep_privacy2/attribute_guided_demo.py
new file mode 100644
index 0000000..0f346eb
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/attribute_guided_demo.py
@@ -0,0 +1,160 @@
+from collections import defaultdict
+import gradio
+import click
+import numpy as np
+import torch
+import cv2
+from PIL import Image
+from dp2 import utils
+from tops.config import instantiate
+import tops
+import gradio.inputs
+from stylemc import get_and_cache_direction, get_stylesW, init_affine_modules
+
+
+class GuidedDemo:
+ def __init__(self, anonymizer, cfg_face) -> None:
+ self.anonymizer = anonymizer
+ assert sum([x is not None for x in list(anonymizer.generators.values())]) == 1
+ self.generator = [x for x in list(anonymizer.generators.values()) if x is not None][0]
+ cfg = list(anonymizer.generator_cfgs.values())[0]
+ cfg.train.batch_size = 1
+ self.dl = instantiate(cfg.data.val.loader)
+ self.cache_dir = cfg.output_dir
+ self.precompute_edits()
+ self.is_first = True
+
+ def precompute_edits(self):
+ self.precomputed_edits = set()
+ for edit in self.precomputed_edits:
+ get_and_cache_direction(self.cache_dir, self.dl, self.generator, edit)
+ if self.cache_dir.joinpath("stylemc_cache").is_dir():
+ for path in self.cache_dir.joinpath("stylemc_cache").iterdir():
+ text_prompt = path.stem.replace("_", " ")
+ self.precomputed_edits.add(text_prompt)
+ print(text_prompt)
+ self.edits = defaultdict(defaultdict)
+
+ def anonymize(self, img, show_boxes: bool, current_box_idx: int, current_styles, current_boxes, update_identity, edits, cache_id=None):
+ if not isinstance(img, torch.Tensor):
+ img, cache_id = pil2torch(img)
+ img = tops.to_cuda(img)
+
+ current_box_idx = current_box_idx % len(current_boxes)
+ edited_styles = [s.clone() for s in current_styles]
+ for face_idx, face_edits in edits.items():
+ for prompt, strength in face_edits.items():
+ direction = get_and_cache_direction(self.cache_dir, self.dl, self.generator, prompt)
+ edited_styles[int(face_idx)] += direction * strength
+ update_identity[int(face_idx)] = True
+ assert img.dtype == torch.uint8
+ img = self.anonymizer(
+ img, truncation_value=0,
+ multi_modal_truncation=True, amp=True,
+ cache_id=cache_id,
+ all_styles=iter(edited_styles),
+ update_identity=update_identity)
+ update_identity = [True for i in range(len(update_identity))]
+ img = utils.im2numpy(img)
+ if show_boxes:
+ x0, y0, x1, y1 = [int(_) for _ in current_boxes[int(current_box_idx)]]
+ img = cv2.rectangle(img, (x0, y0), (x1, y1), (255, 0, 0), 1)
+ return img, update_identity
+
+ def update_image(self, img, show_boxes):
+ img, cache_id = pil2torch(img)
+ img = tops.to_cuda(img)
+ det = self.anonymizer.detector.forward_and_cache(img, cache_id, load_cache=True)[0]
+ current_styles = []
+ for i in range(len(det)):
+ # Need to do forward pass to register all affine modules.
+ batch = det.get_crop(i, img)
+ batch["condition"] = batch["img"].float()
+ if self.multi_modal_truncation:
+ w = self.generator.style_net.multi_modal_truncate(0, n=1)
+ else:
+ w = self.generator.style_net.get_truncated(1, n=1)
+ if self.is_first:
+ init_affine_modules(self.generator, batch)
+ self.is_first = False
+ s = get_stylesW(w)
+ current_styles.append(s)
+ update_identity = [True for i in range(len(det))]
+ current_boxes = np.array(det.boxes)
+ edits = defaultdict(defaultdict)
+ cur_face_idx = -1 % len(current_boxes)
+ img, update_identity = self.anonymize(img, show_boxes, cur_face_idx, current_styles, current_boxes, update_identity, edits, cache_id=cache_id)
+ return img, current_styles, current_boxes, update_identity, edits, cur_face_idx
+
+ def change_face(self, change, cur_face_idx, current_boxes, input_image, show_boxes, current_styles, update_identity, edits):
+ cur_face_idx = (cur_face_idx+change) % len(current_boxes)
+ img, update_identity = self.anonymize(input_image, show_boxes, cur_face_idx, current_styles, current_boxes, update_identity, edits)
+ return img, update_identity, cur_face_idx
+
+ def add_style(self, face_idx: int, prompt: str, strength: float, input_image, show_boxes, current_styles, current_boxes, update_identity, edits):
+ face_idx = face_idx % len(current_boxes)
+ edits[face_idx][prompt] = strength
+ img, update_identity = self.anonymize(input_image, show_boxes, face_idx, current_styles, current_boxes, update_identity, edits)
+ return img, update_identity, edits
+
+ def switch_mmt(self, value):
+ self.multi_modal_truncation = value
+
+ def setup_interface(self):
+ current_styles = gradio.State()
+ current_boxes = gradio.State(None)
+ update_identity = gradio.State([])
+ edits = gradio.State([])
+ with gradio.Row():
+ input_image = gradio.Image(
+ type="pil", label="Upload your image or try the example below!", source="webcam")
+ output_image = gradio.Image(type="numpy", label="Output")
+ with gradio.Row():
+ update_btn = gradio.Button("Update Anonymization").style(full_width=True)
+ mmt_btn = gradio.Checkbox(label="Multi Modal anonymization", value=True)
+
+ with gradio.Row():
+ show_boxes = gradio.Checkbox(value=True, label="Show Selected")
+ cur_face_idx = gradio.Number(value=-1,label="Current", interactive=False)
+ previous = gradio.Button("Previous Person")
+ next_ = gradio.Button("Next Person")
+ with gradio.Row():
+ text_prompt = gradio.Textbox(
+ placeholder=" | ".join(list(self.precomputed_edits)),
+ label="Text Prompt for Edit")
+ edit_strength = gradio.Slider(0, 5, step=.01)
+ add_btn = gradio.Button("Add Edit")
+ add_btn.click(self.add_style, inputs=[cur_face_idx, text_prompt, edit_strength, input_image, show_boxes, current_styles, current_boxes, update_identity, edits], outputs=[output_image, update_identity, edits])
+ mmt_btn.change(self.switch_mmt, inputs=[mmt_btn], outputs=[])
+ self.multi_modal_truncation = mmt_btn.value
+ update_btn.click(self.update_image, inputs=[input_image, show_boxes], outputs=[output_image, current_styles, current_boxes, update_identity, edits, cur_face_idx])
+ input_image.change(self.update_image, inputs=[input_image, show_boxes], outputs=[output_image, current_styles, current_boxes, update_identity, edits, cur_face_idx])
+ previous.click(self.change_face, inputs=[gradio.State(-1), cur_face_idx, current_boxes, input_image, show_boxes, current_styles, update_identity, edits], outputs=[output_image, update_identity, cur_face_idx])
+ next_.click(self.change_face, inputs=[gradio.State(1), cur_face_idx, current_boxes, input_image, show_boxes, current_styles, update_identity, edits], outputs=[output_image, update_identity, cur_face_idx])
+
+ show_boxes.change(self.anonymize, inputs=[input_image, show_boxes, cur_face_idx, current_styles, current_boxes, update_identity, edits], outputs=[output_image, update_identity])
+
+
+def pil2torch(img: Image.Image):
+ img = img.convert("RGB")
+ img = np.array(img)
+ img = np.rollaxis(img, 2)
+ return torch.from_numpy(img), None
+
+@click.command()
+@click.argument("config_path")
+def main(config_path):
+ cfg_face = utils.load_config(config_path)
+ anonymizer_face = instantiate(cfg_face.anonymizer, load_cache=False)
+ anonymizer_face.initialize_tracker(fps=1)
+
+
+ with gradio.Blocks() as demo:
+ gradio.Markdown("#
DeepPrivacy2 - Realistic Image Anonymization
")
+ gradio.Markdown("###
Håkon Hukkelås, Rudolf Mester, Frank Lindseth
")
+ with gradio.Tab("Text-Guided Anonymization"):
+ GuidedDemo(anonymizer_face, cfg_face).setup_interface()
+
+
+ demo.launch()
+main()
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/configs/anonymizers/FB_cse.py b/project/models/deprecated_deep_privacy2/configs/anonymizers/FB_cse.py
new file mode 100644
index 0000000..ff44a8e
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/anonymizers/FB_cse.py
@@ -0,0 +1,28 @@
+from dp2.anonymizer import Anonymizer
+from dp2.detection.person_detector import CSEPersonDetector
+from ..defaults import common
+from tops.config import LazyCall as L
+from dp2.generator.dummy_generators import MaskOutGenerator
+
+
+maskout_G = L(MaskOutGenerator)(noise="constant")
+
+detector = L(CSEPersonDetector)(
+ mask_rcnn_cfg=dict(),
+ cse_cfg=dict(),
+ cse_post_process_cfg=dict(
+ target_imsize=(288, 160),
+ exp_bbox_cfg=dict(percentage_background=0.3, axis_minimum_expansion=.1),
+ exp_bbox_filter=dict(minimum_area=32*32, min_bbox_ratio_inside=0, aspect_ratio_range=[0, 99999]),
+ iou_combine_threshold=0.4,
+ dilation_percentage=0.02,
+ normalize_embedding=False
+ ),
+ score_threshold=0.3,
+ cache_directory=common.output_dir.joinpath("cse_person_detection_cache")
+)
+
+anonymizer = L(Anonymizer)(
+ detector="${detector}",
+ cse_person_G_cfg="configs/fdh/styleganL.py",
+)
diff --git a/project/models/deprecated_deep_privacy2/configs/anonymizers/FB_cse_mask.py b/project/models/deprecated_deep_privacy2/configs/anonymizers/FB_cse_mask.py
new file mode 100644
index 0000000..5c9d2a4
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/anonymizers/FB_cse_mask.py
@@ -0,0 +1,29 @@
+from dp2.anonymizer import Anonymizer
+from dp2.detection.person_detector import CSEPersonDetector
+from ..defaults import common
+from tops.config import LazyCall as L
+from dp2.generator.dummy_generators import MaskOutGenerator
+
+
+maskout_G = L(MaskOutGenerator)(noise="constant")
+
+detector = L(CSEPersonDetector)(
+ mask_rcnn_cfg=dict(),
+ cse_cfg=dict(),
+ cse_post_process_cfg=dict(
+ target_imsize=(288, 160),
+ exp_bbox_cfg=dict(percentage_background=0.3, axis_minimum_expansion=.1),
+ exp_bbox_filter=dict(minimum_area=32*32, min_bbox_ratio_inside=0, aspect_ratio_range=[0, 99999]),
+ iou_combine_threshold=0.4,
+ dilation_percentage=0.02,
+ normalize_embedding=False
+ ),
+ score_threshold=0.3,
+ cache_directory=common.output_dir.joinpath("cse_person_detection_cache")
+)
+
+anonymizer = L(Anonymizer)(
+ detector="${detector}",
+ person_G_cfg="configs/fdh/styleganL_nocse.py",
+ cse_person_G_cfg="configs/fdh/styleganL.py",
+)
diff --git a/project/models/deprecated_deep_privacy2/configs/anonymizers/FB_cse_mask_face.py b/project/models/deprecated_deep_privacy2/configs/anonymizers/FB_cse_mask_face.py
new file mode 100644
index 0000000..d411d66
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/anonymizers/FB_cse_mask_face.py
@@ -0,0 +1,29 @@
+from dp2.anonymizer import Anonymizer
+from dp2.detection.cse_mask_face_detector import CSeMaskFaceDetector
+from ..defaults import common
+from tops.config import LazyCall as L
+
+detector = L(CSeMaskFaceDetector)(
+ mask_rcnn_cfg=dict(),
+ face_detector_cfg=dict(),
+ face_post_process_cfg=dict(target_imsize=(256, 256), fdf128_expand=False),
+ cse_cfg=dict(),
+ cse_post_process_cfg=dict(
+ target_imsize=(288, 160),
+ exp_bbox_cfg=dict(percentage_background=0.3, axis_minimum_expansion=.1),
+ exp_bbox_filter=dict(minimum_area=32*32, min_bbox_ratio_inside=0, aspect_ratio_range=[0, 99999]),
+ iou_combine_threshold=0.4,
+ dilation_percentage=0.02,
+ normalize_embedding=False
+ ),
+ score_threshold=0.3,
+ cache_directory=common.output_dir.joinpath("cse_mask_face_detection_cache")
+)
+
+anonymizer = L(Anonymizer)(
+ detector="${detector}",
+ face_G_cfg="configs/fdf/stylegan.py",
+ person_G_cfg="configs/fdh/styleganL_nocse.py",
+ cse_person_G_cfg="configs/fdh/styleganL.py",
+ car_G_cfg="configs/generators/dummy/pixelation8.py"
+)
diff --git a/project/models/deprecated_deep_privacy2/configs/anonymizers/FB_triagan.py b/project/models/deprecated_deep_privacy2/configs/anonymizers/FB_triagan.py
new file mode 100644
index 0000000..69bc646
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/anonymizers/FB_triagan.py
@@ -0,0 +1,26 @@
+from dp2.anonymizer import Anonymizer
+from dp2.detection.models.vit_pose_maskrcnn import MaskRCNNVitPose
+from ..defaults import common
+from tops.config import LazyCall as L
+
+
+detector = L(MaskRCNNVitPose)(
+ mask_rcnn_cfg=dict(),
+ post_process_cfg=dict(
+ target_imsize=(288, 160),
+ exp_bbox_cfg=dict(percentage_background=0.3, axis_minimum_expansion=0.1),
+ exp_bbox_filter=dict(
+ minimum_area=32 * 32, min_bbox_ratio_inside=0, aspect_ratio_range=[0, 99999]
+ ),
+ dilation_percentage=0.02,
+ kp_vis_thr=0.05,
+ insert_joint_map=True,
+ ),
+ score_threshold=0.3,
+ cache_directory=common.output_dir.joinpath("maskrcnn_vitpose_cache"),
+)
+
+anonymizer = L(Anonymizer)(
+ detector="${detector}",
+ person_G_cfg="configs/fdh/triagan/L_im288.py",
+)
diff --git a/project/models/deprecated_deep_privacy2/configs/anonymizers/deep_privacy1.py b/project/models/deprecated_deep_privacy2/configs/anonymizers/deep_privacy1.py
new file mode 100644
index 0000000..9bf116c
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/anonymizers/deep_privacy1.py
@@ -0,0 +1,15 @@
+from .face_fdf128 import anonymizer, common, detector
+from dp2.detection.deep_privacy1_detector import DeepPrivacy1Detector
+from tops.config import LazyCall as L
+
+anonymizer.update(
+ face_G_cfg="configs/fdf/deep_privacy1.py",
+)
+
+anonymizer.detector = L(DeepPrivacy1Detector)(
+ face_detector_cfg=dict(name="DSFDDetector", clip_boxes=True),
+ face_post_process_cfg=dict(target_imsize=(128, 128), fdf128_expand=True),
+ score_threshold=0.3,
+ keypoint_threshold=0.3,
+ cache_directory=common.output_dir.joinpath("deep_privacy1_cache")
+)
diff --git a/project/models/deprecated_deep_privacy2/configs/anonymizers/face.py b/project/models/deprecated_deep_privacy2/configs/anonymizers/face.py
new file mode 100644
index 0000000..1eed93b
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/anonymizers/face.py
@@ -0,0 +1,17 @@
+from dp2.anonymizer import Anonymizer
+from dp2.detection.face_detector import FaceDetector
+from ..defaults import common
+from tops.config import LazyCall as L
+
+
+detector = L(FaceDetector)(
+ face_detector_cfg=dict(name="DSFDDetector", clip_boxes=True),
+ face_post_process_cfg=dict(target_imsize=(256, 256), fdf128_expand=False),
+ score_threshold=0.3,
+ cache_directory=common.output_dir.joinpath("face_detection_cache"),
+)
+
+anonymizer = L(Anonymizer)(
+ detector="${detector}",
+ face_G_cfg="configs/fdf/stylegan.py",
+)
diff --git a/project/models/deprecated_deep_privacy2/configs/anonymizers/face_fdf128.py b/project/models/deprecated_deep_privacy2/configs/anonymizers/face_fdf128.py
new file mode 100644
index 0000000..327b7f5
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/anonymizers/face_fdf128.py
@@ -0,0 +1,18 @@
+from dp2.anonymizer import Anonymizer
+from dp2.detection.face_detector import FaceDetector
+from ..defaults import common
+from tops.config import LazyCall as L
+
+
+detector = L(FaceDetector)(
+ face_detector_cfg=dict(name="DSFDDetector", clip_boxes=True),
+ face_post_process_cfg=dict(target_imsize=(128, 128), fdf128_expand=True),
+ score_threshold=0.3,
+ cache_directory=common.output_dir.joinpath("face_detection_cache")
+)
+
+
+anonymizer = L(Anonymizer)(
+ detector="${detector}",
+ face_G_cfg="configs/fdf/stylegan_fdf128.py",
+)
diff --git a/project/models/deprecated_deep_privacy2/configs/anonymizers/market1501/blackout.py b/project/models/deprecated_deep_privacy2/configs/anonymizers/market1501/blackout.py
new file mode 100644
index 0000000..bf18e05
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/anonymizers/market1501/blackout.py
@@ -0,0 +1,8 @@
+from ..FB_cse_mask_face import anonymizer, detector, common
+
+detector.score_threshold = .1
+detector.face_detector_cfg.confidence_threshold = .5
+detector.cse_cfg.score_thres = 0.3
+anonymizer.face_G_cfg = None
+anonymizer.person_G_cfg = "configs/generators/dummy/maskout.py"
+anonymizer.cse_person_G_cfg = "configs/generators/dummy/maskout.py"
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/configs/anonymizers/market1501/person.py b/project/models/deprecated_deep_privacy2/configs/anonymizers/market1501/person.py
new file mode 100644
index 0000000..e730de3
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/anonymizers/market1501/person.py
@@ -0,0 +1,6 @@
+from ..FB_cse_mask_face import anonymizer, detector, common
+
+detector.score_threshold = .1
+detector.face_detector_cfg.confidence_threshold = .5
+detector.cse_cfg.score_thres = 0.3
+anonymizer.face_G_cfg = None
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/configs/anonymizers/market1501/pixelation16.py b/project/models/deprecated_deep_privacy2/configs/anonymizers/market1501/pixelation16.py
new file mode 100644
index 0000000..c3645a0
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/anonymizers/market1501/pixelation16.py
@@ -0,0 +1,8 @@
+from ..FB_cse_mask_face import anonymizer, detector, common
+
+detector.score_threshold = .1
+detector.face_detector_cfg.confidence_threshold = .5
+detector.cse_cfg.score_thres = 0.3
+anonymizer.face_G_cfg = None
+anonymizer.person_G_cfg = "configs/generators/dummy/pixelation16.py"
+anonymizer.cse_person_G_cfg = "configs/generators/dummy/pixelation16.py"
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/configs/anonymizers/market1501/pixelation8.py b/project/models/deprecated_deep_privacy2/configs/anonymizers/market1501/pixelation8.py
new file mode 100644
index 0000000..bb01506
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/anonymizers/market1501/pixelation8.py
@@ -0,0 +1,8 @@
+from ..FB_cse_mask_face import anonymizer, detector, common
+
+detector.score_threshold = .1
+detector.face_detector_cfg.confidence_threshold = .5
+detector.cse_cfg.score_thres = 0.3
+anonymizer.face_G_cfg = None
+anonymizer.person_G_cfg = "configs/generators/dummy/pixelation8.py"
+anonymizer.cse_person_G_cfg = "configs/generators/dummy/pixelation8.py"
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/configs/anonymizers/traditional/body/gaussian.py b/project/models/deprecated_deep_privacy2/configs/anonymizers/traditional/body/gaussian.py
new file mode 100644
index 0000000..3ea774b
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/anonymizers/traditional/body/gaussian.py
@@ -0,0 +1,3 @@
+from ...FB_triagan import detector, anonymizer, common
+
+anonymizer.person_G_cfg = "configs/generators/dummy/gaussian.py"
diff --git a/project/models/deprecated_deep_privacy2/configs/anonymizers/traditional/body/maskout.py b/project/models/deprecated_deep_privacy2/configs/anonymizers/traditional/body/maskout.py
new file mode 100644
index 0000000..44475d5
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/anonymizers/traditional/body/maskout.py
@@ -0,0 +1,3 @@
+from ...FB_triagan import detector, anonymizer, common
+
+anonymizer.person_G_cfg = "configs/generators/dummy/maskout.py"
diff --git a/project/models/deprecated_deep_privacy2/configs/anonymizers/traditional/face/gaussian.py b/project/models/deprecated_deep_privacy2/configs/anonymizers/traditional/face/gaussian.py
new file mode 100644
index 0000000..7db8aba
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/anonymizers/traditional/face/gaussian.py
@@ -0,0 +1,4 @@
+from ...face import detector, anonymizer, common
+
+anonymizer.face_G_cfg = "configs/generators/dummy/gaussian.py"
+
diff --git a/project/models/deprecated_deep_privacy2/configs/anonymizers/traditional/face/maskout.py b/project/models/deprecated_deep_privacy2/configs/anonymizers/traditional/face/maskout.py
new file mode 100644
index 0000000..0634d3a
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/anonymizers/traditional/face/maskout.py
@@ -0,0 +1,4 @@
+from ...face import detector, anonymizer, common
+
+anonymizer.face_G_cfg = "configs/generators/dummy/maskout.py"
+
diff --git a/project/models/deprecated_deep_privacy2/configs/datasets/coco_cse.py b/project/models/deprecated_deep_privacy2/configs/datasets/coco_cse.py
new file mode 100644
index 0000000..f4834b6
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/datasets/coco_cse.py
@@ -0,0 +1,69 @@
+import os
+from pathlib import Path
+from tops.config import LazyCall as L
+import torch
+import functools
+from dp2.data.datasets.coco_cse import CocoCSE
+from dp2.data.build import get_dataloader
+from dp2.data.transforms.transforms import CreateEmbedding, Normalize, Resize, ToFloat, CreateCondition, RandomHorizontalFlip
+from dp2.data.transforms.stylegan2_transform import StyleGANAugmentPipe
+from dp2.metrics.torch_metrics import compute_metrics_iteratively
+from .utils import final_eval_fn
+
+
+dataset_base_dir = os.environ["BASE_DATASET_DIR"] if "BASE_DATASET_DIR" in os.environ else "data"
+metrics_cache = os.environ["FBA_METRICS_CACHE"] if "FBA_METRICS_CACHE" in os.environ else ".cache"
+data_dir = Path(dataset_base_dir, "coco_cse")
+data = dict(
+ imsize=(288, 160),
+ im_channels=3,
+ semantic_nc=26,
+ cse_nc=16,
+ train=dict(
+ dataset=L(CocoCSE)(data_dir.joinpath("train"), transform=None, normalize_E=False),
+ loader=L(get_dataloader)(
+ shuffle=True, num_workers=6, drop_last=True, prefetch_factor=2,
+ batch_size="${train.batch_size}",
+ dataset="${..dataset}",
+ infinite=True,
+ gpu_transform=L(torch.nn.Sequential)(*[
+ L(ToFloat)(),
+ L(StyleGANAugmentPipe)(
+ rotate=0.5, rotate_max=.05,
+ xint=.5, xint_max=0.05,
+ scale=.5, scale_std=.05,
+ aniso=0.5, aniso_std=.05,
+ xfrac=.5, xfrac_std=.05,
+ brightness=.5, brightness_std=.05,
+ contrast=.5, contrast_std=.1,
+ hue=.5, hue_max=.05,
+ saturation=.5, saturation_std=.5,
+ imgfilter=.5, imgfilter_std=.1),
+ L(RandomHorizontalFlip)(p=0.5),
+ L(CreateEmbedding)(),
+ L(Resize)(size="${data.imsize}"),
+ L(Normalize)(mean=[.5, .5, .5], std=[.5, .5, .5], inplace=True),
+ L(CreateCondition)(),
+ ])
+ )
+ ),
+ val=dict(
+ dataset=L(CocoCSE)(data_dir.joinpath("val"), transform=None, normalize_E=False),
+ loader=L(get_dataloader)(
+ shuffle=False, num_workers=6, drop_last=True, prefetch_factor=2,
+ batch_size="${train.batch_size}",
+ dataset="${..dataset}",
+ infinite=False,
+ gpu_transform=L(torch.nn.Sequential)(*[
+ L(ToFloat)(),
+ L(CreateEmbedding)(),
+ L(Resize)(size="${data.imsize}"),
+ L(Normalize)(mean=[.5, .5, .5], std=[.5, .5, .5], inplace=True),
+ L(CreateCondition)(),
+ ])
+ )
+ ),
+ # Training evaluation might do optimizations to reduce compute overhead. E.g. compute with AMP.
+ train_evaluation_fn=functools.partial(compute_metrics_iteratively, cache_directory=Path(metrics_cache, "coco_cse_val"), include_two_fake=False),
+ evaluation_fn=functools.partial(final_eval_fn, cache_directory=Path(metrics_cache, "coco_cse_val_final"), include_two_fake=True)
+)
diff --git a/project/models/deprecated_deep_privacy2/configs/datasets/fdf128.py b/project/models/deprecated_deep_privacy2/configs/datasets/fdf128.py
new file mode 100644
index 0000000..c19fc0d
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/datasets/fdf128.py
@@ -0,0 +1,24 @@
+from pathlib import Path
+from functools import partial
+from dp2.data.datasets.fdf import FDFDataset
+from .fdf256 import data, dataset_base_dir, metrics_cache, final_eval_fn, train_eval_fn
+
+data_dir = Path(dataset_base_dir, "fdf")
+data.train.dataset.dirpath = data_dir.joinpath("train")
+data.val.dataset.dirpath = data_dir.joinpath("val")
+data.imsize = (128, 128)
+
+
+data.train_evaluation_fn = partial(
+ train_eval_fn, cache_directory=Path(metrics_cache, "fdf128_val_train"))
+data.evaluation_fn = partial(
+ final_eval_fn, cache_directory=Path(metrics_cache, "fdf128_val_final"))
+
+data.train.dataset.update(
+ _target_ = FDFDataset,
+ imsize="${data.imsize}"
+)
+data.val.dataset.update(
+ _target_ = FDFDataset,
+ imsize="${data.imsize}"
+)
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/configs/datasets/fdf128_wds/fdf128.py b/project/models/deprecated_deep_privacy2/configs/datasets/fdf128_wds/fdf128.py
new file mode 100644
index 0000000..38384e1
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/datasets/fdf128_wds/fdf128.py
@@ -0,0 +1,82 @@
+import os
+from pathlib import Path
+from tops.config import LazyCall as L
+import torch
+import functools
+from dp2.data.datasets.fdf128_wds import get_dataloader_fdf_wds
+from dp2.data.utils import get_fdf_flipmap
+from dp2.data.transforms.transforms import (
+ Normalize,
+ ToFloat,
+ CreateCondition,
+ RandomHorizontalFlip,
+)
+from ..utils import train_eval_fn
+from dp2.metrics.torch_metrics import compute_metrics_iteratively
+from dp2.metrics.fid_clip import compute_fid_clip
+from dp2.metrics.ppl import calculate_ppl
+
+
+def final_eval_fn(*args, **kwargs):
+ result = compute_metrics_iteratively(*args, **kwargs)
+ result2 = calculate_ppl(*args, **kwargs, upsample_size=(128, 128))
+ result3 = compute_fid_clip(*args, **kwargs)
+ assert all(key not in result for key in result2)
+ result.update(result2)
+ result.update(result3)
+ return result
+
+
+def get_cache_directory(imsize, subset):
+ return Path(metrics_cache, f"{subset}{imsize[0]}")
+
+dataset_base_dir = (
+ os.environ["BASE_DATASET_DIR"] if "BASE_DATASET_DIR" in os.environ else "data"
+)
+metrics_cache = (
+ os.environ["FBA_METRICS_CACHE"] if "FBA_METRICS_CACHE" in os.environ else ".cache"
+)
+data_dir = Path(dataset_base_dir, "fdf_resampled")
+data = dict(
+ imsize=(128, 128),
+ im_channels=3,
+ cse_nc=0,
+ n_keypoints=7,
+ train=dict(
+ loader=L(get_dataloader_fdf_wds)(
+ path=data_dir.joinpath("train", "128", "out-{000000..000473}.tar"),
+ batch_size="${train.batch_size}",
+ num_workers=4,
+ transform=L(torch.nn.Sequential)(
+ L(RandomHorizontalFlip)(p=0.5, flip_map=get_fdf_flipmap()),
+ ),
+ gpu_transform=L(torch.nn.Sequential)(
+ L(ToFloat)(norm=False, keys=["img", "mask"]),
+ L(Normalize)(mean=[0.5*255, 0.5*255, 0.5*255], std=[0.5*255, 0.5*255, 0.5*255], inplace=True),
+ L(CreateCondition)(),
+ ),
+ infinite=True,
+ shuffle=True,
+ partial_batches=False,
+ )
+ ),
+ val=dict(
+ loader=L(get_dataloader_fdf_wds)(
+ path=data_dir.joinpath("val", "128", "out-{000000..000016}.tar"),
+ batch_size="${train.batch_size}",
+ num_workers=2,
+ transform=None,
+ gpu_transform="${data.train.loader.gpu_transform}",
+ infinite=False,
+ shuffle=False,
+ partial_batches=True,
+ )
+ ),
+ # Training evaluation might do optimizations to reduce compute overhead. E.g. compute with AMP.
+ train_evaluation_fn=L(functools.partial)(
+ train_eval_fn, cache_directory=L(get_cache_directory)(imsize="${data.imsize}", subset="fdf"),
+ data_len=50_000),
+ evaluation_fn=L(functools.partial)(
+ final_eval_fn, cache_directory=L(get_cache_directory)(imsize="${data.imsize}", subset="fdf_eval"),
+ data_len=50_000)
+)
diff --git a/project/models/deprecated_deep_privacy2/configs/datasets/fdf128_wds/fdf16.py b/project/models/deprecated_deep_privacy2/configs/datasets/fdf128_wds/fdf16.py
new file mode 100644
index 0000000..1b99ba0
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/datasets/fdf128_wds/fdf16.py
@@ -0,0 +1,9 @@
+from .fdf128 import data, data_dir
+
+data.imsize = (16, 16)
+data.val.loader.update(
+ path=data_dir.joinpath("val", "16", "out-{000000..000016}.tar"),
+)
+data.train.loader.update(
+ path=data_dir.joinpath("train", "16", "out-{000000..000473}.tar"),
+)
diff --git a/project/models/deprecated_deep_privacy2/configs/datasets/fdf128_wds/fdf32.py b/project/models/deprecated_deep_privacy2/configs/datasets/fdf128_wds/fdf32.py
new file mode 100644
index 0000000..040ab7c
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/datasets/fdf128_wds/fdf32.py
@@ -0,0 +1,9 @@
+from .fdf128 import data, data_dir
+
+data.imsize = (32, 32)
+data.val.loader.update(
+ path=data_dir.joinpath("val", "32", "out-{000000..000016}.tar"),
+)
+data.train.loader.update(
+ path=data_dir.joinpath("train", "32", "out-{000000..000473}.tar"),
+)
diff --git a/project/models/deprecated_deep_privacy2/configs/datasets/fdf128_wds/fdf64.py b/project/models/deprecated_deep_privacy2/configs/datasets/fdf128_wds/fdf64.py
new file mode 100644
index 0000000..a88f2e1
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/datasets/fdf128_wds/fdf64.py
@@ -0,0 +1,9 @@
+from .fdf128 import data, data_dir
+
+data.imsize = (64, 64)
+data.val.loader.update(
+ path=data_dir.joinpath("val", "64", "out-{000000..000016}.tar"),
+)
+data.train.loader.update(
+ path=data_dir.joinpath("train", "64", "out-{000000..000473}.tar"),
+)
diff --git a/project/models/deprecated_deep_privacy2/configs/datasets/fdf256.py b/project/models/deprecated_deep_privacy2/configs/datasets/fdf256.py
new file mode 100644
index 0000000..828802d
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/datasets/fdf256.py
@@ -0,0 +1,55 @@
+import os
+from pathlib import Path
+from tops.config import LazyCall as L
+import torch
+import functools
+from dp2.data.datasets.fdf import FDF256Dataset
+from dp2.data.build import get_dataloader
+from dp2.data.transforms.transforms import Normalize, Resize, ToFloat, CreateCondition, RandomHorizontalFlip
+from .utils import final_eval_fn, train_eval_fn
+
+
+dataset_base_dir = os.environ["BASE_DATASET_DIR"] if "BASE_DATASET_DIR" in os.environ else "data"
+metrics_cache = os.environ["FBA_METRICS_CACHE"] if "FBA_METRICS_CACHE" in os.environ else ".cache"
+data_dir = Path(dataset_base_dir, "fdf256")
+data = dict(
+ imsize=(256, 256),
+ im_channels=3,
+ semantic_nc=None,
+ cse_nc=None,
+ n_keypoints=None,
+ train=dict(
+ dataset=L(FDF256Dataset)(dirpath=data_dir.joinpath("train"), transform=None, load_keypoints=False),
+ loader=L(get_dataloader)(
+ shuffle=True, num_workers=3, drop_last=True, prefetch_factor=2,
+ batch_size="${train.batch_size}",
+ dataset="${..dataset}",
+ infinite=True,
+ gpu_transform=L(torch.nn.Sequential)(*[
+ L(ToFloat)(),
+ L(RandomHorizontalFlip)(p=0.5),
+ L(Resize)(size="${data.imsize}"),
+ L(Normalize)(mean=[.5, .5, .5], std=[.5, .5, .5], inplace=True),
+ L(CreateCondition)(),
+ ])
+ )
+ ),
+ val=dict(
+ dataset=L(FDF256Dataset)(dirpath=data_dir.joinpath("val"), transform=None, load_keypoints=False),
+ loader=L(get_dataloader)(
+ shuffle=False, num_workers=3, drop_last=False, prefetch_factor=2,
+ batch_size="${train.batch_size}",
+ dataset="${..dataset}",
+ infinite=False,
+ gpu_transform=L(torch.nn.Sequential)(*[
+ L(ToFloat)(),
+ L(Resize)(size="${data.imsize}"),
+ L(Normalize)(mean=[.5, .5, .5], std=[.5, .5, .5], inplace=True),
+ L(CreateCondition)(),
+ ])
+ )
+ ),
+ # Training evaluation might do optimizations to reduce compute overhead. E.g. compute with AMP.
+ train_evaluation_fn=functools.partial(train_eval_fn, cache_directory=Path(metrics_cache, "fdf_val_train")),
+ evaluation_fn=functools.partial(final_eval_fn, cache_directory=Path(metrics_cache, "fdf_val"))
+)
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/configs/datasets/fdh.py b/project/models/deprecated_deep_privacy2/configs/datasets/fdh.py
new file mode 100644
index 0000000..47faade
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/datasets/fdh.py
@@ -0,0 +1,90 @@
+import os
+from pathlib import Path
+from tops.config import LazyCall as L
+import torch
+import functools
+from dp2.data.datasets.fdh import get_dataloader_fdh_wds
+from dp2.data.utils import get_coco_flipmap
+from dp2.data.transforms.transforms import (
+ Normalize,
+ ToFloat,
+ CreateCondition,
+ RandomHorizontalFlip,
+ CreateEmbedding,
+)
+from dp2.metrics.torch_metrics import compute_metrics_iteratively
+from dp2.metrics.fid_clip import compute_fid_clip
+from dp2.metrics.ppl import calculate_ppl
+from .utils import train_eval_fn
+
+
+def final_eval_fn(*args, **kwargs):
+ result = compute_metrics_iteratively(*args, **kwargs)
+ result2 = calculate_ppl(*args, **kwargs, upsample_size=(288, 160))
+ result3 = compute_fid_clip(*args, **kwargs)
+ assert all(key not in result for key in result2)
+ result.update(result2)
+ result.update(result3)
+ return result
+
+
+def get_cache_directory(imsize, subset):
+ return Path(metrics_cache, f"{subset}{imsize[0]}")
+
+dataset_base_dir = (
+ os.environ["BASE_DATASET_DIR"] if "BASE_DATASET_DIR" in os.environ else "data"
+)
+metrics_cache = (
+ os.environ["FBA_METRICS_CACHE"] if "FBA_METRICS_CACHE" in os.environ else ".cache"
+)
+data_dir = Path(dataset_base_dir, "fdh")
+data = dict(
+ imsize=(288, 160),
+ im_channels=3,
+ cse_nc=16,
+ n_keypoints=17,
+ train=dict(
+ loader=L(get_dataloader_fdh_wds)(
+ path=data_dir.joinpath("train", "out-{000000..001423}.tar"),
+ batch_size="${train.batch_size}",
+ num_workers=6,
+ transform=L(torch.nn.Sequential)(
+ L(RandomHorizontalFlip)(p=0.5, flip_map=get_coco_flipmap()),
+ ),
+ gpu_transform=L(torch.nn.Sequential)(
+ L(ToFloat)(norm=False, keys=["img", "mask", "E_mask", "maskrcnn_mask"]),
+ L(CreateEmbedding)(embed_path=data_dir.joinpath("embed_map.torch")),
+ L(Normalize)(mean=[0.5*255, 0.5*255, 0.5*255], std=[0.5*255, 0.5*255, 0.5*255], inplace=True),
+ L(CreateCondition)(),
+ ),
+ infinite=True,
+ shuffle=True,
+ partial_batches=False,
+ load_embedding=True,
+ keypoints_split="train",
+ load_new_keypoints=False
+ )
+ ),
+ val=dict(
+ loader=L(get_dataloader_fdh_wds)(
+ path=data_dir.joinpath("val", "out-{000000..000023}.tar"),
+ batch_size="${train.batch_size}",
+ num_workers=6,
+ transform=None,
+ gpu_transform="${data.train.loader.gpu_transform}",
+ infinite=False,
+ shuffle=False,
+ partial_batches=True,
+ load_embedding=True,
+ keypoints_split="val",
+ load_new_keypoints="${data.train.loader.load_new_keypoints}"
+ )
+ ),
+ # Training evaluation might do optimizations to reduce compute overhead. E.g. compute with AMP.
+ train_evaluation_fn=L(functools.partial)(
+ train_eval_fn, cache_directory=L(get_cache_directory)(imsize="${data.imsize}", subset="fdh"),
+ data_len=30_000),
+ evaluation_fn=L(functools.partial)(
+ final_eval_fn, cache_directory=L(get_cache_directory)(imsize="${data.imsize}", subset="fdh_eval"),
+ data_len=30_000)
+)
diff --git a/project/models/deprecated_deep_privacy2/configs/datasets/fdh_no_embeddings.py b/project/models/deprecated_deep_privacy2/configs/datasets/fdh_no_embeddings.py
new file mode 100644
index 0000000..4275d84
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/datasets/fdh_no_embeddings.py
@@ -0,0 +1,35 @@
+
+from dp2.data.transforms.transforms import ToFloat, Normalize, CreateCondition, InsertJointMap, RandomHorizontalFlip
+from tops.config import LazyCall as L
+from dp2.data.utils import get_coco_flipmap
+from tops.config import LazyCall as L
+import torch
+from pathlib import Path
+from .fdh import data, dataset_base_dir
+data.imsize = (288, 160)
+data_dir = Path(dataset_base_dir, "fdh_no_embeddings")
+data.train.loader.update(
+ path=data_dir.joinpath("train", "out-{000000..000612}.tar"),
+ read_condition=False,
+ gpu_transform=L(torch.nn.Sequential)(
+ L(ToFloat)(keys=["img", "mask", "maskrcnn_mask"], norm=False),
+ L(Normalize)(mean=[0.5*255, 0.5*255, 0.5*255], std=[0.5*255, 0.5*255, 0.5*255], inplace=True),
+ L(CreateCondition)(),
+ ),
+ transform=L(torch.nn.Sequential)(
+ L(RandomHorizontalFlip)(p=0.5, flip_map=get_coco_flipmap()),
+ L(InsertJointMap)(imsize="${data.imsize}"),
+ ),
+ load_embedding=False,
+ load_new_keypoints=True,
+ num_workers=4,
+)
+data.val.loader.update(
+ path=data_dir.joinpath("val", "out-{000000..000010}.tar"),
+ num_workers=2,
+ read_condition=False,
+ load_embedding=False,
+ transform=L(torch.nn.Sequential)(
+ L(InsertJointMap)(imsize="${data.imsize}"),
+ )
+)
diff --git a/project/models/deprecated_deep_privacy2/configs/datasets/fdh_resampled_wds/__init__.py b/project/models/deprecated_deep_privacy2/configs/datasets/fdh_resampled_wds/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/project/models/deprecated_deep_privacy2/configs/datasets/fdh_resampled_wds/fdh144.py b/project/models/deprecated_deep_privacy2/configs/datasets/fdh_resampled_wds/fdh144.py
new file mode 100644
index 0000000..a2d548d
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/datasets/fdh_resampled_wds/fdh144.py
@@ -0,0 +1,8 @@
+from .fdh18 import data, data_dir
+data.imsize = (144, 80)
+data.val.loader.update(
+ path=data_dir.joinpath("val", "144", "out-{000000..000009}.tar"),
+)
+data.train.loader.update(
+ path=data_dir.joinpath("train", "144", "out-{000000..000609}.tar"),
+)
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/configs/datasets/fdh_resampled_wds/fdh18.py b/project/models/deprecated_deep_privacy2/configs/datasets/fdh_resampled_wds/fdh18.py
new file mode 100644
index 0000000..aee8ee1
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/datasets/fdh_resampled_wds/fdh18.py
@@ -0,0 +1,20 @@
+from pathlib import Path
+import torch
+from tops.config import LazyCall as L
+from dp2.data.transforms.transforms import Normalize, ToFloat
+from ..fdh_no_embeddings import data, dataset_base_dir
+
+data_dir = Path(dataset_base_dir, "fdh_no_embeddings_resampled/")
+data.imsize = (18, 10)
+data.val.loader.update(
+ read_condition=True,
+ path=data_dir.joinpath("val", "18", "out-{000000..000009}.tar"),
+)
+data.train.loader.update(
+ path=data_dir.joinpath("train", "18", "out-{000000..000609}.tar"),
+ read_condition=True,
+ gpu_transform=L(torch.nn.Sequential)(
+ L(ToFloat)(keys=["img", "mask", "maskrcnn_mask", "condition"], norm=False),
+ L(Normalize)(mean=[0.5*255, 0.5*255, 0.5*255], std=[0.5*255, 0.5*255, 0.5*255], inplace=True, keys=["img", "condition"]),
+ )
+)
diff --git a/project/models/deprecated_deep_privacy2/configs/datasets/fdh_resampled_wds/fdh36.py b/project/models/deprecated_deep_privacy2/configs/datasets/fdh_resampled_wds/fdh36.py
new file mode 100644
index 0000000..d795198
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/datasets/fdh_resampled_wds/fdh36.py
@@ -0,0 +1,8 @@
+from .fdh18 import data, data_dir
+data.imsize = (36, 20)
+data.val.loader.update(
+ path=data_dir.joinpath("val", "36", "out-{000000..000009}.tar"),
+)
+data.train.loader.update(
+ path=data_dir.joinpath("train", "36", "out-{000000..000609}.tar"),
+)
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/configs/datasets/fdh_resampled_wds/fdh72.py b/project/models/deprecated_deep_privacy2/configs/datasets/fdh_resampled_wds/fdh72.py
new file mode 100644
index 0000000..502ea8f
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/datasets/fdh_resampled_wds/fdh72.py
@@ -0,0 +1,8 @@
+from .fdh18 import data, data_dir
+data.imsize = (72, 40)
+data.val.loader.update(
+ path=data_dir.joinpath("val", "72", "out-{000000..000009}.tar"),
+)
+data.train.loader.update(
+ path=data_dir.joinpath("train", "72", "out-{000000..000609}.tar"),
+)
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/configs/datasets/utils.py b/project/models/deprecated_deep_privacy2/configs/datasets/utils.py
new file mode 100644
index 0000000..6704b12
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/datasets/utils.py
@@ -0,0 +1,21 @@
+from dp2.metrics.ppl import calculate_ppl
+from dp2.metrics.torch_metrics import compute_metrics_iteratively
+from dp2.metrics.fid_clip import compute_fid_clip
+
+
+def final_eval_fn(*args, **kwargs):
+ result = compute_metrics_iteratively(*args, **kwargs)
+ result2 = calculate_ppl(*args, **kwargs,)
+ result3 = compute_fid_clip(*args, **kwargs)
+ assert all(key not in result for key in result2)
+ result.update(result2)
+ result.update(result3)
+ return result
+
+
+def train_eval_fn(*args, **kwargs):
+ result = compute_metrics_iteratively(*args, **kwargs)
+ result2 = compute_fid_clip(*args, **kwargs)
+ assert all(key not in result for key in result2)
+ result.update(result2)
+ return result
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/configs/defaults.py b/project/models/deprecated_deep_privacy2/configs/defaults.py
new file mode 100644
index 0000000..4f83120
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/defaults.py
@@ -0,0 +1,53 @@
+import pathlib
+import os
+import torch
+from tops.config import LazyCall as L
+
+if "PRETRAINED_CHECKPOINTS_PATH" in os.environ:
+ PRETRAINED_CHECKPOINTS_PATH = pathlib.Path(os.environ["PRETRAINED_CHECKPOINTS_PATH"])
+else:
+ PRETRAINED_CHECKPOINTS_PATH = pathlib.Path("pretrained_checkpoints")
+if "BASE_OUTPUT_DIR" in os.environ:
+ BASE_OUTPUT_DIR = pathlib.Path(os.environ["BASE_OUTPUT_DIR"])
+else:
+ BASE_OUTPUT_DIR = pathlib.Path("outputs")
+
+
+
+common = dict(
+ logger_backend=["wandb", "stdout", "json", "image_dumper"],
+ wandb_project="deep_privacy2",
+ output_dir=BASE_OUTPUT_DIR,
+ experiment_name=None, # Optional experiment name to show on wandb
+)
+
+train = dict(
+ batch_size=32,
+ seed=0,
+ ims_per_log=1024,
+ ims_per_val=int(200e3),
+ max_images_to_train=int(12e6),
+ amp=dict(
+ enabled=True,
+ scaler_D=L(torch.cuda.amp.GradScaler)(init_scale=2**16, growth_factor=4, growth_interval=100, enabled="${..enabled}"),
+ scaler_G=L(torch.cuda.amp.GradScaler)(init_scale=2**16, growth_factor=4, growth_interval=100, enabled="${..enabled}"),
+ ),
+ fp16_ddp_accumulate=False, # All gather gradients in fp16?
+ broadcast_buffers=False,
+ bias_act_plugin_enabled=True,
+ grid_sample_gradfix_enabled=True,
+ conv2d_gradfix_enabled=False,
+ channels_last=False,
+ compile_G=dict(
+ enabled=False,
+ mode="default" # default, reduce-overhead or max-autotune
+ ),
+ compile_D=dict(
+ enabled=False,
+ mode="default" # default, reduce-overhead or max-autotune
+ )
+)
+
+# exponential moving average
+EMA = dict(rampup=0.05)
+
diff --git a/project/models/deprecated_deep_privacy2/configs/discriminators/projected_discriminator.py b/project/models/deprecated_deep_privacy2/configs/discriminators/projected_discriminator.py
new file mode 100644
index 0000000..c447ac0
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/discriminators/projected_discriminator.py
@@ -0,0 +1,161 @@
+from functools import partial
+import torch
+from dp2.discriminator.projected_gan import ProjectedDiscriminator
+from dp2.discriminator.projected_gan.feature_nets import (
+ _make_efficientnet,
+ _make_resnet50_clip,
+ _make_resnet50_cse,
+ _make_resnet50,
+)
+from dp2.discriminator.projected_gan.vit import _make_vit_timm
+from dp2.discriminator.projected_gan.vit_openclip import OpenCLIPViT
+
+from dp2.loss.projected_gan_loss import ProjectedGANLoss, blur
+from tops.config import LazyCall as L
+
+imagenet_norm = dict(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
+inception_norm = dict(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
+clip_norm = dict(
+ mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711]
+)
+
+VIT_PATCH_MAE = dict(
+ backbone_cfg=L(_make_vit_timm)(
+ model_name="vit_base_patch16_224",
+ weight_path="https://dl.fbaipublicfiles.com/mae/pretrain/mae_pretrain_vit_base.pth",
+ ),
+ interp_size=None,
+ input_BGR=False,
+ jit_script=False,
+ **imagenet_norm
+)
+VIT_PATCH_MAE_LARGE = dict(
+ backbone_cfg=L(_make_vit_timm)(
+ model_name="vit_large_patch16_224",
+ weight_path="https://dl.fbaipublicfiles.com/mae/pretrain/mae_pretrain_vit_large.pth",
+ ),
+ interp_size=None,
+ input_BGR=False,
+ jit_script=False,
+ **imagenet_norm
+)
+VIT_PATCH_MAE_HUGE = dict(
+ backbone_cfg=L(_make_vit_timm)(
+ model_name="vit_huge_patch14_224",
+ weight_path="https://dl.fbaipublicfiles.com/mae/pretrain/mae_pretrain_vit_huge.pth",
+ ),
+ interp_size=None,
+ input_BGR=False,
+ jit_script=False,
+ **imagenet_norm
+)
+VIT_DINO_S = dict(
+ backbone_cfg=L(_make_vit_timm)(
+ model_name="vit_small_patch16_224",
+ weight_path="https://dl.fbaipublicfiles.com/dino/dino_deitsmall16_pretrain/dino_deitsmall16_pretrain.pth"
+ ),
+ interp_size=(224, 224),
+ input_BGR=False,
+ jit_script=False,
+ **imagenet_norm
+)
+VIT_DINO_B = dict(
+ backbone_cfg=L(_make_vit_timm)(
+ model_name="vit_base_patch16_224",
+ weight_path="https://dl.fbaipublicfiles.com/dino/dino_vitbase16_pretrain/dino_vitbase16_pretrain.pth"
+ ),
+ interp_size=(224, 224),
+ input_BGR=False,
+ jit_script=False,
+ **imagenet_norm
+)
+
+tf_efficientnet_lite0 = dict(
+ backbone_cfg=L(_make_efficientnet)(model_type="tf_efficientnet_lite0"),
+ interp_size=None,
+ input_BGR=False,
+ jit_script=True,
+ **inception_norm
+)
+RN50_CSE = dict(
+ backbone_cfg=L(_make_resnet50_cse)(
+ cfg_url="https://raw.githubusercontent.com/facebookresearch/detectron2/main/projects/DensePose/configs/cse/densepose_rcnn_R_50_FPN_s1x.yaml"
+ ),
+ interp_size=None,
+ mean=[0.485, 0.456, 0.406],
+ std=[1 / 255, 1 / 255, 1 / 255],
+ input_BGR=True,
+ jit_script=False
+)
+RN50_CLIP = dict(
+ backbone_cfg=L(_make_resnet50_clip)(),
+ interp_size=None,
+ input_BGR=False,
+ jit_script=False,
+ **clip_norm
+)
+RN50_IN = dict(
+ backbone_cfg=L(_make_resnet50)(),
+ interp_size=None,
+ input_BGR=False,
+ jit_script=False,
+ **imagenet_norm
+)
+
+deit_base_distilled_patch16_224 = dict(
+ backbone_cfg=L(_make_vit_timm)(
+ model_name="deit_base_distilled_patch16_224", weight_path=None
+ ),
+ interp_size=(224, 224),
+ input_BGR=False,
+ jit_script=False,
+ **imagenet_norm
+)
+
+openclip_vit_b_32 = dict(
+ backbone_cfg=L(OpenCLIPViT)(
+ model_name="ViT-B-32",
+ pretrained_dataset="laion2b_s34b_b79k",
+ ),
+ input_BGR=False,
+ jit_script=False,
+ interp_size=(224, 224),
+ **clip_norm # Not sure if norm is correct for L-14 / B-32
+)
+openclip_vit_b_16 = dict(
+ backbone_cfg=L(OpenCLIPViT)(
+ model_name="ViT-B-16",
+ pretrained_dataset="openai",
+ ),
+ input_BGR=False,
+ jit_script=False,
+ interp_size=(224, 224),
+ **clip_norm
+)
+openclip_vit_l_14 = dict(
+ backbone_cfg=L(OpenCLIPViT)(
+ model_name="ViT-L-14",
+ pretrained_dataset="laion2b_s32b_b82k",
+ ),
+ input_BGR=False,
+ jit_script=False,
+ interp_size=(224, 224),
+ **clip_norm # Not sure if norm is correct for L-14 / B-32
+)
+
+
+discriminator = L(ProjectedDiscriminator)(
+ num_discs=4,
+ patch=True,
+ diffaug_policy=["color", "cutout"],
+ backbones=[VIT_PATCH_MAE],
+ last_ksize=3,
+)
+
+loss_fnc = L(ProjectedGANLoss)(
+ aug_fade_kimg=int(400e3),
+ blur_init_sigma=4,
+)
+
+D_optim = L(torch.optim.Adam)(lr=0.002, betas=(0.0, 0.99))
+G_optim = L(torch.optim.Adam)(lr=0.002, betas=(0.0, 0.99))
diff --git a/project/models/deprecated_deep_privacy2/configs/discriminators/sg2_discriminator.py b/project/models/deprecated_deep_privacy2/configs/discriminators/sg2_discriminator.py
new file mode 100644
index 0000000..081ebfb
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/discriminators/sg2_discriminator.py
@@ -0,0 +1,43 @@
+from tops.config import LazyCall as L
+from dp2.discriminator import SG2Discriminator
+import torch
+from dp2.loss import StyleGAN2Loss
+
+
+discriminator = L(SG2Discriminator)(
+ imsize="${data.imsize}",
+ im_channels="${data.im_channels}",
+ min_fmap_resolution=4,
+ max_cnum_mul=8,
+ cnum=80,
+ input_condition=True,
+ conv_clamp=256,
+ input_cse=False,
+ cse_nc="${data.cse_nc}",
+ fix_residual=False,
+)
+
+
+loss_fnc = L(StyleGAN2Loss)(
+ lazy_regularization=True,
+ lazy_reg_interval=16,
+ r1_opts=dict(lambd=5, mask_out=False, mask_out_scale=False),
+ EP_lambd=0.001,
+ pl_reg_opts=dict(weight=0, batch_shrink=2,start_nimg=int(1e6), pl_decay=0.01)
+)
+
+def build_D_optim(type, lr, betas, lazy_regularization, lazy_reg_interval, **kwargs):
+ if lazy_regularization:
+ # From Analyzing and improving the image quality of stylegan, CVPR 2020
+ c = lazy_reg_interval / (lazy_reg_interval + 1)
+ betas = [beta ** c for beta in betas]
+ lr *= c
+ print(f"Lazy regularization on. Setting lr to: {lr}, betas to: {betas}")
+ return type(lr=lr, betas=betas, **kwargs)
+
+
+D_optim = L(build_D_optim)(
+ type=torch.optim.Adam, lr=0.001, betas=(0.0, 0.99),
+ lazy_regularization="${loss_fnc.lazy_regularization}",
+ lazy_reg_interval="${loss_fnc.lazy_reg_interval}")
+G_optim = L(torch.optim.Adam)(lr=0.001, betas=(0.0, 0.99))
diff --git a/project/models/deprecated_deep_privacy2/configs/fdf/deep_privacy1.py b/project/models/deprecated_deep_privacy2/configs/fdf/deep_privacy1.py
new file mode 100644
index 0000000..4ab2b54
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdf/deep_privacy1.py
@@ -0,0 +1,9 @@
+from tops.config import LazyCall as L
+from dp2.generator.deep_privacy1 import MSGGenerator
+from ..datasets.fdf128 import data
+from ..defaults import common, train
+
+generator = L(MSGGenerator)()
+
+common.model_url = "https://api.loke.aws.unit.no/dlr-gui-backend-resources-content/v2/contents/links/0940803d-1a2c-4b54-9c1d-0d3aeb80c5a8970f7dd4-bde6-4120-9d3e-5fad937eef2b7b0544e2-8c00-43c2-9193-f56679740872"
+common.model_md5sum = "6cc8b285bdc1fcdfc64f5db7c521d0a6"
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/configs/fdf/stylegan.py b/project/models/deprecated_deep_privacy2/configs/fdf/stylegan.py
new file mode 100644
index 0000000..a4da2c3
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdf/stylegan.py
@@ -0,0 +1,14 @@
+from ..generators.stylegan_unet import generator
+from ..datasets.fdf256 import data
+from ..discriminators.sg2_discriminator import discriminator, G_optim, D_optim, loss_fnc
+from ..defaults import train, common, EMA
+
+train.max_images_to_train = int(35e6)
+G_optim.lr = 0.002
+D_optim.lr = 0.002
+generator.input_cse = False
+loss_fnc.r1_opts.lambd = 1
+train.ims_per_val = int(2e6)
+
+common.model_url = "https://api.loke.aws.unit.no/dlr-gui-backend-resources-content/v2/contents/links/89660f04-5c11-4dbf-adac-cbe2f11b0aeea25cbf78-7558-475a-b3c7-03f5c10b7934646b0720-ca0a-4d53-aded-daddbfa45c9e"
+common.model_md5sum = "e8e32190528af2ed75f0cb792b7f2b07"
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/configs/fdf/stylegan_fdf128.py b/project/models/deprecated_deep_privacy2/configs/fdf/stylegan_fdf128.py
new file mode 100644
index 0000000..a47d6d2
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdf/stylegan_fdf128.py
@@ -0,0 +1,17 @@
+from ..discriminators.sg2_discriminator import discriminator, G_optim, D_optim, loss_fnc
+from ..datasets.fdf128 import data
+from ..generators.stylegan_unet import generator
+from ..defaults import train, common, EMA
+from tops.config import LazyCall as L
+
+G_optim.lr = 0.002
+D_optim.lr = 0.002
+generator.update(cnum=128, max_cnum_mul=4, input_cse=False)
+loss_fnc.r1_opts.lambd = 0.1
+
+train.update(ims_per_val=int(2e6), batch_size=64, max_images_to_train=int(35e6))
+
+common.update(
+ model_url="https://api.loke.aws.unit.no/dlr-gui-backend-resources-content/v2/contents/links/66d803c0-55ce-44c0-9d53-815c2c0e6ba4eb458409-9e91-45d1-bce0-95c8a47a57218b102fdf-bea3-44dc-aac4-0fb1d370ef1c",
+ model_md5sum="bccd4403e7c9bca682566ff3319e8176"
+)
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/configs/fdf/triagan_L.py b/project/models/deprecated_deep_privacy2/configs/fdf/triagan_L.py
new file mode 100644
index 0000000..7fa153a
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdf/triagan_L.py
@@ -0,0 +1,42 @@
+from ..discriminators.projected_discriminator import (
+ G_optim,
+ D_optim,
+ loss_fnc,
+ discriminator,
+ VIT_PATCH_MAE_LARGE,
+ RN50_CLIP
+)
+from ..defaults import common, EMA, train
+from ..datasets.fdf128_wds.fdf128 import data
+from ..generators.triagan import generator, ckpt_mapper
+
+train.update(
+ batch_size=128,
+ ims_per_log=1024 * 20,
+ ims_per_val=int(2.4e6),
+ max_images_to_train=int(77e6),
+ broadcast_buffers=True,
+ fp16_ddp_accumulate=True,
+)
+loss_fnc.aug_fade_kimg = int(4e6)
+
+generator.update(
+ dim_mults=[1, 2, 2, 2, 2],
+ dim=256,
+ imsize="${data.imsize}",
+ use_maskrcnn_mask=False,
+ input_keypoint_indices=list(range(3)),
+ input_keypoints=True,
+ use_noise=True,
+ layer_scale=False,
+ input_joint=False,
+ num_resnet_blocks=2
+)
+
+VIT_PATCH_MAE_LARGE.interp_size = (224, 224)
+RN50_CLIP.interp_size = (224, 224)
+discriminator.update(
+ backbones=[RN50_CLIP, VIT_PATCH_MAE_LARGE],
+)
+common.model_md5sum = "7b94366d9d2e1e9a6491e065491fda87"
+common.model_url = "https://api.loke.aws.unit.no/dlr-gui-backend-resources-content/v2/contents/links/88e98c73-e890-489d-a3eb-cf6fbf1728f531b0047f-ddf3-4188-8028-2b55c580ac6da54d9760-e395-4f2a-8890-743f3562e1b3"
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/styleganL.py b/project/models/deprecated_deep_privacy2/configs/fdh/styleganL.py
new file mode 100644
index 0000000..48fcf09
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/styleganL.py
@@ -0,0 +1,16 @@
+from tops.config import LazyCall as L
+from ..generators.stylegan_unet import generator
+from ..datasets.fdh import data
+from ..discriminators.sg2_discriminator import discriminator, G_optim, D_optim, loss_fnc
+from ..defaults import train, common, EMA
+
+train.max_images_to_train = int(50e6)
+train.batch_size = 64
+G_optim.lr = 0.002
+D_optim.lr = 0.002
+data.train.loader.num_workers = 4
+train.ims_per_val = int(1e6)
+loss_fnc.r1_opts.lambd = .1
+
+common.model_url = "https://api.loke.aws.unit.no/dlr-gui-backend-resources-content/v2/contents/links/21841da7-2546-4ce3-8460-909b3a63c58b13aac1a1-c778-4c8d-9b69-3e5ed2cde9de1524e76e-7aa6-4dd8-b643-52abc9f0792c"
+common.model_md5sum = "3411478b5ec600a4219cccf4499732bd"
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/styleganL_nocse.py b/project/models/deprecated_deep_privacy2/configs/fdh/styleganL_nocse.py
new file mode 100644
index 0000000..210fd68
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/styleganL_nocse.py
@@ -0,0 +1,14 @@
+from tops.config import LazyCall as L
+from ..generators.stylegan_unet import generator
+from ..datasets.fdh import data
+from ..discriminators.sg2_discriminator import discriminator, G_optim, D_optim, loss_fnc
+from ..defaults import train, common, EMA
+
+train.max_images_to_train = int(50e6)
+G_optim.lr = 0.002
+D_optim.lr = 0.002
+generator.input_cse = False
+data.load_embeddings = False
+common.model_url = "https://folk.ntnu.no/haakohu/checkpoints/deep_privacy2/fdh_styleganL_nocse.ckpt"
+common.model_md5sum = "fda0d809741bc67487abada793975c37"
+generator.fix_errors = False
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/triagan/L_im144.py b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/L_im144.py
new file mode 100644
index 0000000..0c3ea4a
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/L_im144.py
@@ -0,0 +1,15 @@
+from .L_im72 import (
+ G_optim, D_optim, loss_fnc, common, EMA, train,
+ generator, discriminator, ckpt_mapper
+)
+from ...datasets.fdh_resampled_wds.fdh144 import data
+generator.update(
+ dim=256,
+ dim_mults=[1, 2, 2, 2,2],
+)
+
+train.update(
+ generator_init_cfg="configs/fdh/triagan/L_im72.py",
+)
+train.max_images_to_train = int(110e6)
+train.batch_size = 512
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/triagan/L_im18.py b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/L_im18.py
new file mode 100644
index 0000000..13d7ecc
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/L_im18.py
@@ -0,0 +1,35 @@
+from ...discriminators.projected_discriminator import (
+ G_optim,
+ D_optim,
+ loss_fnc,
+ discriminator,
+ VIT_PATCH_MAE_LARGE,
+ RN50_CLIP
+)
+from ...defaults import common, EMA, train
+from dp2.data.utils import get_coco_keypoints
+from ...generators.triagan import generator, ckpt_mapper
+from ...datasets.fdh_resampled_wds.fdh18 import data
+
+train.update(
+ batch_size=1024,
+ ims_per_log=1024 * 20,
+ ims_per_val=int(10e6),
+ max_images_to_train=int(300e6),
+ broadcast_buffers=True,
+ fp16_ddp_accumulate=True,
+)
+loss_fnc.aug_fade_kimg = int(4e6)
+
+generator.update(
+ input_keypoint_indices=list(range(len(get_coco_keypoints()))),
+ input_keypoints=True,
+ num_resnet_blocks=2,
+)
+
+loss_fnc.loss_type = "masked-hinge"
+VIT_PATCH_MAE_LARGE.interp_size = (224, 224)
+RN50_CLIP.interp_size = (288, 160)
+discriminator.update(
+ backbones=[VIT_PATCH_MAE_LARGE, RN50_CLIP],
+)
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/triagan/L_im288.py b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/L_im288.py
new file mode 100644
index 0000000..a03aa9d
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/L_im288.py
@@ -0,0 +1,27 @@
+from .L_im144 import (
+ G_optim, D_optim, loss_fnc, common, EMA, train,
+ generator, discriminator, ckpt_mapper
+)
+from ...datasets.fdh_no_embeddings import data
+from ...discriminators.projected_discriminator import (
+ VIT_PATCH_MAE_LARGE,
+ RN50_CLIP
+)
+from functools import partial
+from tops.config import LazyCall as L
+generator.update(
+ dim=128,
+ dim_mults=[1, 2, 4, 4, 4, 4],
+)
+train.update(
+ generator_init_cfg="configs/fdh/triagan/L_im144.py",
+)
+train.max_images_to_train = int(70e6)
+train.batch_size = 128
+VIT_PATCH_MAE_LARGE.interp_size = (224, 224)
+RN50_CLIP.interp_size = None
+discriminator.update(
+ backbones=[VIT_PATCH_MAE_LARGE, RN50_CLIP],
+)
+common.model_url = "https://api.loke.aws.unit.no/dlr-gui-backend-resources-content/v2/contents/links/e62a306a-5295-47dd-8a0e-4f7c05b9ecd44c9fbc76-5ce2-4dd0-9454-04776bef2745659fbec7-fa0a-485b-8501-c94a2439b601"
+common.model_md5sum = "b649410e831b45f7800a89c738b411ce"
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/triagan/L_im36.py b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/L_im36.py
new file mode 100644
index 0000000..6b96da3
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/L_im36.py
@@ -0,0 +1,13 @@
+from .L_im18 import (
+ G_optim, D_optim, loss_fnc, common, EMA, train,
+ generator, discriminator, ckpt_mapper
+)
+from ...datasets.fdh_resampled_wds.fdh36 import data
+generator.update(
+ dim_mults=[1, 1, 1],
+)
+
+train.update(
+ generator_init_cfg="configs/fdh/triagan/L_im18.py",
+)
+train.max_images_to_train = int(200e6)
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/triagan/L_im72.py b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/L_im72.py
new file mode 100644
index 0000000..1e7d263
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/L_im72.py
@@ -0,0 +1,16 @@
+from .L_im36 import (
+ G_optim, D_optim, loss_fnc, common, EMA, train,
+ generator, discriminator, ckpt_mapper
+)
+from ...datasets.fdh_resampled_wds.fdh72 import data
+generator.update(
+ dim_mults=[1, 1, 1, 1],
+)
+
+train.update(
+ generator_init_cfg="configs/fdh/triagan/L_im36.py",
+)
+train.max_images_to_train = int(160e6)
+
+common.model_md5sum = "291b9374a8f004fb9a2cfce59249be58"
+common.model_url = "https://api.loke.aws.unit.no/dlr-gui-backend-resources-content/v2/contents/links/57f4101a-e1b7-414d-b616-ce4d71586fc7379379b4-c16e-41ba-aa3f-cd0f5af1ae94ecbce694-137f-4c80-8f7c-0b7ed6ace39f"
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/PG/im18.py b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/PG/im18.py
new file mode 100644
index 0000000..f106364
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/PG/im18.py
@@ -0,0 +1,8 @@
+from ..base import generator, discriminator, D_optim, G_optim, common, EMA, train, loss_fnc
+from .....datasets.fdh_resampled_wds.fdh18 import data
+
+generator.update(
+ dim_mults=[1, 1],
+ layer_scale=True,
+)
+train.max_images_to_train = int(76e6)
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/PG/im36.py b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/PG/im36.py
new file mode 100644
index 0000000..b3e89c6
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/PG/im36.py
@@ -0,0 +1,14 @@
+from .im18 import (
+ G_optim, D_optim, loss_fnc, common, EMA, train,
+ generator, discriminator
+)
+from .....datasets.fdh_resampled_wds.fdh36 import data
+
+generator.update(
+ dim_mults=[1, 1, 1],
+)
+
+train.update(
+ generator_init_cfg="configs/fdh/triagan/ablations/PG/im18.py",
+)
+train.max_images_to_train = int(61e6)
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/PG/im72.py b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/PG/im72.py
new file mode 100644
index 0000000..9f08d51
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/PG/im72.py
@@ -0,0 +1,14 @@
+from .im18 import (
+ G_optim, D_optim, loss_fnc, common, EMA, train,
+ generator, discriminator
+)
+from .....datasets.fdh_resampled_wds.fdh72 import data
+
+generator.update(
+ dim_mults=[1, 1, 1, 1],
+)
+
+train.update(
+ generator_init_cfg="configs/fdh/triagan/ablations/PG/im36.py",
+)
+train.max_images_to_train = int(50e6)
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/base.py b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/base.py
new file mode 100644
index 0000000..06cd483
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/base.py
@@ -0,0 +1,27 @@
+from ..L_im18 import (
+ generator,
+ discriminator,
+ D_optim,
+ G_optim,
+ common,
+ EMA,
+ train,
+ loss_fnc,
+ ckpt_mapper,
+)
+from ....datasets.fdh_resampled_wds.fdh72 import data
+
+
+train.update(
+ batch_size=512,
+ max_images_to_train=int(50e6),
+)
+
+generator.update(
+ dim_mults=[1, 1, 1, 1],
+ dim=512,
+ num_resnet_blocks=1,
+ layer_scale=False,
+ use_noise=False,
+)
+loss_fnc.loss_type = "hinge"
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_CLIP.py b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_CLIP.py
new file mode 100644
index 0000000..784dd28
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_CLIP.py
@@ -0,0 +1,20 @@
+from ..base import (
+ G_optim,
+ D_optim,
+ loss_fnc,
+ common,
+ EMA,
+ train,
+ data,
+ generator,
+ discriminator,
+ ckpt_mapper,
+)
+from .....discriminators.projected_discriminator import (
+ RN50_CLIP,
+)
+
+RN50_CLIP.interp_size = (288, 160)
+discriminator.update(
+ backbones=[RN50_CLIP],
+)
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_CLIP_MAD.py b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_CLIP_MAD.py
new file mode 100644
index 0000000..96893e2
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_CLIP_MAD.py
@@ -0,0 +1,14 @@
+from .im72_CLIP import (
+ G_optim,
+ D_optim,
+ loss_fnc,
+ common,
+ EMA,
+ train,
+ data,
+ generator,
+ discriminator,
+ ckpt_mapper,
+)
+
+loss_fnc.loss_type = "masked-hinge"
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_MAE.py b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_MAE.py
new file mode 100644
index 0000000..1b8df53
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_MAE.py
@@ -0,0 +1,18 @@
+from ..base import (
+ G_optim,
+ D_optim,
+ loss_fnc,
+ common,
+ EMA,
+ train,
+ data,
+ generator,
+ discriminator,
+ ckpt_mapper,
+)
+from .....discriminators.projected_discriminator import VIT_PATCH_MAE
+
+VIT_PATCH_MAE.interp_size = (224, 224)
+discriminator.update(
+ backbones=[VIT_PATCH_MAE],
+)
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_MAEL.py b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_MAEL.py
new file mode 100644
index 0000000..f40c026
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_MAEL.py
@@ -0,0 +1,18 @@
+from ..base import (
+ G_optim,
+ D_optim,
+ loss_fnc,
+ common,
+ EMA,
+ train,
+ data,
+ generator,
+ discriminator,
+ ckpt_mapper,
+)
+from .....discriminators.projected_discriminator import VIT_PATCH_MAE_LARGE
+
+VIT_PATCH_MAE_LARGE.interp_size = (224, 224)
+discriminator.update(
+ backbones=[VIT_PATCH_MAE_LARGE],
+)
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_MAEL_MAD.py b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_MAEL_MAD.py
new file mode 100644
index 0000000..b8f1a21
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_MAEL_MAD.py
@@ -0,0 +1,14 @@
+from .im72_MAEL import (
+ G_optim,
+ D_optim,
+ loss_fnc,
+ common,
+ EMA,
+ train,
+ data,
+ generator,
+ discriminator,
+ ckpt_mapper,
+)
+
+loss_fnc.loss_type = "masked-hinge"
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_MAEL_clip.py b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_MAEL_clip.py
new file mode 100644
index 0000000..dc3962b
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_MAEL_clip.py
@@ -0,0 +1,12 @@
+from ..base import (
+ G_optim,
+ D_optim,
+ loss_fnc,
+ common,
+ EMA,
+ train,
+ data,
+ generator,
+ discriminator,
+ ckpt_mapper,
+)
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_MAEL_clip_MAD.py b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_MAEL_clip_MAD.py
new file mode 100644
index 0000000..d47b6b1
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_MAEL_clip_MAD.py
@@ -0,0 +1,14 @@
+from .im72_MAEL_clip import (
+ G_optim,
+ D_optim,
+ loss_fnc,
+ common,
+ EMA,
+ train,
+ data,
+ generator,
+ discriminator,
+ ckpt_mapper,
+)
+
+loss_fnc.loss_type = "masked-hinge"
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_MAE_MAD.py b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_MAE_MAD.py
new file mode 100644
index 0000000..dcac8e5
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_MAE_MAD.py
@@ -0,0 +1,14 @@
+from .im72_MAE import (
+ G_optim,
+ D_optim,
+ loss_fnc,
+ common,
+ EMA,
+ train,
+ data,
+ generator,
+ discriminator,
+ ckpt_mapper,
+)
+
+loss_fnc.loss_type = "masked-hinge"
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_MAE_clip.py b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_MAE_clip.py
new file mode 100644
index 0000000..36adf0c
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_MAE_clip.py
@@ -0,0 +1,19 @@
+from ..base import (
+ G_optim,
+ D_optim,
+ loss_fnc,
+ common,
+ EMA,
+ train,
+ data,
+ generator,
+ discriminator,
+ ckpt_mapper,
+)
+from .....discriminators.projected_discriminator import VIT_PATCH_MAE_LARGE, RN50_CLIP
+
+VIT_PATCH_MAE_LARGE.interp_size = (224, 224)
+RN50_CLIP.interp_size = (288, 160)
+discriminator.update(
+ backbones=[VIT_PATCH_MAE_LARGE, RN50_CLIP],
+)
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_MAE_clip_MAD.py b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_MAE_clip_MAD.py
new file mode 100644
index 0000000..ce6f58d
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_MAE_clip_MAD.py
@@ -0,0 +1,14 @@
+from .im72_MAE_clip import (
+ G_optim,
+ D_optim,
+ loss_fnc,
+ common,
+ EMA,
+ train,
+ data,
+ generator,
+ discriminator,
+ ckpt_mapper,
+)
+
+loss_fnc.loss_type = "masked-hinge"
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_VIT_CLIP.py b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_VIT_CLIP.py
new file mode 100644
index 0000000..6e98de2
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_VIT_CLIP.py
@@ -0,0 +1,18 @@
+from ..base import (
+ G_optim,
+ D_optim,
+ loss_fnc,
+ common,
+ EMA,
+ train,
+ data,
+ generator,
+ discriminator,
+ ckpt_mapper,
+)
+from .....discriminators.projected_discriminator import openclip_vit_b_16
+
+openclip_vit_b_16.interp_size = (224, 224)
+discriminator.update(
+ backbones=[openclip_vit_b_16],
+)
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_VIT_CLIP_MAD.py b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_VIT_CLIP_MAD.py
new file mode 100644
index 0000000..b96a14c
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_VIT_CLIP_MAD.py
@@ -0,0 +1,14 @@
+from .im72_VIT_CLIP import (
+ G_optim,
+ D_optim,
+ loss_fnc,
+ common,
+ EMA,
+ train,
+ data,
+ generator,
+ discriminator,
+ ckpt_mapper,
+)
+
+loss_fnc.loss_type = "masked-hinge"
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_VIT_IN.py b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_VIT_IN.py
new file mode 100644
index 0000000..621463b
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_VIT_IN.py
@@ -0,0 +1,18 @@
+from ..base import (
+ G_optim,
+ D_optim,
+ loss_fnc,
+ common,
+ EMA,
+ train,
+ data,
+ generator,
+ discriminator,
+ ckpt_mapper,
+)
+from .....discriminators.projected_discriminator import deit_base_distilled_patch16_224
+
+deit_base_distilled_patch16_224.interp_size = (224, 224)
+discriminator.update(
+ backbones=[deit_base_distilled_patch16_224],
+)
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_VIT_IN_MAD.py b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_VIT_IN_MAD.py
new file mode 100644
index 0000000..af1655d
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_VIT_IN_MAD.py
@@ -0,0 +1,14 @@
+from .im72_VIT_IN import (
+ G_optim,
+ D_optim,
+ loss_fnc,
+ common,
+ EMA,
+ train,
+ data,
+ generator,
+ discriminator,
+ ckpt_mapper,
+)
+
+loss_fnc.loss_type = "masked-hinge"
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_effnet.py b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_effnet.py
new file mode 100644
index 0000000..a87f3d2
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_effnet.py
@@ -0,0 +1,20 @@
+from ..base import (
+ G_optim,
+ D_optim,
+ loss_fnc,
+ common,
+ EMA,
+ train,
+ data,
+ generator,
+ discriminator,
+ ckpt_mapper,
+)
+from .....discriminators.projected_discriminator import (
+ tf_efficientnet_lite0,
+)
+
+tf_efficientnet_lite0.interp_size = (288, 160)
+discriminator.update(
+ backbones=[tf_efficientnet_lite0],
+)
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_effnet_MAD.py b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_effnet_MAD.py
new file mode 100644
index 0000000..25513ce
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_effnet_MAD.py
@@ -0,0 +1,14 @@
+from .im72_effnet import (
+ G_optim,
+ D_optim,
+ loss_fnc,
+ common,
+ EMA,
+ train,
+ data,
+ generator,
+ discriminator,
+ ckpt_mapper,
+)
+
+loss_fnc.loss_type = "masked-hinge"
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_rn50_CSE.py b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_rn50_CSE.py
new file mode 100644
index 0000000..d9a7932
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_rn50_CSE.py
@@ -0,0 +1,18 @@
+from ..base import (
+ G_optim,
+ D_optim,
+ loss_fnc,
+ common,
+ EMA,
+ train,
+ data,
+ generator,
+ discriminator,
+ ckpt_mapper,
+)
+from .....discriminators.projected_discriminator import RN50_CSE
+
+RN50_CSE.interp_size = (288, 160)
+discriminator.update(
+ backbones=[RN50_CSE],
+)
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_rn50_CSE_MAD.py b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_rn50_CSE_MAD.py
new file mode 100644
index 0000000..965fd68
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_rn50_CSE_MAD.py
@@ -0,0 +1,14 @@
+from .im72_rn50_CSE import (
+ G_optim,
+ D_optim,
+ loss_fnc,
+ common,
+ EMA,
+ train,
+ data,
+ generator,
+ discriminator,
+ ckpt_mapper,
+)
+
+loss_fnc.loss_type = "masked-hinge"
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_rn50_IN.py b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_rn50_IN.py
new file mode 100644
index 0000000..cc44c84
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_rn50_IN.py
@@ -0,0 +1,18 @@
+from ..base import (
+ G_optim,
+ D_optim,
+ loss_fnc,
+ common,
+ EMA,
+ train,
+ data,
+ generator,
+ discriminator,
+ ckpt_mapper,
+)
+from .....discriminators.projected_discriminator import RN50_IN
+
+RN50_IN.interp_size = (288, 160)
+discriminator.update(
+ backbones=[RN50_IN],
+)
diff --git a/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_rn50_IN_MAD.py b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_rn50_IN_MAD.py
new file mode 100644
index 0000000..39dacd4
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/fdh/triagan/ablations/fnets/im72_rn50_IN_MAD.py
@@ -0,0 +1,14 @@
+from .im72_rn50_IN import (
+ G_optim,
+ D_optim,
+ loss_fnc,
+ common,
+ EMA,
+ train,
+ data,
+ generator,
+ discriminator,
+ ckpt_mapper,
+)
+
+loss_fnc.loss_type = "masked-hinge"
diff --git a/project/models/deprecated_deep_privacy2/configs/generators/dummy/gaussian.py b/project/models/deprecated_deep_privacy2/configs/generators/dummy/gaussian.py
new file mode 100644
index 0000000..21434ea
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/generators/dummy/gaussian.py
@@ -0,0 +1,5 @@
+from dp2.generator.dummy_generators import GaussianBlurGenerator
+from tops.config import LazyCall as L
+from ...defaults import common
+
+generator = L(GaussianBlurGenerator)()
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/configs/generators/dummy/maskout.py b/project/models/deprecated_deep_privacy2/configs/generators/dummy/maskout.py
new file mode 100644
index 0000000..4e3b9c2
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/generators/dummy/maskout.py
@@ -0,0 +1,5 @@
+from dp2.generator.dummy_generators import MaskOutGenerator
+from tops.config import LazyCall as L
+from ...defaults import common
+
+generator = L(MaskOutGenerator)(noise="constant")
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/configs/generators/dummy/pixelation16.py b/project/models/deprecated_deep_privacy2/configs/generators/dummy/pixelation16.py
new file mode 100644
index 0000000..c0a84be
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/generators/dummy/pixelation16.py
@@ -0,0 +1,4 @@
+from dp2.generator.dummy_generators import PixelationGenerator
+from tops.config import LazyCall as L
+
+generator = L(PixelationGenerator)(pixelation_size=16)
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/configs/generators/dummy/pixelation8.py b/project/models/deprecated_deep_privacy2/configs/generators/dummy/pixelation8.py
new file mode 100644
index 0000000..65438ec
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/generators/dummy/pixelation8.py
@@ -0,0 +1,5 @@
+from dp2.generator.dummy_generators import PixelationGenerator
+from tops.config import LazyCall as L
+from ...defaults import common
+
+generator = L(PixelationGenerator)(pixelation_size=8)
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/configs/generators/stylegan_unet.py b/project/models/deprecated_deep_privacy2/configs/generators/stylegan_unet.py
new file mode 100644
index 0000000..6388592
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/generators/stylegan_unet.py
@@ -0,0 +1,22 @@
+from dp2.generator.stylegan_unet import StyleGANUnet
+from tops.config import LazyCall as L
+
+generator = L(StyleGANUnet)(
+ imsize="${data.imsize}",
+ im_channels="${data.im_channels}",
+ min_fmap_resolution=8,
+ cnum=64,
+ max_cnum_mul=8,
+ n_middle_blocks=0,
+ z_channels=512,
+ mask_output=True,
+ conv_clamp=256,
+ input_cse=True,
+ scale_grad=True,
+ cse_nc="${data.cse_nc}",
+ w_dim=512,
+ n_keypoints="${data.n_keypoints}",
+ input_keypoints=False,
+ input_keypoint_indices=[],
+ fix_errors=True
+)
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/configs/generators/triagan.py b/project/models/deprecated_deep_privacy2/configs/generators/triagan.py
new file mode 100644
index 0000000..97a34f1
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/configs/generators/triagan.py
@@ -0,0 +1,43 @@
+from dp2.generator.triagan import TriaGAN
+from functools import partial
+from tops.config import LazyCall as L
+from dp2.generator.base import SG2StyleNet
+
+generator = L(TriaGAN)(
+ im_channels="${data.im_channels}",
+ imsize="${data.imsize}",
+ dim=512,
+ dim_mults=[1, 1],
+ num_resnet_blocks=1,
+ n_middle_blocks=2,
+ z_channels=64,
+ w_dim=512,
+ norm_enc=True,
+ use_maskrcnn_mask=True,
+ input_keypoints=False,
+ input_keypoint_indices=[],
+ input_joint=True,
+ n_keypoints="${data.n_keypoints}",
+ norm_dec=True,
+ layer_scale=True,
+ use_noise=True,
+ style_net=L(SG2StyleNet)(
+ z_dim="${generator.z_channels}", w_dim="${generator.w_dim}"
+ ),
+)
+
+
+def ckpt_map_G(state: dict):
+ new_state = dict()
+ for key, item in state.items():
+ new_key = key
+ for i in range(6):
+ if key == f"decoder.to_rgb.{i}.weight":
+ new_key = "decoder.to_rgb.weight"
+ elif key == f"decoder.to_rgb.{i}.bias":
+ new_key = "decoder.to_rgb.bias"
+ new_state[new_key] = item
+ return new_state
+
+
+ckpt_mapper = L(partial)(ckpt_map_G)
diff --git a/project/models/deprecated_deep_privacy2/docs/.nojekyll b/project/models/deprecated_deep_privacy2/docs/.nojekyll
new file mode 100644
index 0000000..e69de29
diff --git a/project/models/deprecated_deep_privacy2/docs/QUICKSTART.md b/project/models/deprecated_deep_privacy2/docs/QUICKSTART.md
new file mode 100644
index 0000000..87b2737
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/docs/QUICKSTART.md
@@ -0,0 +1,42 @@
+# Getting Started
+
+## Requirements
+- Linux and MacOS (CPU only) are supported, but we recommend linux. The code is not tested on Windows, and it might be difficult to install detectron2 for windows (see [here](https://github.com/hukkelas/deep_privacy2/issues/10) for issue).
+- GPU is not required for inference.
+- 1-8 server-grade NVIDIA GPUs with at least 32GB of memory for training.
+- Python >= 3.8.
+
+## Install with Anaconda
+We recommend to setup and install pytorch with [anaconda](https://www.anaconda.com/) following the [pytorch installation instructions](https://pytorch.org/get-started/locally/).
+
+1. Clone repository: `git clone https://github.com/hukkelas/deep_privacy2/`.
+2. Install using `setup.py`:
+```
+pip install -e .
+```
+or:
+```
+pip install git+https://github.com/hukkelas/deep_privacy2/
+```
+
+## Install with Docker
+
+1. Install [nvidia-docker](https://github.com/NVIDIA/nvidia-docker) to support GPU acceleration.
+2. Build the docker image using the [Dockerfile](Dockerfile).
+```bash
+# If you're not planning to train the network (or not use wandb logging), you can remove the WANDB_API_KEY argument.
+docker build -t deep_privacy2 --build-arg WANDB_API_KEY=YOUR_WANDB_KEY --build-arg UID=$(id -u) --build-arg UNAME=$(id -un) .
+```
+3. Run the docker image with selected command:
+```
+docker run --runtime=nvidia --gpus '"device=0"' --name deep_privacy2 --ipc=host -u $(id -u) -v $PWD:/home/$(id -un) --rm deep_privacy2 python3 anonymize.py configs/anonymizers/deep_privacy1.py -i media/regjeringen.jpg -o output.png
+```
+
+
+## Environment variables
+DeepPrivacy2 uses the following environment variables:
+
+- `BASE_DATASET_DIR`: The directory where datasets are located. Defaults to `./data` if not set
+- `BASE_OUTPUT_DIR`: The directory where outputs will be saved. Defaults to `./outputs`.
+- `FBA_METRICS_CACHE`: The directory where intermediate calculations from metric calculation is saved. For example, FID statistics for real images.
+- `TORCH_HOME`: The directory where checkpoints downloaded from URL are saved.
diff --git a/project/models/deprecated_deep_privacy2/docs/_sidebar.md b/project/models/deprecated_deep_privacy2/docs/_sidebar.md
new file mode 100644
index 0000000..97eeedf
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/docs/_sidebar.md
@@ -0,0 +1,6 @@
+- [Getting started](QUICKSTART.md)
+- [Anonymization](anonymization.md)
+- [Development and Dataset Setup](training_and_development.md)
+- [Gradio Demos](gradio_demos.md)
+- [Building the Docs](building.md)
+- [Anonymizing datasets](anonymizing_datasets.md)
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/docs/anonymization.md b/project/models/deprecated_deep_privacy2/docs/anonymization.md
new file mode 100644
index 0000000..c127154
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/docs/anonymization.md
@@ -0,0 +1,120 @@
+# Anonymization
+
+## Available Models
+DeepPrivacy2 provides various anonymization models. Each model has a training config and an anonymization config.
+- Training Config details the training setup for the generative model.
+- Anonymization config details the inference setup for anonymization. The anonymization config can link to several training configs when multi-modal anonymization is used. See [here](anonymization.md#multi-modal-anonymization) for more info about multi-modal anonymization.
+
+### Face Anonymization Models
+| Dataset (Resolution) | Detection Type | Anonymization Config | Training Config | Comment |
+|----------------------|-------------------------|--------------------------------------|--------------------------------| |
+|FDF128 (128x128) | Face Bbox + 7 Keypoints | [configs/anonymizers/deep_privacy1.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/anonymizers/deep_privacy1.py) | *[configs/fdf/deep_privacy1.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/fdf/deep_privacy1.py) | Not recommended unless you have large head rotations.|
+| FDF128 (128x128) | Face Bbox | [configs/anonymizers/face_fdf128.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/anonymizers/face_fdf128.py) | [configs/fdf/stylegan_fdf128.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/fdf/stylegan_fdf128.py) | Recommended model if all faces have a resolution < 128x128.|
+| FDF256 (256x256) | Face Bbox | [configs/anonymizers/face.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/anonymizers/face.py) | [configs/fdf/stylegan.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/fdf/stylegan.py) | Recommended model if any face has a resolution > 128x128.|
+
+\*Note that the weights for [configs/fdf/deep_privacy1.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/fdf/deep_privacy1.py) are not available to retrain, as these weights are ported from the original [DeepPrivacy repository](s://github.com/hukkelas/DeepPrivacy).
+
+The **face bbox** is the bounding box detected by [DSFD](http://github.com/hukkelas/DSFD-Pytorch-Inference).
+The **7 keypoints** are the first 7 keypoints detected by a Keypoint R-CNN model trained on COCO, indicating nose, eyes, ears, and shoulders.
+
+### Full-body Anonymization Models
+
+| Detection Type | Anonymization Config | Training Config | Comment |
+|---|---|---| |
+| Segmentation Mask | [configs/anonymizers/FB_nocse.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/anonymizers/FB_nocse.py) | [configs/fdh/styleganL_nocse.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/configs/fdh/styleganL_nocse.py) | Generally produces poor quality human figures except for masks that explicitly encodes the pose of the person. |
+| CSE + Segmentation Mask | [configs/anonymizers/FB_cse.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/anonymizers/FB_cse.py) | [configs/fdh/styleganL.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/configs/fdh/styleganL.py) | Recommended model. |
+
+The FDH dataset with a resolution of 288x160 is used to train all full-body anonymization models.
+
+The **CSE** refers to surface maps from a Continuous Surface Embedding model. **Segementation mask** refers to a instance segmentation mask, where we use the output of a Mask R-CNN model trained on COCO.
+The **17 keypoints** are keypoints following the COCO format.
+
+## Using anonymize.py
+[anonymize.py](anonymize.py) is the main script for anonymization.
+
+The typical usage is
+```
+python3 anonymize.py configs/anonymizers/FB_cse.py -i path_to_image.png
+```
+where the first argument is the chosen anonymizer (see above for the different models) and the second a path to an image/folder/video.
+
+There are several optional arguments, see `python3 anonymize.py --help` for more info.
+```
+python3 anonymize.py --help
+Usage: anonymize.py [OPTIONS] CONFIG_PATH
+
+ config_path: Specify the path to the anonymization model to use.
+
+Options:
+ -i, --input_path TEXT Input path. Accepted inputs: images, videos,
+ directories.
+ -o, --output_path PATH Output path to save. Can be directory or
+ file.
+ -v, --visualize Visualize the result
+ --max-res INTEGER Maximum resolution of height/wideo
+ --start-time, --st INTEGER Start time (second) for vide anonymization
+ --end-time, --et INTEGER End time (second) for vide anonymization
+ --fps INTEGER FPS for anonymization
+ --detection-score-threshold, --dst FLOAT RANGE
+ Detection threshold, threshold applied for
+ all detection models. [0<=x<=1]
+ --visualize-detection, --vd Visualize only detections without running
+ anonymization.
+ --multi-modal-truncation, --mt Enable multi-modal truncation proposed by:
+ https://arxiv.org/pdf/2202.12211.pdf
+ --cache Enable detection caching. Will save and load
+ detections from cache.
+ --amp Use automatic mixed precision for generator
+ forward pass
+ -t, --truncation_value FLOAT RANGE
+ Latent interpolation truncation value.
+ [0<=x<=1]
+ --track Track detections over frames. Will use the
+ same latent variable (z) for tracked
+ identities.
+ --seed INTEGER Set random seed for generating images.
+ --person-generator PATH Config path to unconditional person
+ generator
+ --cse-person-generator PATH Config path to CSE-guided person generator
+ --webcam Read image from webcam feed.
+ --help Show this message and exit.
+```
+
+### Singe image anonymization
+```
+python3 anonymize.py configs/anonymizers/FB_cse.py -i path_to_image.png --output_path output.png
+```
+
+### Folder anonymization
+
+If a folder is given as the input, all image and video files in the given folder will be anonymized and placed under --output_path. The script will duplicate the directory structure/filenames in the given folder for the output.
+```
+python3 anonymize.py configs/anonymizers/FB_cse.py -i path/to/input/folder --output_path output_folder
+```
+
+### Video anonymization
+```
+python3 anonymize.py configs/anonymizers/FB_cse.py -i path_to_video.mp4 --output_path output.mp4
+```
+
+### Webcam anonymization
+```
+python3 anonymize.py configs/anonymizers/FB_cse.py --webcam
+```
+
+
+## Multi-modal anonymization
+
+DeepPrivacy2 supports anonymizing individuals detected by different modalities (e.g. faces and bodies).
+
+
+
+The following multi-modal anonymization models are provided:
+
+
+| Config File | Detection Modalities | Synthesis Configs | Modalities |
+| --- |---| ---| --- |
+| [configs/anonymizers/FB_cse_mask_face.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/anonymizers/FB_cse_mask_face.py) | CSE+Segmentation Masks, Segmentation Masks, Face bbox | [configs/fdh/styleganL.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/fdh/styleganL.py), [configs/fdh/styleganL_nocse.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/fdh/styleganL_nocse.py), [configs/fdf/stylegan.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/fdf/stylegan.py) | Bodies (detected w/CSE), bodies (not detected w/CSE), Faces|
+| [configs/anonymizers/FB_cse_mask.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/anonymizers/FB_cse_mask.py) | CSE+Segmentation Masks, Segmentation Masks | [configs/fdh/styleganL.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/fdh/styleganL.py), [configs/fdh/styleganL_nocse.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/fdh/styleganL_nocse.py), | Bodies (detected w/CSE), bodies (not detected w/CSE)|
+
+Note that combining different synthesis networks listed [previously](anonymization.md#available-models) is straightforward, see for eaxmple [configs/anonymizers/FB_cse_mask_face.py](https://github.com/hukkelas/deep_privacy2/blob/master/configs/anonymizers/FB_cse_mask_face.py).
diff --git a/project/models/deprecated_deep_privacy2/docs/anonymizing_datasets.md b/project/models/deprecated_deep_privacy2/docs/anonymizing_datasets.md
new file mode 100644
index 0000000..9f97ebc
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/docs/anonymizing_datasets.md
@@ -0,0 +1,107 @@
+# Anonymizing datasets
+
+This document contains information to reproduce the experiments from the paper "Does Image Anonymization Impact Computer Vision Training?" published at CVPR Workshop on Autonomous Driving 2023.
+
+## Dataset setup
+The paper evaluates on BDD100k, Cityscapes, and COCO. Download the datasets following the instructions from each, and keep the original datafile structure as documented for each dataset. The code expects the following folder structre for the different datasets:
+
+### BDD100k
+```
+bdd100k-directory/
+ annotated_keypoints_train.json # Can be downloaded from https://drive.google.com/file/d/1apTK26BuERnruEDqWJ2LdLQ9xoM-aRRw/view?usp=sharing
+ face_boxes_train.json # Can be downloaded from https://drive.google.com/file/d/1D2p1g8mC-0qu9AqHCIsTmvqcxBz9Ug-t/view?usp=sharing
+ images/
+ jsons/
+ labels/
+```
+### COCO
+```
+coco-directory/
+ boxes_train2017.json # Can be downloaded from https://drive.google.com/file/d/1FS9ZOymm7XMmZd_ocH-ikYioJlH6J63c/view?usp=sharing
+ boxes_val2017.json # Can be downloaded from https://drive.google.com/file/d/12B5a_apfUOr8UJK8ED2g1EX6kU1IxWsw/view?usp=sharing
+ annotations/
+ person_keypoints_train2017.json
+ captions_val2017.json
+ instances_val2017.json
+ captions_train2017.json
+ person_keypoints_val2017.json
+ instances_train2017.json
+ train2017/
+ ...
+ val2017/
+ ...
+
+```
+### Cityscapes
+```
+cityscapes-directory/
+ annotated_keypoints_train.json # Can be downloaded from https://drive.google.com/file/d/1Acv7A1hONHUH1MvaXwCHQ95-f5LUEl7c/view?usp=sharing
+ annotated_keypoints_val.json # Can be downloaded from https://drive.google.com/file/d/1WkfIhuKlcie9DjMt5IgL10FzIwUFrtkX/view?usp=sharing
+ face_boxes_train.json # Can be downloaded from https://drive.google.com/file/d/1O56H4xbx_DgIkiF1E8JTZUjYmuHgO0Bs/view?usp=sharing
+ camera/
+ gtFine/
+ leftImg8bit/
+```
+## Anonymizing
+All scripts for full-body anonymization accepts the following three config files: [configs/anonymizers/FB_triagan.py](configs/anonymizers/FB_triagan.py), [configs/anonymizers/traditional/body/gaussian.py](configs/anonymizers/traditional/body/gaussian.py), and [configs/anonymizers/traditional/body/maskout.py](configs/anonymizers/traditional/body/maskout.py).
+All scripts for face anonymization accepts the following three config files: [configs/anonymizers/face_fdf128.py](configs/anonymizers/face_fdf128.py), [configs/anonymizers/traditional/face/gaussian.py](configs/anonymizers/traditional/face/gaussian.py), and [configs/anonymizers/traditional/face/maskout.py](configs/anonymizers/traditional/face/maskout.py).
+All scripts accepts the following config files:
+
+Some of the scripts have additional arguments:
+- `--match-histogram`: Enables naive histogram matching
+- `--sampler`: Select the sampling approach of the latent variable
+- `--n-sampling-steps`: Setting this to > 1 enables histogram matching via latent optimization. Default is set to 100 for experiments in paper.
+- `--min_size`: Set the minimum resolution of bboxes to anonymize.
+
+**Note**: The path to the dataset and directory to save the anonymized dataset is hard-coded in the code. Change these yourself, all dataset sources and targets are saved under the path `/mnt/work2/haakohu/datasets` for my setup.
+
+### Anonymizing COCO
+
+**Face Anonymization:**
+
+```
+python3 -m tools.anonymization.coco.anonymize_faces configs/anonymizers/face_fdf128.py
+```
+
+We experimented with higher-resolution face anonymization for the COCO dataset. To refine the face anonymization, run:
+```
+python3 -m tools.anonymization.coco.refine_faces
+```
+Note that this has to be run **after** the low-resolution face anonymizer.
+
+**Full-body Anonymization:**
+```
+python3 -m tools.anonymization.coco.anonymize_body configs/anonymizers/FB_triagan.py
+```
+
+### Anonymizing BDD100k
+
+**Face Anonymization:**
+
+```
+python3 -m tools.anonymization.bdd100k.anonymize_face configs/anonymizers/face_fdf128.py
+```
+
+**Full-body Anonymization:**
+```
+python3 -m tools.anonymization.bdd100k.anonymize_body configs/anonymizers/FB_triagan.py
+```
+
+
+### Anonymizing Cityscapes
+
+**Face Anonymization:**
+
+```
+python3 -m tools.anonymization.cityscapes.anonymize_faces configs/anonymizers/face_fdf128.py
+```
+
+**Full-body Anonymization:**
+```
+python3 -m tools.anonymization.cityscapes.anonymize_body configs/anonymizers/FB_triagan.py
+```
+
+
+## Training the models on anonymized datasets
+
+See the paper to reproduce our experiments to train and validate on the anonymized datasets.
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/docs/building.md b/project/models/deprecated_deep_privacy2/docs/building.md
new file mode 100644
index 0000000..dc39ffe
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/docs/building.md
@@ -0,0 +1,10 @@
+# Building the Docs
+
+First, install [docsify](https://docsify.js.org/#/quickstart).
+
+Then:
+
+```
+docsify serve docs/
+```
+from the root folder.
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/docs/gradio_demos.md b/project/models/deprecated_deep_privacy2/docs/gradio_demos.md
new file mode 100644
index 0000000..b3fd7fa
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/docs/gradio_demos.md
@@ -0,0 +1,35 @@
+# Gradio Demos
+
+
+## Face Anonymization
+Test it on [Hugginface](https://huggingface.co/spaces/haakohu/deep_privacy2_face), or run it on your local computer:
+
+```
+python3 -m gradio_demos.face
+```
+
+## Full-body anonymization
+Test it on [Hugginface](https://huggingface.co/spaces/haakohu/deep_privacy2), or run it on your local computer:
+
+```
+python3 -m gradio_demos.body_cse
+```
+
+
+## Attribute guided anonymization
+DeepPrivacy2 allows for controllable anonymization through text prompts by adapting [StyleMC](https://github.com/catlab-team/stylemc).
+StyleMC finds global semantically meaningful directions in the GAN latent space by manipulating images towards a given text prompt with a [CLIP](https://github.com/openai/CLIP)-based loss.
+
+
+
+
+The repository includes a [gradio](https://gradio.app/) demo for interactive text-guided anonymization.
+To use the demo, first:
+
+1. Download the FDF256 dataset (see [here](training_and_development.md#dataset-setup)). Only the validation set is required.
+2. Run the following:
+```
+python3 attribute_guided_demo.py
+```
+
+The script will spin up a local webserver.
diff --git a/project/models/deprecated_deep_privacy2/docs/index.html b/project/models/deprecated_deep_privacy2/docs/index.html
new file mode 100644
index 0000000..b7fc5fb
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/docs/index.html
@@ -0,0 +1,25 @@
+
+
+
+
+ Document
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/project/models/deprecated_deep_privacy2/docs/media/anonymization_illustration.png b/project/models/deprecated_deep_privacy2/docs/media/anonymization_illustration.png
new file mode 100644
index 0000000..dfad22a
Binary files /dev/null and b/project/models/deprecated_deep_privacy2/docs/media/anonymization_illustration.png differ
diff --git a/project/models/deprecated_deep_privacy2/docs/media/header.png b/project/models/deprecated_deep_privacy2/docs/media/header.png
new file mode 100644
index 0000000..0899ca6
Binary files /dev/null and b/project/models/deprecated_deep_privacy2/docs/media/header.png differ
diff --git a/project/models/deprecated_deep_privacy2/docs/reproducing_triagan.md b/project/models/deprecated_deep_privacy2/docs/reproducing_triagan.md
new file mode 100644
index 0000000..34fff57
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/docs/reproducing_triagan.md
@@ -0,0 +1,43 @@
+# Reproducing results from: "Synthesizing Anyone, Anywhere, in Any Pose"
+
+The dataset for FDH has to be set up for the triagan paper. See [training_and_development](here) for more info.
+
+See the supplementary material for the paper for more information.
+
+### Table 1 results:
+#### Training
+```
+# Model A
+python3 train.py configs/fdh/triagan/ablations/fnets/im72_effnet.py
+# B
+python3 train.py configs/fdh/triagan/ablations/fnets/im72_effnet_MAD.py
+# C
+python3 train.py configs/fdh/triagan/ablations/fnets/im72_MAEL_clip_MAD.py
+# D - requires progressive growing
+python3 train.py configs/fdh/triagan/ablations/PG/im18.py
+python3 train.py configs/fdh/triagan/ablations/PG/im36.py
+python3 train.py configs/fdh/triagan/ablations/PG/im72.py
+# E - required progrssive growing
+python3 train.py configs/fdh/triagan/L_im18.py
+python3 train.py configs/fdh/triagan/L_im36.py
+python3 train.py configs/fdh/triagan/L_im72.py
+python3 train.py configs/fdh/triagan/L_im144.py
+python3 train.py configs/fdh/triagan/L_im288.py
+```
+
+#### Validation
+For each config path, you can run:
+```
+python3 -m tools.triagan.validate_triaGAN
+```
+All table 1 results are computed from the model with resolution (72x40)
+
+### Figure 3
+All models in figure 3 is included in `configs/fdh/triagan/ablations/fnets`
+
+
+### Table 2 results
+```
+python3 -m tools.triagan.validate_triaGAN configs/fdh/styleganL.py
+python3 -m tools.triagan.validate_triaGAN configs/fdh/triagan/L_im288.py
+```
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/docs/training_and_development.md b/project/models/deprecated_deep_privacy2/docs/training_and_development.md
new file mode 100644
index 0000000..de4795a
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/docs/training_and_development.md
@@ -0,0 +1,57 @@
+# Training, development and Dataset Setup
+## Training
+First, download dataset for training (see below).
+
+To start training, type the following:
+```
+python3 train.py configs/fdh/styleganL.py
+```
+The training automatically logs to [wandb](https://wandb.ai/).
+
+## Model development utility scripts
+**Dataset inspection:** To inspect the training dataset, you can use:
+```
+python3 -m tools.inspect_dataset configs/fdh/styleganL.py
+```
+
+**Sanity check:**
+```
+python3 -m tools.dryrun configs/fdh/styleganL.py
+```
+
+**Output visualization:** To visualize output of trained models:
+```
+python3 -m tools.show_examples configs/fdh/styleganL.py
+```
+
+
+## Calculating metrics
+```
+python3 validate.py configs/fdh/styleganL.py
+```
+**NOTE:** The metrics calculated with validate.py will slightly differ from training metrics, as validate.py disables automatic mixed precision.
+
+
+## Dataset Setup
+
+**Setting Data directory:**
+The default dataset directory is ./data. If you want to change the dataset directory, set the environment variable `BASE_DATASET_DIR`. For example, `export BASE_DATASET_DIR=/work/data/`.
+
+
+### FDF256
+Follow the instructions [here](https://github.com/hukkelas/FDF/blob/master/FDF256.md) to download the FDF256 dataset. The dataset should be placed in the directory: `data/fdf256`.
+
+### FDH
+Follow the instructions [here](https://www.github.com/hukkelas/FDH) to download the FDH dataset. The dataset should be placed in the directory: `data/fdh`.
+
+#### FDH for TriA-GAN paper
+
+TriA-GAN requires the FDH dataset to be prepared for progressive growing training. This can be done by first downloading the dataset to 'data/fdh'.
+Then, run:
+```
+python3 -m tools.dataset.copy_fdh_remove_embedding
+```
+Followed by
+```
+python3 -m tools.dataset.create_webdataset_progressive
+```
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/dp2/__init__.py b/project/models/deprecated_deep_privacy2/dp2/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/project/models/deprecated_deep_privacy2/dp2/anonymizer/__init__.py b/project/models/deprecated_deep_privacy2/dp2/anonymizer/__init__.py
new file mode 100644
index 0000000..32606aa
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/anonymizer/__init__.py
@@ -0,0 +1 @@
+from .anonymizer import Anonymizer
diff --git a/project/models/deprecated_deep_privacy2/dp2/anonymizer/anonymizer.py b/project/models/deprecated_deep_privacy2/dp2/anonymizer/anonymizer.py
new file mode 100644
index 0000000..de5e1bd
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/anonymizer/anonymizer.py
@@ -0,0 +1,240 @@
+from pathlib import Path
+from typing import Union, Optional
+import numpy as np
+import torch
+import tops
+import torchvision.transforms.functional as F
+from motpy import Detection, MultiObjectTracker
+from dp2.utils import load_config
+from dp2.infer import build_trained_generator
+from dp2.detection.structures import (
+ CSEPersonDetection,
+ FaceDetection,
+ PersonDetection,
+ VehicleDetection,
+)
+from tops import logger
+from stylemc import get_and_cache_direction, get_stylesW, init_affine_modules
+
+
+class Anonymizer:
+ def __init__(
+ self,
+ detector,
+ load_cache: bool = False,
+ person_G_cfg: Optional[Union[str, Path]] = None,
+ cse_person_G_cfg: Optional[Union[str, Path]] = None,
+ face_G_cfg: Optional[Union[str, Path]] = None,
+ car_G_cfg: Optional[Union[str, Path]] = None,
+ ) -> None:
+ self.detector = detector
+ self.generators = {
+ k: None
+ for k in [
+ CSEPersonDetection,
+ PersonDetection,
+ FaceDetection,
+ VehicleDetection,
+ ]
+ }
+ self.load_cache = load_cache
+ self.generator_cfgs = dict()
+ if cse_person_G_cfg is not None:
+ self.generator_cfgs[CSEPersonDetection] = load_config(cse_person_G_cfg)
+ self.generators[CSEPersonDetection] = build_trained_generator(
+ self.generator_cfgs[CSEPersonDetection]
+ )
+ tops.logger.log(f"Loaded generator from: {cse_person_G_cfg}")
+ if person_G_cfg is not None:
+ self.generator_cfgs[PersonDetection] = load_config(person_G_cfg)
+ self.generators[PersonDetection] = build_trained_generator(
+ self.generator_cfgs[PersonDetection]
+ )
+ tops.logger.log(f"Loaded generator from: {cse_person_G_cfg}")
+ if face_G_cfg is not None:
+ self.generator_cfgs[FaceDetection] = load_config(face_G_cfg)
+ self.generators[FaceDetection] = build_trained_generator(
+ self.generator_cfgs[FaceDetection]
+ )
+ tops.logger.log(f"Loaded generator from: {face_G_cfg}")
+ if car_G_cfg is not None:
+ self.generator_cfgs[VehicleDetection] = load_config(car_G_cfg)
+ self.generators[VehicleDetection] = build_trained_generator(
+ self.generator_cfgs[VehicleDetection]
+ )
+ tops.logger.log(f"Loaded generator from: {face_G_cfg}")
+ self.dl = None
+
+ def initialize_tracker(self, fps: float):
+ self.tracker = MultiObjectTracker(dt=1 / fps)
+ self.track_to_z_idx = dict()
+
+ def reset_tracker(self):
+ self.track_to_z_idx = dict()
+
+ def forward_G(
+ self,
+ G,
+ batch,
+ multi_modal_truncation: bool,
+ amp: bool,
+ z_idx: Optional[int],
+ truncation_value: float,
+ detection_type,
+ all_styles=None,
+ text_prompt=None,
+ text_prompt_strength: Optional[float] = None,
+ ):
+ batch["img"] = F.normalize(
+ batch["img"].float(),
+ [0.5 * 255, 0.5 * 255, 0.5 * 255],
+ [0.5 * 255, 0.5 * 255, 0.5 * 255],
+ )
+ batch["condition"] = batch["mask"].float() * batch["img"]
+ cfg = self.generator_cfgs[detection_type]
+ if text_prompt is not None and self.dl is None:
+ cfg.train.batch_size = 1
+ self.dl = tops.config.instantiate(cfg.data.val.loader)
+ init_affine_modules(G, batch)
+ if z_idx is None:
+ z_idx = np.random.randint(0, 2**32)
+ state = np.random.RandomState(seed=z_idx)
+ z = state.normal(size=(1, G.z_channels)).astype(np.float32)
+ z = tops.to_cuda(torch.from_numpy(z))
+ if not hasattr(G, "style_net"):
+ if multi_modal_truncation:
+ logger.warn("The current generator does not support multi-modal truncation.")
+ w = None
+ z = G.get_z(z=z, truncation_value=truncation_value)
+ elif multi_modal_truncation:
+ w = G.style_net.multi_modal_truncate(
+ truncation_value,
+ w_indices=[z_idx % len(G.style_net.w_centers)],
+ z=z,
+ )
+ else:
+ w = G.style_net.get_truncated(truncation_value, z=z)
+
+ if text_prompt is not None:
+ direction = get_and_cache_direction(cfg.output_dir, self.dl, G, text_prompt)
+ all_styles = get_stylesW(w)
+ all_styles = all_styles + direction * text_prompt_strength
+ all_styles = all_styles
+ elif all_styles is not None:
+ all_styles = next(all_styles)
+
+ with torch.cuda.amp.autocast(amp):
+ if all_styles is not None:
+ anonymized_im = G(**batch, s=iter(all_styles))["img"]
+ else:
+ anonymized_im = G(**batch, w=w)["img"]
+ anonymized_im = (anonymized_im + 1).div(2).clamp(0, 1).mul(255)
+ return anonymized_im
+
+ @torch.no_grad()
+ def anonymize_detections(
+ self, im, detection, update_identity=None, z_idx=None, **synthesis_kwargs
+ ):
+ G = self.generators[type(detection)]
+ if G is None:
+ return im
+ C, H, W = im.shape
+ if update_identity is None:
+ update_identity = [True for i in range(len(detection))]
+ for idx in range(len(detection)):
+ if not update_identity[idx]:
+ continue
+ batch = detection.get_crop(idx, im)
+ x0, y0, x1, y1 = batch.pop("boxes")[0]
+ batch = {k: tops.to_cuda(v) for k, v in batch.items()}
+ anonymized_im = self.forward_G(
+ G,
+ batch,
+ **synthesis_kwargs,
+ z_idx=None if z_idx is None else z_idx[idx],
+ detection_type=type(detection),
+ )
+
+ gim = F.resize(
+ anonymized_im[0],
+ (y1 - y0, x1 - x0),
+ interpolation=F.InterpolationMode.BICUBIC,
+ antialias=True,
+ )
+ mask = F.resize(
+ batch["mask"][0],
+ (y1 - y0, x1 - x0),
+ interpolation=F.InterpolationMode.NEAREST,
+ ).squeeze(0)
+ # Remove padding
+ pad = [max(-x0, 0), max(-y0, 0)]
+ pad = [*pad, max(x1 - W, 0), max(y1 - H, 0)]
+
+ def remove_pad(x):
+ return x[
+ ..., pad[1] : x.shape[-2] - pad[3], pad[0] : x.shape[-1] - pad[2]
+ ]
+
+ gim = remove_pad(gim)
+ mask = remove_pad(mask) > 0.5
+ x0, y0 = max(x0, 0), max(y0, 0)
+ x1, y1 = min(x1, W), min(y1, H)
+ mask = mask.logical_not()[None].repeat(3, 1, 1)
+
+ im[:, y0:y1, x0:x1][mask] = gim[mask].round().clamp(0, 255).byte()
+ return im
+
+ def visualize_detection(
+ self, im: torch.Tensor, cache_id: str = None
+ ) -> torch.Tensor:
+ im = tops.to_cuda(im)
+ all_detections = self.detector.forward_and_cache(
+ im, cache_id, load_cache=self.load_cache
+ )
+ im = im.cpu()
+ for det in all_detections:
+ im = det.visualize(im)
+ return im
+
+ @torch.no_grad()
+ def forward(
+ self,
+ im: torch.Tensor,
+ cache_id: str = None,
+ track=True,
+ detections=None,
+ **synthesis_kwargs,
+ ) -> torch.Tensor:
+ assert im.dtype == torch.uint8
+ im = tops.to_cuda(im)
+ all_detections = detections
+ if detections is None:
+ if self.load_cache:
+ all_detections = self.detector.forward_and_cache(im, cache_id, load_cache=True)
+ else:
+ all_detections = self.detector(im)
+ if hasattr(self, "tracker") and track:
+ [_.pre_process() for _ in all_detections]
+ boxes = np.concatenate([_.boxes for _ in all_detections])
+ boxes = [Detection(box) for box in boxes]
+ self.tracker.step(boxes)
+ track_ids = self.tracker.detections_matched_ids
+ z_idx = []
+ for track_id in track_ids:
+ if track_id not in self.track_to_z_idx:
+ self.track_to_z_idx[track_id] = np.random.randint(0, 2**32 - 1)
+ z_idx.append(self.track_to_z_idx[track_id])
+ z_idx = np.array(z_idx)
+ idx_offset = 0
+
+ for detection in all_detections:
+ zs = None
+ if hasattr(self, "tracker") and track:
+ zs = z_idx[idx_offset : idx_offset + len(detection)]
+ idx_offset += len(detection)
+ im = self.anonymize_detections(im, detection, z_idx=zs, **synthesis_kwargs)
+
+ return im.cpu()
+
+ def __call__(self, *args, **kwargs):
+ return self.forward(*args, **kwargs)
diff --git a/project/models/deprecated_deep_privacy2/dp2/anonymizer/histogram_match_anonymizers.py b/project/models/deprecated_deep_privacy2/dp2/anonymizer/histogram_match_anonymizers.py
new file mode 100644
index 0000000..3b93c32
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/anonymizer/histogram_match_anonymizers.py
@@ -0,0 +1,87 @@
+
+import torch
+import tops
+import numpy as np
+from kornia.color import rgb_to_hsv
+from dp2 import utils
+from kornia.enhance import histogram
+from .anonymizer import Anonymizer
+import torchvision.transforms.functional as F
+from skimage.exposure import match_histograms
+from kornia.filters import gaussian_blur2d
+
+
+class LatentHistogramMatchAnonymizer(Anonymizer):
+
+ def forward_G(
+ self,
+ G,
+ batch,
+ multi_modal_truncation: bool,
+ amp: bool,
+ z_idx: int,
+ truncation_value: float,
+ idx: int,
+ n_sampling_steps: int = 1,
+ all_styles=None,
+ ):
+ batch["img"] = F.normalize(batch["img"].float(), [0.5*255, 0.5*255, 0.5*255], [0.5*255, 0.5*255, 0.5*255])
+ batch["condition"] = batch["mask"].float() * batch["img"]
+
+ assert z_idx is None and all_styles is None, "Arguments not supported with n_sampling_steps > 1."
+ real_hls = rgb_to_hsv(utils.denormalize_img(batch["img"]))
+ real_hls[:, 0] /= 2 * torch.pi
+ indices = [1, 2]
+ hist_kwargs = dict(
+ bins=torch.linspace(0, 1, 256, dtype=torch.float32, device=tops.get_device()),
+ bandwidth=torch.tensor(1., device=tops.get_device()))
+ real_hist = [histogram(real_hls[:, i].flatten(start_dim=1), **hist_kwargs) for i in indices]
+ if multi_modal_truncation:
+ w = G.style_net.multi_modal_truncate(
+ truncation_value=truncation_value, n=batch["condition"].shape[0]).detach()
+ else:
+ w = G.style_net.get_truncated(truncation_value, n=batch["condition"].shape[0]).detach()
+ assert z_idx is None and all_styles is None, "Arguments not supported with n_sampling_steps > 1."
+ w.requires_grad = True
+ optim = torch.optim.Adam([w])
+ for j in range(n_sampling_steps):
+ with torch.set_grad_enabled(True):
+ with torch.cuda.amp.autocast(amp):
+ anonymized_im = G(**batch, truncation_value=None, w=w)["img"]
+ fake_hls = rgb_to_hsv(anonymized_im*0.5 + 0.5)
+ fake_hls[:, 0] /= 2 * torch.pi
+ fake_hist = [histogram(fake_hls[:, i].flatten(start_dim=1), **hist_kwargs) for i in indices]
+ dist = sum([utils.torch_wasserstein_loss(r, f) for r, f in zip(real_hist, fake_hist)])
+ dist.backward()
+ if w.grad.sum() == 0:
+ break
+ assert w.grad.sum() != 0
+ optim.step()
+ optim.zero_grad()
+ if dist < 0.02:
+ break
+ anonymized_im = (anonymized_im+1).div(2).clamp(0, 1).mul(255)
+ return anonymized_im
+
+
+class HistogramMatchAnonymizer(Anonymizer):
+
+ def forward_G(self, G, batch, *args, **kwargs):
+ rimg = batch["img"]
+ anonymized_im = super().forward_G(G, batch, *args, **kwargs)
+
+ equalized_gim = match_histograms(tops.im2numpy(anonymized_im.round().clamp(0, 255).byte()), tops.im2numpy(rimg))
+ if equalized_gim.dtype != np.uint8:
+ equalized_gim = equalized_gim.astype(np.float32)
+ assert equalized_gim.dtype == np.float32, equalized_gim.dtype
+ equalized_gim = tops.im2torch(equalized_gim, to_float=False)[0]
+ else:
+ equalized_gim = tops.im2torch(equalized_gim, to_float=False).float()[0]
+ equalized_gim = equalized_gim.to(device=rimg.device)
+ assert equalized_gim.dtype == torch.float32
+ gaussian_mask = 1 - (batch["maskrcnn_mask"][0].repeat(3, 1, 1) > 0.5).float()
+
+ gaussian_mask = gaussian_blur2d(gaussian_mask[None], kernel_size=[19, 19], sigma=[10, 10])[0]
+ gaussian_mask = gaussian_mask / gaussian_mask.max()
+ anonymized_im = gaussian_mask * equalized_gim + (1-gaussian_mask) * anonymized_im
+ return anonymized_im
diff --git a/project/models/deprecated_deep_privacy2/dp2/data/__init__.py b/project/models/deprecated_deep_privacy2/dp2/data/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/project/models/deprecated_deep_privacy2/dp2/data/build.py b/project/models/deprecated_deep_privacy2/dp2/data/build.py
new file mode 100644
index 0000000..ceab946
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/data/build.py
@@ -0,0 +1,40 @@
+import torch
+import tops
+from .utils import collate_fn
+
+
+def get_dataloader(
+ dataset, gpu_transform: torch.nn.Module,
+ num_workers,
+ batch_size,
+ infinite: bool,
+ drop_last: bool,
+ prefetch_factor: int,
+ shuffle,
+ channels_last=False
+ ):
+ sampler = None
+ dl_kwargs = dict(
+ pin_memory=True,
+ )
+ if infinite:
+ sampler = tops.InfiniteSampler(
+ dataset, rank=tops.rank(),
+ num_replicas=tops.world_size(),
+ shuffle=shuffle
+ )
+ elif tops.world_size() > 1:
+ sampler = torch.utils.data.DistributedSampler(
+ dataset, shuffle=shuffle, num_replicas=tops.world_size(), rank=tops.rank())
+ dl_kwargs["drop_last"] = drop_last
+ else:
+ dl_kwargs["shuffle"] = shuffle
+ dl_kwargs["drop_last"] = drop_last
+ dataloader = torch.utils.data.DataLoader(
+ dataset, sampler=sampler, collate_fn=collate_fn,
+ batch_size=batch_size,
+ num_workers=num_workers, prefetch_factor=prefetch_factor,
+ **dl_kwargs
+ )
+ dataloader = tops.DataPrefetcher(dataloader, gpu_transform, channels_last=channels_last)
+ return dataloader
diff --git a/project/models/deprecated_deep_privacy2/dp2/data/datasets/__init__.py b/project/models/deprecated_deep_privacy2/dp2/data/datasets/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/project/models/deprecated_deep_privacy2/dp2/data/datasets/coco_cse.py b/project/models/deprecated_deep_privacy2/dp2/data/datasets/coco_cse.py
new file mode 100644
index 0000000..b240932
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/data/datasets/coco_cse.py
@@ -0,0 +1,68 @@
+import pickle
+import torchvision
+import torch
+import pathlib
+import numpy as np
+from typing import Callable, Optional, Union
+from torch.hub import get_dir as get_hub_dir
+
+
+def cache_embed_stats(embed_map: torch.Tensor):
+ mean = embed_map.mean(dim=0, keepdim=True)
+ rstd = ((embed_map - mean).square().mean(dim=0, keepdim=True)+1e-8).rsqrt()
+
+ cache = dict(mean=mean, rstd=rstd, embed_map=embed_map)
+ path = pathlib.Path(get_hub_dir(), f"embed_map_stats.torch")
+ path.parent.mkdir(exist_ok=True, parents=True)
+ torch.save(cache, path)
+
+
+class CocoCSE(torch.utils.data.Dataset):
+
+ def __init__(self,
+ dirpath: Union[str, pathlib.Path],
+ transform: Optional[Callable],
+ normalize_E: bool,):
+ dirpath = pathlib.Path(dirpath)
+ self.dirpath = dirpath
+
+ self.transform = transform
+ assert self.dirpath.is_dir(),\
+ f"Did not find dataset at: {dirpath}"
+ self.image_paths, self.embedding_paths = self._load_impaths()
+ self.embed_map = torch.from_numpy(np.load(self.dirpath.joinpath("embed_map.npy")))
+ mean = self.embed_map.mean(dim=0, keepdim=True)
+ rstd = ((self.embed_map - mean).square().mean(dim=0, keepdim=True)+1e-8).rsqrt()
+ self.embed_map = (self.embed_map - mean) * rstd
+ cache_embed_stats(self.embed_map)
+
+ def _load_impaths(self):
+ image_dir = self.dirpath.joinpath("images")
+ image_paths = list(image_dir.glob("*.png"))
+ image_paths.sort()
+ embedding_paths = [
+ self.dirpath.joinpath("embedding", x.stem + ".npy") for x in image_paths
+ ]
+ return image_paths, embedding_paths
+
+ def __len__(self):
+ return len(self.image_paths)
+
+ def __getitem__(self, idx):
+ im = torchvision.io.read_image(str(self.image_paths[idx]))
+ vertices, mask, border = np.split(np.load(self.embedding_paths[idx]), 3, axis=-1)
+ vertices = torch.from_numpy(vertices.squeeze()).long()
+ mask = torch.from_numpy(mask.squeeze()).float()
+ border = torch.from_numpy(border.squeeze()).float()
+ E_mask = 1 - mask - border
+ batch = {
+ "img": im,
+ "vertices": vertices[None],
+ "mask": mask[None],
+ "embed_map": self.embed_map,
+ "border": border[None],
+ "E_mask": E_mask[None]
+ }
+ if self.transform is None:
+ return batch
+ return self.transform(batch)
diff --git a/project/models/deprecated_deep_privacy2/dp2/data/datasets/fdf.py b/project/models/deprecated_deep_privacy2/dp2/data/datasets/fdf.py
new file mode 100644
index 0000000..23f68a5
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/data/datasets/fdf.py
@@ -0,0 +1,128 @@
+import pathlib
+from typing import Tuple
+import numpy as np
+import torch
+import pathlib
+try:
+ import pyspng
+ PYSPNG_IMPORTED = True
+except ImportError:
+ PYSPNG_IMPORTED = False
+ print("Could not load pyspng. Defaulting to pillow image backend.")
+ from PIL import Image
+from tops import logger
+
+
+class FDFDataset:
+
+ def __init__(self,
+ dirpath,
+ imsize: Tuple[int],
+ load_keypoints: bool,
+ transform):
+ dirpath = pathlib.Path(dirpath)
+ self.dirpath = dirpath
+ self.transform = transform
+ self.imsize = imsize[0]
+ self.load_keypoints = load_keypoints
+ assert self.dirpath.is_dir(),\
+ f"Did not find dataset at: {dirpath}"
+ image_dir = self.dirpath.joinpath("images", str(self.imsize))
+ self.image_paths = list(image_dir.glob("*.png"))
+ assert len(self.image_paths) > 0,\
+ f"Did not find images in: {image_dir}"
+ self.image_paths.sort(key=lambda x: int(x.stem))
+ self.landmarks = np.load(self.dirpath.joinpath("landmarks.npy")).reshape(-1, 7, 2).astype(np.float32)
+
+ self.bounding_boxes = torch.load(self.dirpath.joinpath("bounding_box", f"{self.imsize}.torch"))
+ assert len(self.image_paths) == len(self.bounding_boxes)
+ assert len(self.image_paths) == len(self.landmarks)
+ logger.log(
+ f"Dataset loaded from: {dirpath}. Number of samples:{len(self)}, imsize={imsize}")
+
+ def get_mask(self, idx):
+ mask = torch.ones((1, self.imsize, self.imsize), dtype=torch.bool)
+ bounding_box = self.bounding_boxes[idx]
+ x0, y0, x1, y1 = bounding_box
+ mask[:, y0:y1, x0:x1] = 0
+ return mask
+
+ def __len__(self):
+ return len(self.image_paths)
+
+ def __getitem__(self, index):
+ impath = self.image_paths[index]
+ if PYSPNG_IMPORTED:
+ with open(impath, "rb") as fp:
+ im = pyspng.load(fp.read())
+ else:
+ with Image.open(impath) as fp:
+ im = np.array(fp)
+ im = torch.from_numpy(np.rollaxis(im, -1, 0))
+ masks = self.get_mask(index)
+ landmark = self.landmarks[index]
+ batch = {
+ "img": im,
+ "mask": masks,
+ }
+ if self.load_keypoints:
+ batch["keypoints"] = landmark
+ if self.transform is None:
+ return batch
+ return self.transform(batch)
+
+
+class FDF256Dataset:
+
+ def __init__(self,
+ dirpath,
+ load_keypoints: bool,
+ transform):
+ dirpath = pathlib.Path(dirpath)
+ self.dirpath = dirpath
+ self.transform = transform
+ self.load_keypoints = load_keypoints
+ assert self.dirpath.is_dir(),\
+ f"Did not find dataset at: {dirpath}"
+ image_dir = self.dirpath.joinpath("images")
+ self.image_paths = list(image_dir.glob("*.png"))
+ assert len(self.image_paths) > 0,\
+ f"Did not find images in: {image_dir}"
+ self.image_paths.sort(key=lambda x: int(x.stem))
+ self.landmarks = np.load(self.dirpath.joinpath("landmarks.npy")).reshape(-1, 7, 2).astype(np.float32)
+ self.bounding_boxes = torch.from_numpy(np.load(self.dirpath.joinpath("bounding_box.npy")))
+ assert len(self.image_paths) == len(self.bounding_boxes)
+ assert len(self.image_paths) == len(self.landmarks)
+ logger.log(
+ f"Dataset loaded from: {dirpath}. Number of samples:{len(self)}")
+
+ def get_mask(self, idx):
+ mask = torch.ones((1, 256, 256), dtype=torch.bool)
+ bounding_box = self.bounding_boxes[idx]
+ x0, y0, x1, y1 = bounding_box
+ mask[:, y0:y1, x0:x1] = 0
+ return mask
+
+ def __len__(self):
+ return len(self.image_paths)
+
+ def __getitem__(self, index):
+ impath = self.image_paths[index]
+ if PYSPNG_IMPORTED:
+ with open(impath, "rb") as fp:
+ im = pyspng.load(fp.read())
+ else:
+ with Image.open(impath) as fp:
+ im = np.array(fp)
+ im = torch.from_numpy(np.rollaxis(im, -1, 0))
+ masks = self.get_mask(index)
+ landmark = self.landmarks[index]
+ batch = {
+ "img": im,
+ "mask": masks,
+ }
+ if self.load_keypoints:
+ batch["keypoints"] = landmark
+ if self.transform is None:
+ return batch
+ return self.transform(batch)
diff --git a/project/models/deprecated_deep_privacy2/dp2/data/datasets/fdf128_wds.py b/project/models/deprecated_deep_privacy2/dp2/data/datasets/fdf128_wds.py
new file mode 100644
index 0000000..5af477d
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/data/datasets/fdf128_wds.py
@@ -0,0 +1,96 @@
+import torch
+import tops
+import numpy as np
+import io
+import webdataset as wds
+import os
+from ..utils import png_decoder, get_num_workers, collate_fn
+
+
+def kp_decoder(x):
+ # Keypoints are between [0, 1] for webdataset
+ keypoints = torch.from_numpy(np.load(io.BytesIO(x))).float().view(7, 2).clamp(0, 1)
+ keypoints = torch.cat((keypoints, torch.ones((7, 1))), dim=-1)
+ return keypoints
+
+
+def bbox_decoder(x):
+ return torch.from_numpy(np.load(io.BytesIO(x))).float().view(4)
+
+
+class BBoxToMask:
+
+ def __call__(self, sample):
+ imsize = sample["image.png"].shape[-1]
+ bbox = sample["bounding_box.npy"] * imsize
+ x0, y0, x1, y1 = np.round(bbox).astype(np.int64)
+ mask = torch.ones((1, imsize, imsize), dtype=torch.bool)
+ mask[:, y0:y1, x0:x1] = 0
+ sample["mask"] = mask
+ return sample
+
+
+def get_dataloader_fdf_wds(
+ path,
+ batch_size: int,
+ num_workers: int,
+ transform: torch.nn.Module,
+ gpu_transform: torch.nn.Module,
+ infinite: bool,
+ shuffle: bool,
+ partial_batches: bool,
+ sample_shuffle=10_000,
+ tar_shuffle=100,
+ channels_last=False,
+ ):
+ # Need to set this for split_by_node to work.
+ os.environ["RANK"] = str(tops.rank())
+ os.environ["WORLD_SIZE"] = str(tops.world_size())
+ if infinite:
+ pipeline = [wds.ResampledShards(str(path))]
+ else:
+ pipeline = [wds.SimpleShardList(str(path))]
+ if shuffle:
+ pipeline.append(wds.shuffle(tar_shuffle))
+ pipeline.extend([
+ wds.split_by_node,
+ wds.split_by_worker,
+ ])
+ if shuffle:
+ pipeline.append(wds.shuffle(sample_shuffle))
+
+ decoder = [
+ wds.handle_extension("image.png", png_decoder),
+ wds.handle_extension("keypoints.npy", kp_decoder),
+ ]
+
+ rename_keys = [
+ ["img", "image.png"],
+ ["keypoints", "keypoints.npy"],
+ ["__key__", "__key__"],
+ ["mask", "mask"]
+ ]
+
+ pipeline.extend([
+ wds.tarfile_to_samples(),
+ wds.decode(*decoder),
+ ])
+ pipeline.append(wds.map(BBoxToMask()))
+ pipeline.extend([
+ wds.batched(batch_size, collation_fn=collate_fn, partial=partial_batches),
+ wds.rename_keys(*rename_keys),
+ ])
+
+ if transform is not None:
+ pipeline.append(wds.map(transform))
+ pipeline = wds.DataPipeline(*pipeline)
+ if infinite:
+ pipeline = pipeline.repeat(nepochs=1000000)
+
+ loader = wds.WebLoader(
+ pipeline, batch_size=None, shuffle=False,
+ num_workers=get_num_workers(num_workers),
+ persistent_workers=True,
+ )
+ loader = tops.DataPrefetcher(loader, gpu_transform, channels_last=channels_last, to_float=False)
+ return loader
diff --git a/project/models/deprecated_deep_privacy2/dp2/data/datasets/fdh.py b/project/models/deprecated_deep_privacy2/dp2/data/datasets/fdh.py
new file mode 100644
index 0000000..0c5293b
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/data/datasets/fdh.py
@@ -0,0 +1,142 @@
+import torch
+import tops
+import numpy as np
+import io
+import webdataset as wds
+import os
+import json
+from pathlib import Path
+from ..utils import png_decoder, mask_decoder, get_num_workers, collate_fn
+
+
+def kp_decoder(x):
+ # Keypoints are between [0, 1] for webdataset
+ keypoints = torch.from_numpy(np.load(io.BytesIO(x))).float()
+ def check_outside(x): return (x < 0).logical_or(x > 1)
+ is_outside = check_outside(keypoints[:, 0]).logical_or(
+ check_outside(keypoints[:, 1])
+ )
+ keypoints[:, 2] = (keypoints[:, 2] > 0).logical_and(is_outside.logical_not())
+ return keypoints
+
+
+def vertices_decoder(x):
+ vertices = torch.from_numpy(np.load(io.BytesIO(x)).astype(np.int32))
+ return vertices.squeeze()[None]
+
+
+class InsertNewKeypoints:
+
+ def __init__(self, keypoints_path: Path) -> None:
+ with open(keypoints_path, "r") as fp:
+ self.keypoints = json.load(fp)
+
+ def __call__(self, sample):
+ key = sample["__key__"]
+ keypoints = torch.tensor(self.keypoints[key], dtype=torch.float32)
+ def check_outside(x): return (x < 0).logical_or(x > 1)
+ is_outside = check_outside(keypoints[:, 0]).logical_or(
+ check_outside(keypoints[:, 1])
+ )
+ keypoints[:, 2] = (keypoints[:, 2] > 0).logical_and(is_outside.logical_not())
+
+ sample["keypoints.npy"] = keypoints
+ return sample
+
+
+def get_dataloader_fdh_wds(
+ path,
+ batch_size: int,
+ num_workers: int,
+ transform: torch.nn.Module,
+ gpu_transform: torch.nn.Module,
+ infinite: bool,
+ shuffle: bool,
+ partial_batches: bool,
+ load_embedding: bool,
+ sample_shuffle=10_000,
+ tar_shuffle=100,
+ read_condition=False,
+ channels_last=False,
+ load_new_keypoints=False,
+ keypoints_split=None,
+ ):
+ # Need to set this for split_by_node to work.
+ os.environ["RANK"] = str(tops.rank())
+ os.environ["WORLD_SIZE"] = str(tops.world_size())
+ if infinite:
+ pipeline = [wds.ResampledShards(str(path))]
+ else:
+ pipeline = [wds.SimpleShardList(str(path))]
+ if shuffle:
+ pipeline.append(wds.shuffle(tar_shuffle))
+ pipeline.extend([
+ wds.split_by_node,
+ wds.split_by_worker,
+ ])
+ if shuffle:
+ pipeline.append(wds.shuffle(sample_shuffle))
+
+ decoder = [
+ wds.handle_extension("image.png", png_decoder),
+ wds.handle_extension("mask.png", mask_decoder),
+ wds.handle_extension("maskrcnn_mask.png", mask_decoder),
+ wds.handle_extension("keypoints.npy", kp_decoder),
+ ]
+
+ rename_keys = [
+ ["img", "image.png"], ["mask", "mask.png"],
+ ["keypoints", "keypoints.npy"], ["maskrcnn_mask", "maskrcnn_mask.png"],
+ ["__key__", "__key__"]
+ ]
+ if load_embedding:
+ decoder.extend([
+ wds.handle_extension("vertices.npy", vertices_decoder),
+ wds.handle_extension("E_mask.png", mask_decoder)
+ ])
+ rename_keys.extend([
+ ["vertices", "vertices.npy"],
+ ["E_mask", "e_mask.png"]
+ ])
+
+ if read_condition:
+ decoder.append(
+ wds.handle_extension("condition.png", png_decoder)
+ )
+ rename_keys.append(["condition", "condition.png"])
+
+ pipeline.extend([
+ wds.tarfile_to_samples(),
+ wds.decode(*decoder),
+
+ ])
+ if load_new_keypoints:
+ assert keypoints_split in ["train", "val"]
+ keypoint_url = "https://api.loke.aws.unit.no/dlr-gui-backend-resources-content/v2/contents/links/1eb88522-8b91-49c7-b56a-ed98a9c7888cef9c0429-a385-4248-abe3-8682de26d041f268aed1-7c88-4677-baad-7623c2ee330f"
+ file_name = "fdh_keypoints_val-050133b34d.json"
+ if keypoints_split == "train":
+ keypoint_url = "https://api.loke.aws.unit.no/dlr-gui-backend-resources-content/v2/contents/links/3e828b1c-d6c0-4622-90bc-1b2cce48ccfff14ab45d-0a5c-431d-be13-7e60580765bd7938601c-e72e-41d9-8836-fffc49e76f58"
+ file_name = "fdh_keypoints_train-2cff11f69a.json"
+ # Set check_hash=True if you suspect download is incorrect.
+ filepath = tops.download_file(keypoint_url, file_name=file_name, check_hash=False)
+ pipeline.append(
+ wds.map(InsertNewKeypoints(filepath))
+ )
+ pipeline.extend([
+ wds.batched(batch_size, collation_fn=collate_fn, partial=partial_batches),
+ wds.rename_keys(*rename_keys),
+ ])
+
+ if transform is not None:
+ pipeline.append(wds.map(transform))
+ pipeline = wds.DataPipeline(*pipeline)
+ if infinite:
+ pipeline = pipeline.repeat(nepochs=1000000)
+
+ loader = wds.WebLoader(
+ pipeline, batch_size=None, shuffle=False,
+ num_workers=get_num_workers(num_workers),
+ persistent_workers=True,
+ )
+ loader = tops.DataPrefetcher(loader, gpu_transform, channels_last=channels_last, to_float=False)
+ return loader
diff --git a/project/models/deprecated_deep_privacy2/dp2/data/transforms/__init__.py b/project/models/deprecated_deep_privacy2/dp2/data/transforms/__init__.py
new file mode 100644
index 0000000..9ee4bcf
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/data/transforms/__init__.py
@@ -0,0 +1,2 @@
+from .transforms import RandomCrop, CreateCondition, CreateEmbedding, Resize, ToFloat, Normalize
+from .stylegan2_transform import StyleGANAugmentPipe
diff --git a/project/models/deprecated_deep_privacy2/dp2/data/transforms/functional.py b/project/models/deprecated_deep_privacy2/dp2/data/transforms/functional.py
new file mode 100644
index 0000000..1ee57f2
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/data/transforms/functional.py
@@ -0,0 +1,57 @@
+import torchvision.transforms.functional as F
+import torch
+import pickle
+from tops import download_file, assert_shape
+from typing import Dict
+from functools import lru_cache
+
+global symmetry_transform
+
+
+@lru_cache(maxsize=1)
+def get_symmetry_transform(symmetry_url):
+ file_name = download_file(symmetry_url)
+ with open(file_name, "rb") as fp:
+ symmetry = pickle.load(fp)
+ return torch.from_numpy(symmetry["vertex_transforms"]).long()
+
+
+hflip_handled_cases = set([
+ "keypoints", "img", "mask", "border", "semantic_mask", "vertices", "E_mask", "embed_map", "condition",
+ "embedding", "vertx2cat", "maskrcnn_mask", "__key__"])
+
+
+def hflip(container: Dict[str, torch.Tensor], flip_map=None) -> Dict[str, torch.Tensor]:
+ container["img"] = F.hflip(container["img"])
+ if "condition" in container:
+ container["condition"] = F.hflip(container["condition"])
+ if "embedding" in container:
+ container["embedding"] = F.hflip(container["embedding"])
+ assert all([key in hflip_handled_cases for key in container]), container.keys()
+ if "keypoints" in container:
+ assert flip_map is not None
+ if container["keypoints"].ndim == 3:
+ keypoints = container["keypoints"][:, flip_map, :]
+ keypoints[:, :, 0] = 1 - keypoints[:, :, 0]
+ else:
+ assert_shape(container["keypoints"], (None, 3))
+ keypoints = container["keypoints"][flip_map, :]
+ keypoints[:, 0] = 1 - keypoints[:, 0]
+ container["keypoints"] = keypoints
+ if "mask" in container:
+ container["mask"] = F.hflip(container["mask"])
+ if "border" in container:
+ container["border"] = F.hflip(container["border"])
+ if "semantic_mask" in container:
+ container["semantic_mask"] = F.hflip(container["semantic_mask"])
+ if "vertices" in container:
+ symmetry_transform = get_symmetry_transform(
+ "https://dl.fbaipublicfiles.com/densepose/meshes/symmetry/symmetry_smpl_27554.pkl")
+ container["vertices"] = F.hflip(container["vertices"])
+ symmetry_transform_ = symmetry_transform.to(container["vertices"].device)
+ container["vertices"] = symmetry_transform_[container["vertices"].long()]
+ if "E_mask" in container:
+ container["E_mask"] = F.hflip(container["E_mask"])
+ if "maskrcnn_mask" in container:
+ container["maskrcnn_mask"] = F.hflip(container["maskrcnn_mask"])
+ return container
diff --git a/project/models/deprecated_deep_privacy2/dp2/data/transforms/stylegan2_transform.py b/project/models/deprecated_deep_privacy2/dp2/data/transforms/stylegan2_transform.py
new file mode 100644
index 0000000..49a143c
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/data/transforms/stylegan2_transform.py
@@ -0,0 +1,394 @@
+import numpy as np
+import scipy.signal
+import torch
+try:
+ from sg3_torch_utils import misc
+ from sg3_torch_utils.ops import upfirdn2d
+ from sg3_torch_utils.ops import grid_sample_gradfix
+ from sg3_torch_utils.ops import conv2d_gradfix
+except:
+ pass
+#----------------------------------------------------------------------------
+# Coefficients of various wavelet decomposition low-pass filters.
+
+wavelets = {
+ 'haar': [0.7071067811865476, 0.7071067811865476],
+ 'db1': [0.7071067811865476, 0.7071067811865476],
+ 'db2': [-0.12940952255092145, 0.22414386804185735, 0.836516303737469, 0.48296291314469025],
+ 'db3': [0.035226291882100656, -0.08544127388224149, -0.13501102001039084, 0.4598775021193313, 0.8068915093133388, 0.3326705529509569],
+ 'db4': [-0.010597401784997278, 0.032883011666982945, 0.030841381835986965, -0.18703481171888114, -0.02798376941698385, 0.6308807679295904, 0.7148465705525415, 0.23037781330885523],
+ 'db5': [0.003335725285001549, -0.012580751999015526, -0.006241490213011705, 0.07757149384006515, -0.03224486958502952, -0.24229488706619015, 0.13842814590110342, 0.7243085284385744, 0.6038292697974729, 0.160102397974125],
+ 'db6': [-0.00107730108499558, 0.004777257511010651, 0.0005538422009938016, -0.031582039318031156, 0.02752286553001629, 0.09750160558707936, -0.12976686756709563, -0.22626469396516913, 0.3152503517092432, 0.7511339080215775, 0.4946238903983854, 0.11154074335008017],
+ 'db7': [0.0003537138000010399, -0.0018016407039998328, 0.00042957797300470274, 0.012550998556013784, -0.01657454163101562, -0.03802993693503463, 0.0806126091510659, 0.07130921926705004, -0.22403618499416572, -0.14390600392910627, 0.4697822874053586, 0.7291320908465551, 0.39653931948230575, 0.07785205408506236],
+ 'db8': [-0.00011747678400228192, 0.0006754494059985568, -0.0003917403729959771, -0.00487035299301066, 0.008746094047015655, 0.013981027917015516, -0.04408825393106472, -0.01736930100202211, 0.128747426620186, 0.00047248457399797254, -0.2840155429624281, -0.015829105256023893, 0.5853546836548691, 0.6756307362980128, 0.3128715909144659, 0.05441584224308161],
+ 'sym2': [-0.12940952255092145, 0.22414386804185735, 0.836516303737469, 0.48296291314469025],
+ 'sym3': [0.035226291882100656, -0.08544127388224149, -0.13501102001039084, 0.4598775021193313, 0.8068915093133388, 0.3326705529509569],
+ 'sym4': [-0.07576571478927333, -0.02963552764599851, 0.49761866763201545, 0.8037387518059161, 0.29785779560527736, -0.09921954357684722, -0.012603967262037833, 0.0322231006040427],
+ 'sym5': [0.027333068345077982, 0.029519490925774643, -0.039134249302383094, 0.1993975339773936, 0.7234076904024206, 0.6339789634582119, 0.01660210576452232, -0.17532808990845047, -0.021101834024758855, 0.019538882735286728],
+ 'sym6': [0.015404109327027373, 0.0034907120842174702, -0.11799011114819057, -0.048311742585633, 0.4910559419267466, 0.787641141030194, 0.3379294217276218, -0.07263752278646252, -0.021060292512300564, 0.04472490177066578, 0.0017677118642428036, -0.007800708325034148],
+ 'sym7': [0.002681814568257878, -0.0010473848886829163, -0.01263630340325193, 0.03051551316596357, 0.0678926935013727, -0.049552834937127255, 0.017441255086855827, 0.5361019170917628, 0.767764317003164, 0.2886296317515146, -0.14004724044296152, -0.10780823770381774, 0.004010244871533663, 0.010268176708511255],
+ 'sym8': [-0.0033824159510061256, -0.0005421323317911481, 0.03169508781149298, 0.007607487324917605, -0.1432942383508097, -0.061273359067658524, 0.4813596512583722, 0.7771857517005235, 0.3644418948353314, -0.05194583810770904, -0.027219029917056003, 0.049137179673607506, 0.003808752013890615, -0.01495225833704823, -0.0003029205147213668, 0.0018899503327594609],
+}
+
+#----------------------------------------------------------------------------
+# Helpers for constructing transformation matrices.
+
+
+def matrix(*rows, device=None):
+ assert all(len(row) == len(rows[0]) for row in rows)
+ elems = [x for row in rows for x in row]
+ ref = [x for x in elems if isinstance(x, torch.Tensor)]
+ if len(ref) == 0:
+ return misc.constant(np.asarray(rows), device=device)
+ assert device is None or device == ref[0].device
+ elems = [x if isinstance(x, torch.Tensor) else misc.constant(x, shape=ref[0].shape, device=ref[0].device) for x in elems]
+ return torch.stack(elems, dim=-1).reshape(ref[0].shape + (len(rows), -1))
+
+
+def translate2d(tx, ty, **kwargs):
+ return matrix(
+ [1, 0, tx],
+ [0, 1, ty],
+ [0, 0, 1],
+ **kwargs)
+
+
+def translate3d(tx, ty, tz, **kwargs):
+ return matrix(
+ [1, 0, 0, tx],
+ [0, 1, 0, ty],
+ [0, 0, 1, tz],
+ [0, 0, 0, 1],
+ **kwargs)
+
+
+def scale2d(sx, sy, **kwargs):
+ return matrix(
+ [sx, 0, 0],
+ [0, sy, 0],
+ [0, 0, 1],
+ **kwargs)
+
+
+def scale3d(sx, sy, sz, **kwargs):
+ return matrix(
+ [sx, 0, 0, 0],
+ [0, sy, 0, 0],
+ [0, 0, sz, 0],
+ [0, 0, 0, 1],
+ **kwargs)
+
+
+def rotate2d(theta, **kwargs):
+ return matrix(
+ [torch.cos(theta), torch.sin(-theta), 0],
+ [torch.sin(theta), torch.cos(theta), 0],
+ [0, 0, 1],
+ **kwargs)
+
+
+def rotate3d(v, theta, **kwargs):
+ vx = v[..., 0]; vy = v[..., 1]; vz = v[..., 2]
+ s = torch.sin(theta); c = torch.cos(theta); cc = 1 - c
+ return matrix(
+ [vx*vx*cc+c, vx*vy*cc-vz*s, vx*vz*cc+vy*s, 0],
+ [vy*vx*cc+vz*s, vy*vy*cc+c, vy*vz*cc-vx*s, 0],
+ [vz*vx*cc-vy*s, vz*vy*cc+vx*s, vz*vz*cc+c, 0],
+ [0, 0, 0, 1],
+ **kwargs)
+
+
+def translate2d_inv(tx, ty, **kwargs):
+ return translate2d(-tx, -ty, **kwargs)
+
+
+def scale2d_inv(sx, sy, **kwargs):
+ return scale2d(1 / sx, 1 / sy, **kwargs)
+
+
+def rotate2d_inv(theta, **kwargs):
+ return rotate2d(-theta, **kwargs)
+
+
+class StyleGANAugmentPipe(torch.nn.Module):
+ def __init__(self,
+ rotate90=0, xint=0, xint_max=0.125,
+ scale=0, rotate=0, aniso=0, xfrac=0, scale_std=0.2, rotate_max=1, aniso_std=0.2, xfrac_std=0.125,
+ brightness=0, contrast=0, lumaflip=0, hue=0, saturation=0, brightness_std=0.2, contrast_std=0.5,
+ hue_max=1, saturation_std=1,
+ imgfilter=0, imgfilter_bands=[1,1,1,1], imgfilter_std=1,
+ ):
+ super().__init__()
+ self.register_buffer('p', torch.ones([])) # Overall multiplier for augmentation probability.
+
+ # Pixel blitting.
+ self.rotate90 = float(rotate90) # Probability multiplier for 90 degree rotations.
+ self.xint = float(xint) # Probability multiplier for integer translation.
+ self.xint_max = float(xint_max) # Range of integer translation, relative to image dimensions.
+
+ # General geometric transformations.
+ self.scale = float(scale) # Probability multiplier for isotropic scaling.
+ self.rotate = float(rotate) # Probability multiplier for arbitrary rotation.
+ self.aniso = float(aniso) # Probability multiplier for anisotropic scaling.
+ self.xfrac = float(xfrac) # Probability multiplier for fractional translation.
+ self.scale_std = float(scale_std) # Log2 standard deviation of isotropic scaling.
+ self.rotate_max = float(rotate_max) # Range of arbitrary rotation, 1 = full circle.
+ self.aniso_std = float(aniso_std) # Log2 standard deviation of anisotropic scaling.
+ self.xfrac_std = float(xfrac_std) # Standard deviation of frational translation, relative to image dimensions.
+
+ # Color transformations.
+ self.brightness = float(brightness) # Probability multiplier for brightness.
+ self.contrast = float(contrast) # Probability multiplier for contrast.
+ self.lumaflip = float(lumaflip) # Probability multiplier for luma flip.
+ self.hue = float(hue) # Probability multiplier for hue rotation.
+ self.saturation = float(saturation) # Probability multiplier for saturation.
+ self.brightness_std = float(brightness_std) # Standard deviation of brightness.
+ self.contrast_std = float(contrast_std) # Log2 standard deviation of contrast.
+ self.hue_max = float(hue_max) # Range of hue rotation, 1 = full circle.
+ self.saturation_std = float(saturation_std) # Log2 standard deviation of saturation.
+
+ # Image-space filtering.
+ self.imgfilter = float(imgfilter) # Probability multiplier for image-space filtering.
+ self.imgfilter_bands = list(imgfilter_bands) # Probability multipliers for individual frequency bands.
+ self.imgfilter_std = float(imgfilter_std) # Log2 standard deviation of image-space filter amplification.
+
+ # Setup orthogonal lowpass filter for geometric augmentations.
+ self.register_buffer('Hz_geom', upfirdn2d.setup_filter(wavelets['sym6']))
+
+ # Construct filter bank for image-space filtering.
+ Hz_lo = np.asarray(wavelets['sym2']) # H(z)
+ Hz_hi = Hz_lo * ((-1) ** np.arange(Hz_lo.size)) # H(-z)
+ Hz_lo2 = np.convolve(Hz_lo, Hz_lo[::-1]) / 2 # H(z) * H(z^-1) / 2
+ Hz_hi2 = np.convolve(Hz_hi, Hz_hi[::-1]) / 2 # H(-z) * H(-z^-1) / 2
+ Hz_fbank = np.eye(4, 1) # Bandpass(H(z), b_i)
+ for i in range(1, Hz_fbank.shape[0]):
+ Hz_fbank = np.dstack([Hz_fbank, np.zeros_like(Hz_fbank)]).reshape(Hz_fbank.shape[0], -1)[:, :-1]
+ Hz_fbank = scipy.signal.convolve(Hz_fbank, [Hz_lo2])
+ Hz_fbank[i, (Hz_fbank.shape[1] - Hz_hi2.size) // 2 : (Hz_fbank.shape[1] + Hz_hi2.size) // 2] += Hz_hi2
+ self.register_buffer('Hz_fbank', torch.as_tensor(Hz_fbank, dtype=torch.float32))
+
+ def forward(self, batch, debug_percentile=None):
+ images = batch["img"]
+ batch["vertices"] = batch["vertices"].float()
+ assert isinstance(images, torch.Tensor) and images.ndim == 4
+ batch_size, num_channels, height, width = images.shape
+ device = images.device
+ self.Hz_fbank = self.Hz_fbank.to(device)
+ self.Hz_geom = self.Hz_geom.to(device)
+ if debug_percentile is not None:
+ debug_percentile = torch.as_tensor(debug_percentile, dtype=torch.float32, device=device)
+
+ # -------------------------------------
+ # Select parameters for pixel blitting.
+ # -------------------------------------
+
+ # Initialize inverse homogeneous 2D transform: G_inv @ pixel_out ==> pixel_in
+ I_3 = torch.eye(3, device=device)
+ G_inv = I_3
+
+ # Apply integer translation with probability (xint * strength).
+ if self.xint > 0:
+ t = (torch.rand([batch_size, 2], device=device) * 2 - 1) * self.xint_max
+ t = torch.where(torch.rand([batch_size, 1], device=device) < self.xint * self.p, t, torch.zeros_like(t))
+ if debug_percentile is not None:
+ t = torch.full_like(t, (debug_percentile * 2 - 1) * self.xint_max)
+ G_inv = G_inv @ translate2d_inv(torch.round(t[:,0] * width), torch.round(t[:,1] * height))
+
+ # --------------------------------------------------------
+ # Select parameters for general geometric transformations.
+ # --------------------------------------------------------
+
+ # Apply isotropic scaling with probability (scale * strength).
+ if self.scale > 0:
+ s = torch.exp2(torch.randn([batch_size], device=device) * self.scale_std)
+ s = torch.where(torch.rand([batch_size], device=device) < self.scale * self.p, s, torch.ones_like(s))
+ if debug_percentile is not None:
+ s = torch.full_like(s, torch.exp2(torch.erfinv(debug_percentile * 2 - 1) * self.scale_std))
+ G_inv = G_inv @ scale2d_inv(s, s)
+
+ # Apply pre-rotation with probability p_rot.
+ p_rot = 1 - torch.sqrt((1 - self.rotate * self.p).clamp(0, 1)) # P(pre OR post) = p
+ if self.rotate > 0:
+ theta = (torch.rand([batch_size], device=device) * 2 - 1) * np.pi * self.rotate_max
+ theta = torch.where(torch.rand([batch_size], device=device) < p_rot, theta, torch.zeros_like(theta))
+ if debug_percentile is not None:
+ theta = torch.full_like(theta, (debug_percentile * 2 - 1) * np.pi * self.rotate_max)
+ G_inv = G_inv @ rotate2d_inv(-theta) # Before anisotropic scaling.
+
+ # Apply anisotropic scaling with probability (aniso * strength).
+ if self.aniso > 0:
+ s = torch.exp2(torch.randn([batch_size], device=device) * self.aniso_std)
+ s = torch.where(torch.rand([batch_size], device=device) < self.aniso * self.p, s, torch.ones_like(s))
+ if debug_percentile is not None:
+ s = torch.full_like(s, torch.exp2(torch.erfinv(debug_percentile * 2 - 1) * self.aniso_std))
+ G_inv = G_inv @ scale2d_inv(s, 1 / s)
+
+ # Apply post-rotation with probability p_rot.
+ if self.rotate > 0:
+ theta = (torch.rand([batch_size], device=device) * 2 - 1) * np.pi * self.rotate_max
+ theta = torch.where(torch.rand([batch_size], device=device) < p_rot, theta, torch.zeros_like(theta))
+ if debug_percentile is not None:
+ theta = torch.zeros_like(theta)
+ G_inv = G_inv @ rotate2d_inv(-theta) # After anisotropic scaling.
+
+ # Apply fractional translation with probability (xfrac * strength).
+ if self.xfrac > 0:
+ t = torch.randn([batch_size, 2], device=device) * self.xfrac_std
+ t = torch.where(torch.rand([batch_size, 1], device=device) < self.xfrac * self.p, t, torch.zeros_like(t))
+ if debug_percentile is not None:
+ t = torch.full_like(t, torch.erfinv(debug_percentile * 2 - 1) * self.xfrac_std)
+ G_inv = G_inv @ translate2d_inv(t[:,0] * width, t[:,1] * height)
+
+ # ----------------------------------
+ # Execute geometric transformations.
+ # ----------------------------------
+
+ # Execute if the transform is not identity.
+ if G_inv is not I_3:
+ # Calculate padding.
+ cx = (width - 1) / 2
+ cy = (height - 1) / 2
+ cp = matrix([-cx, -cy, 1], [cx, -cy, 1], [cx, cy, 1], [-cx, cy, 1], device=device) # [idx, xyz]
+ cp = G_inv @ cp.t() # [batch, xyz, idx]
+ Hz_pad = self.Hz_geom.shape[0] // 4
+ margin = cp[:, :2, :].permute(1, 0, 2).flatten(1) # [xy, batch * idx]
+ margin = torch.cat([-margin, margin]).max(dim=1).values # [x0, y0, x1, y1]
+ margin = margin + misc.constant([Hz_pad * 2 - cx, Hz_pad * 2 - cy] * 2, device=device)
+ margin = margin.max(misc.constant([0, 0] * 2, device=device))
+ margin = margin.min(misc.constant([width-1, height-1] * 2, device=device))
+ mx0, my0, mx1, my1 = margin.ceil().to(torch.int32)
+
+ # Pad image and adjust origin.
+ images = torch.nn.functional.pad(input=images, pad=[mx0,mx1,my0,my1], mode='reflect')
+ batch["mask"] = torch.nn.functional.pad(input=batch["mask"], pad=[mx0,mx1,my0,my1], mode='constant', value=1.0)
+ batch["E_mask"] = torch.nn.functional.pad(input=batch["E_mask"], pad=[mx0,mx1,my0,my1], mode='constant', value=0.0)
+ batch["vertices"] = torch.nn.functional.pad(input=batch["vertices"], pad=[mx0,mx1,my0,my1], mode='constant', value=0.0)
+ G_inv = translate2d((mx0 - mx1) / 2, (my0 - my1) / 2) @ G_inv
+
+ # Upsample.
+ images = upfirdn2d.upsample2d(x=images, f=self.Hz_geom, up=2)
+ batch["mask"] = torch.nn.functional.interpolate(batch["mask"], scale_factor=2, mode="nearest")
+ batch["E_mask"] = torch.nn.functional.interpolate(batch["E_mask"], scale_factor=2, mode="nearest")
+ batch["vertices"] = torch.nn.functional.interpolate(batch["vertices"], scale_factor=2, mode="nearest")
+ G_inv = scale2d(2, 2, device=device) @ G_inv @ scale2d_inv(2, 2, device=device)
+ G_inv = translate2d(-0.5, -0.5, device=device) @ G_inv @ translate2d_inv(-0.5, -0.5, device=device)
+
+ # Execute transformation.
+ shape = [batch_size, num_channels, (height + Hz_pad * 2) * 2, (width + Hz_pad * 2) * 2]
+ G_inv = scale2d(2 / images.shape[3], 2 / images.shape[2], device=device) @ G_inv @ scale2d_inv(2 / shape[3], 2 / shape[2], device=device)
+ grid = torch.nn.functional.affine_grid(theta=G_inv[:,:2,:], size=shape, align_corners=False)
+ images = grid_sample_gradfix.grid_sample(images, grid)
+
+ batch["mask"] = torch.nn.functional.grid_sample(
+ input=batch["mask"], grid=grid, mode='nearest', padding_mode="border", align_corners=False)
+ batch["E_mask"] = torch.nn.functional.grid_sample(
+ input=batch["E_mask"], grid=grid, mode='nearest', padding_mode="border", align_corners=False)
+ batch["vertices"] = torch.nn.functional.grid_sample(
+ input=batch["vertices"], grid=grid, mode='nearest', padding_mode="border", align_corners=False)
+
+
+ # Downsample and crop.
+ images = upfirdn2d.downsample2d(x=images, f=self.Hz_geom, down=2, padding=-Hz_pad*2, flip_filter=True)
+ batch["mask"] = torch.nn.functional.interpolate(batch["mask"][:, :, Hz_pad*2:-Hz_pad*2, Hz_pad*2:-Hz_pad*2], scale_factor=.5, mode="nearest", recompute_scale_factor=False)
+ batch["E_mask"] = torch.nn.functional.interpolate(batch["E_mask"][:, :, Hz_pad*2:-Hz_pad*2, Hz_pad*2:-Hz_pad*2], scale_factor=.5, mode="nearest", recompute_scale_factor=False)
+ batch["vertices"] = torch.nn.functional.interpolate(batch["vertices"][:, :, Hz_pad*2:-Hz_pad*2, Hz_pad*2:-Hz_pad*2], scale_factor=.5, mode="nearest", recompute_scale_factor=False)
+ # --------------------------------------------
+ # Select parameters for color transformations.
+ # --------------------------------------------
+
+ # Initialize homogeneous 3D transformation matrix: C @ color_in ==> color_out
+ I_4 = torch.eye(4, device=device)
+ C = I_4
+
+ # Apply brightness with probability (brightness * strength).
+ if self.brightness > 0:
+ b = torch.randn([batch_size], device=device) * self.brightness_std
+ b = torch.where(torch.rand([batch_size], device=device) < self.brightness * self.p, b, torch.zeros_like(b))
+ if debug_percentile is not None:
+ b = torch.full_like(b, torch.erfinv(debug_percentile * 2 - 1) * self.brightness_std)
+ C = translate3d(b, b, b) @ C
+
+ # Apply contrast with probability (contrast * strength).
+ if self.contrast > 0:
+ c = torch.exp2(torch.randn([batch_size], device=device) * self.contrast_std)
+ c = torch.where(torch.rand([batch_size], device=device) < self.contrast * self.p, c, torch.ones_like(c))
+ if debug_percentile is not None:
+ c = torch.full_like(c, torch.exp2(torch.erfinv(debug_percentile * 2 - 1) * self.contrast_std))
+ C = scale3d(c, c, c) @ C
+
+ # Apply luma flip with probability (lumaflip * strength).
+ v = misc.constant(np.asarray([1, 1, 1, 0]) / np.sqrt(3), device=device) # Luma axis.
+
+ # Apply hue rotation with probability (hue * strength).
+ if self.hue > 0 and num_channels > 1:
+ theta = (torch.rand([batch_size], device=device) * 2 - 1) * np.pi * self.hue_max
+ theta = torch.where(torch.rand([batch_size], device=device) < self.hue * self.p, theta, torch.zeros_like(theta))
+ if debug_percentile is not None:
+ theta = torch.full_like(theta, (debug_percentile * 2 - 1) * np.pi * self.hue_max)
+ C = rotate3d(v, theta) @ C # Rotate around v.
+
+ # Apply saturation with probability (saturation * strength).
+ if self.saturation > 0 and num_channels > 1:
+ s = torch.exp2(torch.randn([batch_size, 1, 1], device=device) * self.saturation_std)
+ s = torch.where(torch.rand([batch_size, 1, 1], device=device) < self.saturation * self.p, s, torch.ones_like(s))
+ if debug_percentile is not None:
+ s = torch.full_like(s, torch.exp2(torch.erfinv(debug_percentile * 2 - 1) * self.saturation_std))
+ C = (v.ger(v) + (I_4 - v.ger(v)) * s) @ C
+
+ # ------------------------------
+ # Execute color transformations.
+ # ------------------------------
+
+ # Execute if the transform is not identity.
+ if C is not I_4:
+ images = images.reshape([batch_size, num_channels, height * width])
+ if num_channels == 3:
+ images = C[:, :3, :3] @ images + C[:, :3, 3:]
+ elif num_channels == 1:
+ C = C[:, :3, :].mean(dim=1, keepdims=True)
+ images = images * C[:, :, :3].sum(dim=2, keepdims=True) + C[:, :, 3:]
+ else:
+ raise ValueError('Image must be RGB (3 channels) or L (1 channel)')
+ images = images.reshape([batch_size, num_channels, height, width])
+
+ # ----------------------
+ # Image-space filtering.
+ # ----------------------
+
+ if self.imgfilter > 0:
+ num_bands = self.Hz_fbank.shape[0]
+ assert len(self.imgfilter_bands) == num_bands
+ expected_power = misc.constant(np.array([10, 1, 1, 1]) / 13, device=device) # Expected power spectrum (1/f).
+
+ # Apply amplification for each band with probability (imgfilter * strength * band_strength).
+ g = torch.ones([batch_size, num_bands], device=device) # Global gain vector (identity).
+ for i, band_strength in enumerate(self.imgfilter_bands):
+ t_i = torch.exp2(torch.randn([batch_size], device=device) * self.imgfilter_std)
+ t_i = torch.where(torch.rand([batch_size], device=device) < self.imgfilter * self.p * band_strength, t_i, torch.ones_like(t_i))
+ if debug_percentile is not None:
+ t_i = torch.full_like(t_i, torch.exp2(torch.erfinv(debug_percentile * 2 - 1) * self.imgfilter_std)) if band_strength > 0 else torch.ones_like(t_i)
+ t = torch.ones([batch_size, num_bands], device=device) # Temporary gain vector.
+ t[:, i] = t_i # Replace i'th element.
+ t = t / (expected_power * t.square()).sum(dim=-1, keepdims=True).sqrt() # Normalize power.
+ g = g * t # Accumulate into global gain.
+
+ # Construct combined amplification filter.
+ Hz_prime = g @ self.Hz_fbank # [batch, tap]
+ Hz_prime = Hz_prime.unsqueeze(1).repeat([1, num_channels, 1]) # [batch, channels, tap]
+ Hz_prime = Hz_prime.reshape([batch_size * num_channels, 1, -1]) # [batch * channels, 1, tap]
+
+ # Apply filter.
+ p = self.Hz_fbank.shape[1] // 2
+ images = images.reshape([1, batch_size * num_channels, height, width])
+ images = torch.nn.functional.pad(input=images, pad=[p,p,p,p], mode='reflect')
+ images = conv2d_gradfix.conv2d(input=images, weight=Hz_prime.unsqueeze(2), groups=batch_size*num_channels)
+ images = conv2d_gradfix.conv2d(input=images, weight=Hz_prime.unsqueeze(3), groups=batch_size*num_channels)
+ images = images.reshape([batch_size, num_channels, height, width])
+
+ # ------------------------
+ # Image-space corruptions.
+ # ------------------------
+ batch["img"] = images
+ batch["vertices"] = batch["vertices"].long()
+ batch["border"] = 1 - batch["E_mask"] - batch["mask"]
+ return batch
diff --git a/project/models/deprecated_deep_privacy2/dp2/data/transforms/transforms.py b/project/models/deprecated_deep_privacy2/dp2/data/transforms/transforms.py
new file mode 100644
index 0000000..444f7ce
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/data/transforms/transforms.py
@@ -0,0 +1,278 @@
+from pathlib import Path
+from typing import Dict, List
+import torchvision
+import torch
+import tops
+import torchvision.transforms.functional as F
+from .functional import hflip
+import numpy as np
+from dp2.utils.vis_utils import get_coco_keypoints
+from PIL import Image, ImageDraw
+from typing import Tuple
+
+
+class RandomHorizontalFlip(torch.nn.Module):
+
+ def __init__(self, p: float, flip_map=None, **kwargs):
+ super().__init__()
+ self.flip_ratio = p
+ self.flip_map = flip_map
+ if self.flip_ratio is None:
+ self.flip_ratio = 0.5
+ assert 0 <= self.flip_ratio <= 1
+
+ def forward(self, container: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
+ if torch.rand(1) > self.flip_ratio:
+ return container
+ return hflip(container, self.flip_map)
+
+
+class CenterCrop(torch.nn.Module):
+ """
+ Performs the transform on the image.
+ NOTE: Does not transform the mask to improve runtime.
+ """
+
+ def __init__(self, size: List[int]):
+ super().__init__()
+ self.size = tuple(size)
+
+ def forward(self, container: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
+ min_size = min(container["img"].shape[1], container["img"].shape[2])
+ if min_size < self.size[0]:
+ container["img"] = F.center_crop(container["img"], min_size)
+ container["img"] = F.resize(container["img"], self.size)
+ return container
+ container["img"] = F.center_crop(container["img"], self.size)
+ return container
+
+
+class Resize(torch.nn.Module):
+ """
+ Performs the transform on the image.
+ NOTE: Does not transform the mask to improve runtime.
+ """
+
+ def __init__(self, size, interpolation=F.InterpolationMode.BILINEAR):
+ super().__init__()
+ self.size = tuple(size)
+ self.interpolation = interpolation
+
+ def forward(self, container: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
+ container["img"] = F.resize(container["img"], self.size, self.interpolation, antialias=True)
+ if "semantic_mask" in container:
+ container["semantic_mask"] = F.resize(
+ container["semantic_mask"], self.size, F.InterpolationMode.NEAREST)
+ if "embedding" in container:
+ container["embedding"] = F.resize(
+ container["embedding"], self.size, self.interpolation)
+ if "mask" in container:
+ container["mask"] = F.resize(
+ container["mask"], self.size, F.InterpolationMode.NEAREST)
+ if "E_mask" in container:
+ container["E_mask"] = F.resize(
+ container["E_mask"], self.size, F.InterpolationMode.NEAREST)
+ if "maskrcnn_mask" in container:
+ container["maskrcnn_mask"] = F.resize(
+ container["maskrcnn_mask"], self.size, F.InterpolationMode.NEAREST)
+ if "vertices" in container:
+ container["vertices"] = F.resize(
+ container["vertices"], self.size, F.InterpolationMode.NEAREST)
+ return container
+
+ def __repr__(self):
+ repr = super().__repr__()
+ vars_ = dict(size=self.size, interpolation=self.interpolation)
+ return repr + " " + " ".join([f"{k}: {v}" for k, v in vars_.items()])
+
+
+class Normalize(torch.nn.Module):
+ """
+ Performs the transform on the image.
+ NOTE: Does not transform the mask to improve runtime.
+ """
+
+ def __init__(self, mean, std, inplace, keys=["img"]):
+ super().__init__()
+ self.mean = mean
+ self.std = std
+ self.inplace = inplace
+ self.keys = keys
+
+ def forward(self, container: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
+ for key in self.keys:
+ container[key] = F.normalize(container[key], self.mean, self.std, self.inplace)
+ return container
+
+ def __repr__(self):
+ repr = super().__repr__()
+ vars_ = dict(mean=self.mean, std=self.std, inplace=self.inplace)
+ return repr + " " + " ".join([f"{k}: {v}" for k, v in vars_.items()])
+
+
+class ToFloat(torch.nn.Module):
+
+ def __init__(self, keys=["img"], norm=True) -> None:
+ super().__init__()
+ self.keys = keys
+ self.gain = 255 if norm else 1
+
+ def forward(self, container: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
+ for key in self.keys:
+ container[key] = container[key].float() / self.gain
+ return container
+
+
+class RandomCrop(torchvision.transforms.RandomCrop):
+ """
+ Performs the transform on the image.
+ NOTE: Does not transform the mask to improve runtime.
+ """
+
+ def forward(self, container: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
+ container["img"] = super().forward(container["img"])
+ return container
+
+
+class CreateCondition(torch.nn.Module):
+
+ def forward(self, container: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
+ if container["img"].dtype == torch.uint8:
+ container["condition"] = container["img"] * container["mask"].byte() + (1-container["mask"].byte()) * 127
+ return container
+ container["condition"] = container["img"] * container["mask"]
+ return container
+
+
+class CreateEmbedding(torch.nn.Module):
+
+ def __init__(self, embed_path: Path, cuda=True) -> None:
+ super().__init__()
+ self.embed_map = torch.load(embed_path, map_location=torch.device("cpu"))
+ if cuda:
+ self.embed_map = tops.to_cuda(self.embed_map)
+
+ def forward(self, container: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
+ vertices = container["vertices"]
+ if vertices.ndim == 3:
+ embedding = self.embed_map[vertices.long()].squeeze(dim=0)
+ embedding = embedding.permute(2, 0, 1) * container["E_mask"]
+ pass
+ else:
+ assert vertices.ndim == 4
+ embedding = self.embed_map[vertices.long()].squeeze(dim=1)
+ embedding = embedding.permute(0, 3, 1, 2) * container["E_mask"]
+ container["embedding"] = embedding
+ container["embed_map"] = self.embed_map.clone()
+ return container
+
+
+class InsertJointMap(torch.nn.Module):
+
+ def __init__(self, imsize: Tuple) -> None:
+ super().__init__()
+ self.imsize = imsize
+ knames = get_coco_keypoints()[0]
+ knames = knames + ["neck", "mid_hip"]
+ connectivity = {
+ "nose": ["left_eye", "right_eye", "neck"],
+ "left_eye": ["right_eye", "left_ear"],
+ "right_eye": ["right_ear"],
+ "left_shoulder": ["right_shoulder", "left_elbow", "left_hip"],
+ "right_shoulder": ["right_elbow", "right_hip"],
+ "left_elbow": ["left_wrist"],
+ "right_elbow": ["right_wrist"],
+ "left_hip": ["right_hip", "left_knee"],
+ "right_hip": ["right_knee"],
+ "left_knee": ["left_ankle"],
+ "right_knee": ["right_ankle"],
+ "neck": ["mid_hip", "nose"],
+ }
+ category = {
+ ("nose", "left_eye"): 0, # head
+ ("nose", "right_eye"): 0, # head
+ ("nose", "neck"): 0, # head
+ ("left_eye", "right_eye"): 0, # head
+ ("left_eye", "left_ear"): 0, # head
+ ("right_eye", "right_ear"): 0, # head
+ ("left_shoulder", "left_elbow"): 1, # left arm
+ ("left_elbow", "left_wrist"): 1, # left arm
+ ("right_shoulder", "right_elbow"): 2, # right arm
+ ("right_elbow", "right_wrist"): 2, # right arm
+ ("left_shoulder", "right_shoulder"): 3, # body
+ ("left_shoulder", "left_hip"): 3, # body
+ ("right_shoulder", "right_hip"): 3, # body
+ ("left_hip", "right_hip"): 3, # body
+ ("left_hip", "left_knee"): 4, # left leg
+ ("left_knee", "left_ankle"): 4, # left leg
+ ("right_hip", "right_knee"): 5, # right leg
+ ("right_knee", "right_ankle"): 5, # right leg
+ ("neck", "mid_hip"): 3, # body
+ ("neck", "nose"): 0, # head
+ }
+ self.indices2category = {
+ tuple([knames.index(n) for n in k]): v for k, v in category.items()
+ }
+ self.connectivity_indices = {
+ knames.index(k): [knames.index(v_) for v_ in v]
+ for k, v in connectivity.items()
+ }
+ self.l_shoulder = knames.index("left_shoulder")
+ self.r_shoulder = knames.index("right_shoulder")
+ self.l_hip = knames.index("left_hip")
+ self.r_hip = knames.index("right_hip")
+ self.l_eye = knames.index("left_eye")
+ self.r_eye = knames.index("right_eye")
+ self.nose = knames.index("nose")
+ self.neck = knames.index("neck")
+
+ def create_joint_map(self, N, H, W, keypoints):
+ joint_maps = np.zeros((N, H, W), dtype=np.uint8)
+ for bidx, keypoints in enumerate(keypoints):
+ assert keypoints.shape == (17, 3), keypoints.shape
+ keypoints = torch.cat((keypoints, torch.zeros(2, 3)))
+ visible = keypoints[:, -1] > 0
+
+ if visible[self.l_shoulder] and visible[self.r_shoulder]:
+ neck = (keypoints[self.l_shoulder]
+ + (keypoints[self.r_shoulder] - keypoints[self.l_shoulder]) / 2)
+ keypoints[-2] = neck
+ visible[-2] = 1
+ if visible[self.l_hip] and visible[self.r_hip]:
+ mhip = (keypoints[self.l_hip]
+ + (keypoints[self.r_hip] - keypoints[self.l_hip]) / 2
+ )
+ keypoints[-1] = mhip
+ visible[-1] = 1
+
+ keypoints[:, 0] *= W
+ keypoints[:, 1] *= H
+ joint_map = Image.fromarray(np.zeros((H, W), dtype=np.uint8))
+ draw = ImageDraw.Draw(joint_map)
+ for fidx in self.connectivity_indices.keys():
+ for tidx in self.connectivity_indices[fidx]:
+ if visible[fidx] == 0 or visible[tidx] == 0:
+ continue
+ c = self.indices2category[(fidx, tidx)]
+ s = tuple(keypoints[fidx, :2].round().long().numpy().tolist())
+ e = tuple(keypoints[tidx, :2].round().long().numpy().tolist())
+ draw.line((s, e), width=1, fill=c + 1)
+ if visible[self.nose] == 0 and visible[self.neck] == 1:
+ m_eye = (
+ keypoints[self.l_eye]
+ + (keypoints[self.r_eye] - keypoints[self.l_eye]) / 2
+ )
+ s = tuple(m_eye[:2].round().long().numpy().tolist())
+ e = tuple(keypoints[self.neck, :2].round().long().numpy().tolist())
+ c = self.indices2category[(self.nose, self.neck)]
+ draw.line((s, e), width=1, fill=c + 1)
+ joint_map = np.array(joint_map)
+
+ joint_maps[bidx] = np.array(joint_map)
+ return joint_maps[:, None]
+
+ def forward(self, batch):
+ batch["joint_map"] = torch.from_numpy(self.create_joint_map(
+ batch["img"].shape[0], *self.imsize, batch["keypoints"]))
+ batch["joint_map"] = batch["joint_map"].to(batch["img"].device)
+ return batch
diff --git a/project/models/deprecated_deep_privacy2/dp2/data/utils.py b/project/models/deprecated_deep_privacy2/dp2/data/utils.py
new file mode 100644
index 0000000..392fe22
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/data/utils.py
@@ -0,0 +1,122 @@
+import torch
+from PIL import Image
+import numpy as np
+import multiprocessing
+import io
+from tops import logger
+from torch.utils.data._utils.collate import default_collate
+
+try:
+ import pyspng
+
+ PYSPNG_IMPORTED = True
+except ImportError:
+ PYSPNG_IMPORTED = False
+ print("Could not load pyspng. Defaulting to pillow image backend.")
+ from PIL import Image
+
+
+def get_fdf_keypoints():
+ return get_coco_keypoints()[:7]
+
+
+def get_fdf_flipmap():
+ keypoints = get_fdf_keypoints()
+ keypoint_flip_map = {
+ "left_eye": "right_eye",
+ "left_ear": "right_ear",
+ "left_shoulder": "right_shoulder",
+ }
+ for key, value in list(keypoint_flip_map.items()):
+ keypoint_flip_map[value] = key
+ keypoint_flip_map["nose"] = "nose"
+ keypoint_flip_map_idx = []
+ for source in keypoints:
+ keypoint_flip_map_idx.append(keypoints.index(keypoint_flip_map[source]))
+ return keypoint_flip_map_idx
+
+
+def get_coco_keypoints():
+ return [
+ "nose",
+ "left_eye",
+ "right_eye", # 2
+ "left_ear",
+ "right_ear", # 4
+ "left_shoulder",
+ "right_shoulder", # 6
+ "left_elbow",
+ "right_elbow", # 8
+ "left_wrist",
+ "right_wrist", # 10
+ "left_hip",
+ "right_hip", # 12
+ "left_knee",
+ "right_knee", # 14
+ "left_ankle",
+ "right_ankle", # 16
+ ]
+
+
+def get_coco_flipmap():
+ keypoints = get_coco_keypoints()
+ keypoint_flip_map = {
+ "left_eye": "right_eye",
+ "left_ear": "right_ear",
+ "left_shoulder": "right_shoulder",
+ "left_elbow": "right_elbow",
+ "left_wrist": "right_wrist",
+ "left_hip": "right_hip",
+ "left_knee": "right_knee",
+ "left_ankle": "right_ankle",
+ }
+ for key, value in list(keypoint_flip_map.items()):
+ keypoint_flip_map[value] = key
+ keypoint_flip_map["nose"] = "nose"
+ keypoint_flip_map_idx = []
+ for source in keypoints:
+ keypoint_flip_map_idx.append(keypoints.index(keypoint_flip_map[source]))
+ return keypoint_flip_map_idx
+
+
+def mask_decoder(x):
+ mask = torch.from_numpy(np.array(Image.open(io.BytesIO(x)))).squeeze()[None]
+ mask = mask > 0 # This fixes bug causing maskf.loat().max() == 255.
+ return mask
+
+
+def png_decoder(x):
+ if PYSPNG_IMPORTED:
+ return torch.from_numpy(np.rollaxis(pyspng.load(x), 2))
+ with Image.open(io.BytesIO(x)) as im:
+ im = torch.from_numpy(np.rollaxis(np.array(im.convert("RGB")), 2))
+ return im
+
+
+def jpg_decoder(x):
+ with Image.open(io.BytesIO(x)) as im:
+ im = torch.from_numpy(np.rollaxis(np.array(im.convert("RGB")), 2))
+ return im
+
+
+def get_num_workers(num_workers: int):
+ n_cpus = multiprocessing.cpu_count()
+ if num_workers > n_cpus:
+ logger.warn(f"Setting the number of workers to match cpu count: {n_cpus}")
+ return n_cpus
+ return num_workers
+
+
+def collate_fn(batch):
+ elem = batch[0]
+ ignore_keys = set(["embed_map", "vertx2cat"])
+ batch_ = {
+ key: default_collate([d[key] for d in batch])
+ for key in elem
+ if key not in ignore_keys
+ }
+ if "embed_map" in elem:
+ batch_["embed_map"] = elem["embed_map"]
+ if "vertx2cat" in elem:
+ batch_["vertx2cat"] = elem["vertx2cat"]
+ return batch_
diff --git a/project/models/deprecated_deep_privacy2/dp2/detection/__init__.py b/project/models/deprecated_deep_privacy2/dp2/detection/__init__.py
new file mode 100644
index 0000000..613969b
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/detection/__init__.py
@@ -0,0 +1,3 @@
+from .cse_mask_face_detector import CSeMaskFaceDetector
+from .person_detector import CSEPersonDetector
+from .structures import PersonDetection, VehicleDetection, FaceDetection
diff --git a/project/models/deprecated_deep_privacy2/dp2/detection/base.py b/project/models/deprecated_deep_privacy2/dp2/detection/base.py
new file mode 100644
index 0000000..6ab8b20
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/detection/base.py
@@ -0,0 +1,42 @@
+import pickle
+import torch
+import lzma
+from pathlib import Path
+from tops import logger
+
+
+class BaseDetector:
+
+ def __init__(self, cache_directory: str) -> None:
+ if cache_directory is not None:
+ self.cache_directory = Path(cache_directory, str(self.__class__.__name__))
+ self.cache_directory.mkdir(exist_ok=True, parents=True)
+
+ def save_to_cache(self, detection, cache_path: Path, after_preprocess=True):
+ logger.log(f"Caching detection to: {cache_path}")
+ with lzma.open(cache_path, "wb") as fp:
+ torch.save(
+ [det.state_dict(after_preprocess=after_preprocess) for det in detection], fp,
+ pickle_protocol=pickle.HIGHEST_PROTOCOL)
+
+ def load_from_cache(self, cache_path: Path):
+ logger.log(f"Loading detection from cache path: {cache_path}")
+ with lzma.open(cache_path, "rb") as fp:
+ state_dict = torch.load(fp)
+ return [
+ state["cls"].from_state_dict(state_dict=state) for state in state_dict
+ ]
+
+ def forward_and_cache(self, im: torch.Tensor, cache_id: str, load_cache: bool):
+ if cache_id is None:
+ return self.forward(im)
+ cache_path = self.cache_directory.joinpath(cache_id + ".torch")
+ if cache_path.is_file() and load_cache:
+ try:
+ return self.load_from_cache(cache_path)
+ except Exception as e:
+ logger.warn(f"The cache file was corrupted: {cache_path}")
+ exit()
+ detections = self.forward(im)
+ self.save_to_cache(detections, cache_path)
+ return detections
diff --git a/project/models/deprecated_deep_privacy2/dp2/detection/box_utils.py b/project/models/deprecated_deep_privacy2/dp2/detection/box_utils.py
new file mode 100644
index 0000000..3d3e6b5
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/detection/box_utils.py
@@ -0,0 +1,104 @@
+import numpy as np
+
+
+def expand_bbox_to_ratio(bbox, imshape, target_aspect_ratio):
+ x0, y0, x1, y1 = [int(_) for _ in bbox]
+ h, w = y1 - y0, x1 - x0
+ cur_ratio = h / w
+
+ if cur_ratio == target_aspect_ratio:
+ return [x0, y0, x1, y1]
+ if cur_ratio < target_aspect_ratio:
+ target_height = int(w*target_aspect_ratio)
+ y0, y1 = expand_axis(y0, y1, target_height, imshape[0])
+ else:
+ target_width = int(h/target_aspect_ratio)
+ x0, x1 = expand_axis(x0, x1, target_width, imshape[1])
+ return x0, y0, x1, y1
+
+
+def expand_axis(start, end, target_width, limit):
+ # Can return a bbox outside of limit
+ cur_width = end - start
+ start = start - (target_width-cur_width)//2
+ end = end + (target_width-cur_width)//2
+ if end - start != target_width:
+ end += 1
+ assert end - start == target_width
+ if start < 0 and end > limit:
+ return start, end
+ if start < 0 and end < limit:
+ to_shift = min(0 - start, limit - end)
+ start += to_shift
+ end += to_shift
+ if end > limit and start > 0:
+ to_shift = min(end - limit, start)
+ end -= to_shift
+ start -= to_shift
+ assert end - start == target_width
+ return start, end
+
+
+def expand_box(bbox, imshape, mask, percentage_background: float):
+ assert isinstance(bbox[0], int)
+ assert 0 < percentage_background < 1
+ # Percentage in S
+ mask_pixels = mask.long().sum().cpu()
+ total_pixels = (bbox[2] - bbox[0]) * (bbox[3] - bbox[1])
+ percentage_mask = mask_pixels / total_pixels
+ if (1 - percentage_mask) > percentage_background:
+ return bbox
+ target_pixels = mask_pixels / (1 - percentage_background)
+ x0, y0, x1, y1 = bbox
+ H = y1 - y0
+ W = x1 - x0
+ p = np.sqrt(target_pixels/(H*W))
+ target_width = int(np.ceil(p * W))
+ target_height = int(np.ceil(p * H))
+ x0, x1 = expand_axis(x0, x1, target_width, imshape[1])
+ y0, y1 = expand_axis(y0, y1, target_height, imshape[0])
+ return [x0, y0, x1, y1]
+
+
+def expand_axises_by_percentage(bbox_XYXY, imshape, percentage):
+ x0, y0, x1, y1 = bbox_XYXY
+ H = y1 - y0
+ W = x1 - x0
+ expansion = int(((H*W)**0.5) * percentage)
+ new_width = W + expansion
+ new_height = H + expansion
+ x0, x1 = expand_axis(x0, x1, min(new_width, imshape[1]), imshape[1])
+ y0, y1 = expand_axis(y0, y1, min(new_height, imshape[0]), imshape[0])
+ return [x0, y0, x1, y1]
+
+
+def get_expanded_bbox(
+ bbox_XYXY,
+ imshape,
+ mask,
+ percentage_background: float,
+ axis_minimum_expansion: float,
+ target_aspect_ratio: float):
+ bbox_XYXY = bbox_XYXY.long().cpu().numpy().tolist()
+ # Expand each axis of the bounding box by a minimum percentage
+ bbox_XYXY = expand_axises_by_percentage(bbox_XYXY, imshape, axis_minimum_expansion)
+ # Find the minimum bbox with the aspect ratio. Can be outside of imshape
+ bbox_XYXY = expand_bbox_to_ratio(bbox_XYXY, imshape, target_aspect_ratio)
+ # Expands square box such that X% of the bbox is background
+ bbox_XYXY = expand_box(bbox_XYXY, imshape, mask, percentage_background)
+ assert isinstance(bbox_XYXY[0], (int, np.int64))
+ return bbox_XYXY
+
+
+def include_box(bbox, minimum_area, aspect_ratio_range, min_bbox_ratio_inside, imshape):
+ def area_inside_ratio(bbox, imshape):
+ area = (bbox[2] - bbox[0]) * (bbox[3] - bbox[1])
+ area_inside = (min(bbox[2], imshape[1]) - max(0, bbox[0])) * (min(imshape[0], bbox[3]) - max(0, bbox[1]))
+ return area_inside / area
+ ratio = (bbox[3] - bbox[1]) / (bbox[2] - bbox[0])
+ area = (bbox[3] - bbox[1]) * (bbox[2] - bbox[0])
+ if area_inside_ratio(bbox, imshape) < min_bbox_ratio_inside:
+ return False
+ if ratio <= aspect_ratio_range[0] or ratio >= aspect_ratio_range[1] or area < minimum_area:
+ return False
+ return True
diff --git a/project/models/deprecated_deep_privacy2/dp2/detection/box_utils_fdf.py b/project/models/deprecated_deep_privacy2/dp2/detection/box_utils_fdf.py
new file mode 100644
index 0000000..e1af1e3
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/detection/box_utils_fdf.py
@@ -0,0 +1,202 @@
+"""
+The FDF dataset expands bound boxes differently from what is used for CSE.
+"""
+
+import numpy as np
+
+
+def quadratic_bounding_box(x0, y0, width, height, imshape):
+ # We assume that we can create a image that is quadratic without
+ # minimizing any of the sides
+ assert width <= min(imshape[:2])
+ assert height <= min(imshape[:2])
+ min_side = min(height, width)
+ if height != width:
+ side_diff = abs(height - width)
+ # Want to extend the shortest side
+ if min_side == height:
+ # Vertical side
+ height += side_diff
+ if height > imshape[0]:
+ # Take full frame, and shrink width
+ y0 = 0
+ height = imshape[0]
+
+ side_diff = abs(height - width)
+ width -= side_diff
+ x0 += side_diff // 2
+ else:
+ y0 -= side_diff // 2
+ y0 = max(0, y0)
+ else:
+ # Horizontal side
+ width += side_diff
+ if width > imshape[1]:
+ # Take full frame width, and shrink height
+ x0 = 0
+ width = imshape[1]
+
+ side_diff = abs(height - width)
+ height -= side_diff
+ y0 += side_diff // 2
+ else:
+ x0 -= side_diff // 2
+ x0 = max(0, x0)
+ # Check that bbox goes outside image
+ x1 = x0 + width
+ y1 = y0 + height
+ if imshape[1] < x1:
+ diff = x1 - imshape[1]
+ x0 -= diff
+ if imshape[0] < y1:
+ diff = y1 - imshape[0]
+ y0 -= diff
+ assert x0 >= 0, "Bounding box outside image."
+ assert y0 >= 0, "Bounding box outside image."
+ assert x0 + width <= imshape[1], "Bounding box outside image."
+ assert y0 + height <= imshape[0], "Bounding box outside image."
+ return x0, y0, width, height
+
+
+def expand_bounding_box(bbox, percentage, imshape):
+ orig_bbox = bbox.copy()
+ x0, y0, x1, y1 = bbox
+ width = x1 - x0
+ height = y1 - y0
+ x0, y0, width, height = quadratic_bounding_box(
+ x0, y0, width, height, imshape)
+ expanding_factor = int(max(height, width) * percentage)
+
+ possible_max_expansion = [(imshape[0] - width) // 2,
+ (imshape[1] - height) // 2,
+ expanding_factor]
+
+ expanding_factor = min(possible_max_expansion)
+ # Expand height
+
+ if expanding_factor > 0:
+
+ y0 = y0 - expanding_factor
+ y0 = max(0, y0)
+
+ height += expanding_factor * 2
+ if height > imshape[0]:
+ y0 -= (imshape[0] - height)
+ height = imshape[0]
+
+ if height + y0 > imshape[0]:
+ y0 -= (height + y0 - imshape[0])
+
+ # Expand width
+ x0 = x0 - expanding_factor
+ x0 = max(0, x0)
+
+ width += expanding_factor * 2
+ if width > imshape[1]:
+ x0 -= (imshape[1] - width)
+ width = imshape[1]
+
+ if width + x0 > imshape[1]:
+ x0 -= (width + x0 - imshape[1])
+ y1 = y0 + height
+ x1 = x0 + width
+ assert y0 >= 0, "Y0 is minus"
+ assert height <= imshape[0], "Height is larger than image."
+ assert x0 + width <= imshape[1]
+ assert y0 + height <= imshape[0]
+ assert width == height, "HEIGHT IS NOT EQUAL WIDTH!!"
+ assert x0 >= 0, "Y0 is minus"
+ assert width <= imshape[1], "Height is larger than image."
+ # Check that original bbox is within new
+ x0_o, y0_o, x1_o, y1_o = orig_bbox
+ assert x0 <= x0_o, f"New bbox is outisde of original. O:{x0_o}, N: {x0}"
+ assert x1 >= x1_o, f"New bbox is outisde of original. O:{x1_o}, N: {x1}"
+ assert y0 <= y0_o, f"New bbox is outisde of original. O:{y0_o}, N: {y0}"
+ assert y1 >= y1_o, f"New bbox is outisde of original. O:{y1_o}, N: {y1}"
+
+ x0, y0, width, height = [int(_) for _ in [x0, y0, width, height]]
+ x1 = x0 + width
+ y1 = y0 + height
+ return np.array([x0, y0, x1, y1])
+
+
+def is_keypoint_within_bbox(x0, y0, x1, y1, keypoint):
+ keypoint = keypoint[:, :3] # only nose + eyes are relevant
+ kp_X = keypoint[0, :]
+ kp_Y = keypoint[1, :]
+ within_X = np.all(kp_X >= x0) and np.all(kp_X <= x1)
+ within_Y = np.all(kp_Y >= y0) and np.all(kp_Y <= y1)
+ return within_X and within_Y
+
+
+def expand_bbox_simple(bbox, percentage):
+ x0, y0, x1, y1 = bbox.astype(float)
+ width = x1 - x0
+ height = y1 - y0
+ x_c = int(x0) + width // 2
+ y_c = int(y0) + height // 2
+ avg_size = max(width, height)
+ new_width = avg_size * (1 + percentage)
+ x0 = x_c - new_width // 2
+ y0 = y_c - new_width // 2
+ x1 = x_c + new_width // 2
+ y1 = y_c + new_width // 2
+ return np.array([x0, y0, x1, y1]).astype(int)
+
+
+def pad_image(im, bbox, pad_value):
+ x0, y0, x1, y1 = bbox
+ if x0 < 0:
+ pad_im = np.zeros((im.shape[0], abs(x0), im.shape[2]),
+ dtype=np.uint8) + pad_value
+ im = np.concatenate((pad_im, im), axis=1)
+ x1 += abs(x0)
+ x0 = 0
+ if y0 < 0:
+ pad_im = np.zeros((abs(y0), im.shape[1], im.shape[2]),
+ dtype=np.uint8) + pad_value
+ im = np.concatenate((pad_im, im), axis=0)
+ y1 += abs(y0)
+ y0 = 0
+ if x1 >= im.shape[1]:
+ pad_im = np.zeros(
+ (im.shape[0], x1 - im.shape[1] + 1, im.shape[2]),
+ dtype=np.uint8) + pad_value
+ im = np.concatenate((im, pad_im), axis=1)
+ if y1 >= im.shape[0]:
+ pad_im = np.zeros(
+ (y1 - im.shape[0] + 1, im.shape[1], im.shape[2]),
+ dtype=np.uint8) + pad_value
+ im = np.concatenate((im, pad_im), axis=0)
+ return im[y0:y1, x0:x1]
+
+
+def clip_box(bbox, im):
+ bbox[0] = max(0, bbox[0])
+ bbox[1] = max(0, bbox[1])
+ bbox[2] = min(im.shape[1] - 1, bbox[2])
+ bbox[3] = min(im.shape[0] - 1, bbox[3])
+ return bbox
+
+
+def cut_face(im, bbox, simple_expand=False, pad_value=0, pad_im=True):
+ outside_im = (bbox < 0).any() or bbox[2] > im.shape[1] or bbox[3] > im.shape[0]
+ if simple_expand or (outside_im and pad_im):
+ return pad_image(im, bbox, pad_value)
+ bbox = clip_box(bbox, im)
+ x0, y0, x1, y1 = bbox
+ return im[y0:y1, x0:x1]
+
+
+def expand_bbox(
+ bbox_ltrb, imshape, simple_expand, default_to_simple=False,
+ expansion_factor=0.35):
+ assert bbox_ltrb.shape == (4,), f"BBox shape was: {bbox_ltrb.shape}"
+ bbox = bbox_ltrb.astype(float)
+ # FDF256 uses simple expand with ratio 0.4
+ if simple_expand:
+ return expand_bbox_simple(bbox, 0.4)
+ try:
+ return expand_bounding_box(bbox, expansion_factor, imshape)
+ except AssertionError:
+ return expand_bbox_simple(bbox, expansion_factor * 2)
diff --git a/project/models/deprecated_deep_privacy2/dp2/detection/cse_mask_face_detector.py b/project/models/deprecated_deep_privacy2/dp2/detection/cse_mask_face_detector.py
new file mode 100644
index 0000000..5eccfc4
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/detection/cse_mask_face_detector.py
@@ -0,0 +1,116 @@
+import torch
+import lzma
+import tops
+from pathlib import Path
+from dp2.detection.base import BaseDetector
+from .utils import combine_cse_maskrcnn_dets
+from face_detection import build_detector as build_face_detector
+from .models.cse import CSEDetector
+from .models.mask_rcnn import MaskRCNNDetector
+from .structures import CSEPersonDetection, VehicleDetection, FaceDetection, PersonDetection
+from tops import logger
+
+
+def box1_inside_box2(box1: torch.Tensor, box2: torch.Tensor):
+ assert len(box1.shape) == 2
+ assert len(box2.shape) == 2
+ box1_inside = torch.zeros(box1.shape[0], device=box1.device, dtype=torch.bool)
+ # This can be batched
+ for i, box in enumerate(box1):
+ is_outside_lefttop = (box[None, [0, 1]] <= box2[:, [0, 1]]).any(dim=1)
+ is_outside_rightbot = (box[None, [2, 3]] >= box2[:, [2, 3]]).any(dim=1)
+ is_outside = is_outside_lefttop.logical_or(is_outside_rightbot)
+ box1_inside[i] = is_outside.logical_not().any()
+ return box1_inside
+
+
+class CSeMaskFaceDetector(BaseDetector):
+
+ def __init__(
+ self,
+ mask_rcnn_cfg,
+ face_detector_cfg: dict,
+ cse_cfg: dict,
+ face_post_process_cfg: dict,
+ cse_post_process_cfg,
+ score_threshold: float,
+ **kwargs
+ ) -> None:
+ super().__init__(**kwargs)
+ self.mask_rcnn = MaskRCNNDetector(**mask_rcnn_cfg, score_thres=score_threshold)
+ if "confidence_threshold" not in face_detector_cfg:
+ face_detector_cfg["confidence_threshold"] = score_threshold
+ if "score_thres" not in cse_cfg:
+ cse_cfg["score_thres"] = score_threshold
+ self.cse_detector = CSEDetector(**cse_cfg)
+ self.face_detector = build_face_detector(**face_detector_cfg, clip_boxes=True)
+ self.cse_post_process_cfg = cse_post_process_cfg
+ self.face_mean = tops.to_cuda(torch.from_numpy(self.face_detector.mean).view(3, 1, 1))
+ self.mask_cse_iou_combine_threshold = self.cse_post_process_cfg.pop("iou_combine_threshold")
+ self.face_post_process_cfg = face_post_process_cfg
+
+ def __call__(self, *args, **kwargs):
+ return self.forward(*args, **kwargs)
+
+ def _detect_faces(self, im: torch.Tensor):
+ H, W = im.shape[1:]
+ im = im.float() - self.face_mean
+ im = self.face_detector.resize(im[None], 1.0)
+ boxes_XYXY = self.face_detector._batched_detect(im)[0][:, :-1] # Remove score
+ boxes_XYXY[:, [0, 2]] *= W
+ boxes_XYXY[:, [1, 3]] *= H
+ return boxes_XYXY.round().long()
+
+ def load_from_cache(self, cache_path: Path):
+ logger.log(f"Loading detection from cache path: {cache_path}",)
+ with lzma.open(cache_path, "rb") as fp:
+ state_dict = torch.load(fp, map_location="cpu")
+ kwargs = dict(
+ post_process_cfg=self.cse_post_process_cfg,
+ embed_map=self.cse_detector.embed_map,
+ **self.face_post_process_cfg
+ )
+ return [
+ state["cls"].from_state_dict(**kwargs, state_dict=state)
+ for state in state_dict
+ ]
+
+ @torch.no_grad()
+ def forward(self, im: torch.Tensor):
+ maskrcnn_dets = self.mask_rcnn(im)
+ cse_dets = self.cse_detector(im)
+ embed_map = self.cse_detector.embed_map
+ print("Calling face detector.")
+ face_boxes = self._detect_faces(im).cpu()
+ maskrcnn_person = {
+ k: v[maskrcnn_dets["is_person"]] for k, v in maskrcnn_dets.items()
+ }
+ maskrcnn_other = {
+ k: v[maskrcnn_dets["is_person"].logical_not()] for k, v in maskrcnn_dets.items()
+ }
+ maskrcnn_other = VehicleDetection(maskrcnn_other["segmentation"])
+ combined_segmentation, cse_dets, matches = combine_cse_maskrcnn_dets(
+ maskrcnn_person["segmentation"], cse_dets, self.mask_cse_iou_combine_threshold)
+
+ persons_with_cse = CSEPersonDetection(
+ combined_segmentation, cse_dets, **self.cse_post_process_cfg,
+ embed_map=embed_map, orig_imshape_CHW=im.shape
+ )
+ persons_with_cse.pre_process()
+ not_matched = [i for i in range(maskrcnn_person["segmentation"].shape[0]) if i not in matches[:, 0]]
+ persons_without_cse = PersonDetection(
+ maskrcnn_person["segmentation"][not_matched], **self.cse_post_process_cfg,
+ orig_imshape_CHW=im.shape
+ )
+ persons_without_cse.pre_process()
+
+ face_boxes_covered = box1_inside_box2(face_boxes, persons_with_cse.dilated_boxes).logical_or(
+ box1_inside_box2(face_boxes, persons_without_cse.dilated_boxes)
+ )
+ face_boxes = face_boxes[face_boxes_covered.logical_not()]
+ face_boxes = FaceDetection(face_boxes, **self.face_post_process_cfg)
+
+ # Order matters. The anonymizer will anonymize FIFO.
+ # Later detections will overwrite.
+ all_detections = [face_boxes, maskrcnn_other, persons_without_cse, persons_with_cse]
+ return all_detections
diff --git a/project/models/deprecated_deep_privacy2/dp2/detection/deep_privacy1_detector.py b/project/models/deprecated_deep_privacy2/dp2/detection/deep_privacy1_detector.py
new file mode 100644
index 0000000..e4a588b
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/detection/deep_privacy1_detector.py
@@ -0,0 +1,106 @@
+import torch
+import tops
+import lzma
+from torchvision.models.detection import keypointrcnn_resnet50_fpn, KeypointRCNN_ResNet50_FPN_Weights
+from .base import BaseDetector
+from face_detection import build_detector as build_face_detector
+from .structures import FaceDetection
+from tops import logger
+from pathlib import Path
+
+def is_keypoint_within_bbox(x0, y0, x1, y1, keypoint):
+ keypoint = keypoint[:3, :] # only nose + eyes are relevant
+ kp_X = keypoint[:, 0]
+ kp_Y = keypoint[:, 1]
+ within_X = (kp_X >= x0).all() and (kp_X <= x1).all()
+ within_Y = (kp_Y >= y0).all() and (kp_Y <= y1).all()
+ return within_X and within_Y
+
+
+def match_bbox_keypoint(bounding_boxes, keypoints):
+ """
+ bounding_boxes shape: [N, 5]
+ keypoints: [N persons, K keypoints, (x, y)]
+ """
+ if len(bounding_boxes) == 0 or len(keypoints) == 0:
+ return torch.empty((0, 4)), torch.empty((0, 7, 2))
+ assert bounding_boxes.shape[1] == 4,\
+ f"Shape was : {bounding_boxes.shape}"
+ assert keypoints.shape[-1] == 2,\
+ f"Expected (x,y) in last axis, got: {keypoints.shape}"
+ assert keypoints.shape[1] in (5, 7),\
+ f"Expeted 5 or 7 keypoints. Keypoint shape was: {keypoints.shape}"
+
+ matches = []
+ for bbox_idx, bbox in enumerate(bounding_boxes):
+ keypoint = None
+ for kp_idx, keypoint in enumerate(keypoints):
+ if kp_idx in (x[1] for x in matches):
+ continue
+ if is_keypoint_within_bbox(*bbox, keypoint):
+ matches.append((bbox_idx, kp_idx))
+ break
+ keypoint_idx = [x[1] for x in matches]
+ bbox_idx = [x[0] for x in matches]
+ return bounding_boxes[bbox_idx], keypoints[keypoint_idx]
+
+
+class DeepPrivacy1Detector(BaseDetector):
+
+ def __init__(self,
+ keypoint_threshold: float,
+ face_detector_cfg,
+ score_threshold: float,
+ face_post_process_cfg,
+ **kwargs):
+ super().__init__(**kwargs)
+ self.keypoint_detector = tops.to_cuda(keypointrcnn_resnet50_fpn(
+ weights=KeypointRCNN_ResNet50_FPN_Weights.COCO_V1).eval())
+ self.keypoint_threshold = keypoint_threshold
+ self.face_detector = build_face_detector(**face_detector_cfg, confidence_threshold=score_threshold)
+ self.face_mean = tops.to_cuda(torch.from_numpy(self.face_detector.mean).view(3, 1, 1))
+ self.face_post_process_cfg = face_post_process_cfg
+
+ @torch.no_grad()
+ def _detect_faces(self, im: torch.Tensor):
+ H, W = im.shape[1:]
+ im = im.float() - self.face_mean
+ im = self.face_detector.resize(im[None], 1.0)
+ boxes_XYXY = self.face_detector._batched_detect(im)[0][:, :-1] # Remove score
+ boxes_XYXY[:, [0, 2]] *= W
+ boxes_XYXY[:, [1, 3]] *= H
+ return boxes_XYXY.round().long().cpu()
+
+ @torch.no_grad()
+ def _detect_keypoints(self, img: torch.Tensor):
+ img = img.float() / 255
+ outputs = self.keypoint_detector([img])
+
+ # Shape: [N persons, K keypoints, (x,y,visibility)]
+ keypoints = outputs[0]["keypoints"]
+ scores = outputs[0]["scores"]
+ assert list(scores) == sorted(list(scores))[::-1]
+ mask = scores >= self.keypoint_threshold
+ keypoints = keypoints[mask, :, :2]
+ return keypoints[:, :7, :2]
+
+ def __call__(self, *args, **kwargs):
+ return self.forward(*args, **kwargs)
+
+ @torch.no_grad()
+ def forward(self, im: torch.Tensor):
+ face_boxes = self._detect_faces(im)
+ keypoints = self._detect_keypoints(im)
+ face_boxes, keypoints = match_bbox_keypoint(face_boxes, keypoints)
+ face_boxes = FaceDetection(face_boxes, **self.face_post_process_cfg, keypoints=keypoints)
+ return [face_boxes]
+
+ def load_from_cache(self, cache_path: Path):
+ logger.log(f"Loading detection from cache path: {cache_path}",)
+ with lzma.open(cache_path, "rb") as fp:
+ state_dict = torch.load(fp, map_location="cpu")
+ kwargs = self.face_post_process_cfg
+ return [
+ state["cls"].from_state_dict(**kwargs, state_dict=state)
+ for state in state_dict
+ ]
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/dp2/detection/face_detector.py b/project/models/deprecated_deep_privacy2/dp2/detection/face_detector.py
new file mode 100644
index 0000000..8354d7b
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/detection/face_detector.py
@@ -0,0 +1,62 @@
+import torch
+import lzma
+import tops
+from pathlib import Path
+from dp2.detection.base import BaseDetector
+from face_detection import build_detector as build_face_detector
+from .structures import FaceDetection
+from tops import logger
+
+
+def box1_inside_box2(box1: torch.Tensor, box2: torch.Tensor):
+ assert len(box1.shape) == 2
+ assert len(box2.shape) == 2
+ box1_inside = torch.zeros(box1.shape[0], device=box1.device, dtype=torch.bool)
+ # This can be batched
+ for i, box in enumerate(box1):
+ is_outside_lefttop = (box[None, [0, 1]] <= box2[:, [0, 1]]).any(dim=1)
+ is_outside_rightbot = (box[None, [2, 3]] >= box2[:, [2, 3]]).any(dim=1)
+ is_outside = is_outside_lefttop.logical_or(is_outside_rightbot)
+ box1_inside[i] = is_outside.logical_not().any()
+ return box1_inside
+
+
+class FaceDetector(BaseDetector):
+
+ def __init__(
+ self,
+ face_detector_cfg: dict,
+ score_threshold: float,
+ face_post_process_cfg: dict,
+ **kwargs
+ ) -> None:
+ super().__init__(**kwargs)
+ self.face_detector = build_face_detector(**face_detector_cfg, confidence_threshold=score_threshold)
+ self.face_mean = tops.to_cuda(torch.from_numpy(self.face_detector.mean).view(3, 1, 1))
+ self.face_post_process_cfg = face_post_process_cfg
+
+ def __call__(self, *args, **kwargs):
+ return self.forward(*args, **kwargs)
+
+ def _detect_faces(self, im: torch.Tensor):
+ H, W = im.shape[1:]
+ im = im.float() - self.face_mean
+ im = self.face_detector.resize(im[None], 1.0)
+ boxes_XYXY = self.face_detector._batched_detect(im)[0][:, :-1] # Remove score
+ boxes_XYXY[:, [0, 2]] *= W
+ boxes_XYXY[:, [1, 3]] *= H
+ return boxes_XYXY.round().long().cpu()
+
+ @torch.no_grad()
+ def forward(self, im: torch.Tensor):
+ face_boxes = self._detect_faces(im)
+ face_boxes = FaceDetection(face_boxes, **self.face_post_process_cfg)
+ return [face_boxes]
+
+ def load_from_cache(self, cache_path: Path):
+ logger.log(f"Loading detection from cache path: {cache_path}")
+ with lzma.open(cache_path, "rb") as fp:
+ state_dict = torch.load(fp)
+ return [
+ state["cls"].from_state_dict(state_dict=state, **self.face_post_process_cfg) for state in state_dict
+ ]
diff --git a/project/models/deprecated_deep_privacy2/dp2/detection/models/__init__.py b/project/models/deprecated_deep_privacy2/dp2/detection/models/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/project/models/deprecated_deep_privacy2/dp2/detection/models/cse.py b/project/models/deprecated_deep_privacy2/dp2/detection/models/cse.py
new file mode 100644
index 0000000..7b9fbf7
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/detection/models/cse.py
@@ -0,0 +1,134 @@
+import torch
+from typing import List
+import tops
+from torchvision.transforms.functional import InterpolationMode, resize
+from densepose.data.utils import get_class_to_mesh_name_mapping
+from densepose import add_densepose_config
+from densepose.structures import DensePoseEmbeddingPredictorOutput
+from densepose.vis.extractor import DensePoseOutputsExtractor
+from densepose.modeling import build_densepose_embedder
+from detectron2.config import get_cfg
+from detectron2.data.transforms import ResizeShortestEdge
+from detectron2.checkpoint.detection_checkpoint import DetectionCheckpointer
+from detectron2.modeling import build_model
+
+
+model_urls = {
+ "https://raw.githubusercontent.com/facebookresearch/detectron2/main/projects/DensePose/configs/cse/densepose_rcnn_R_101_FPN_DL_soft_s1x.yaml": "https://dl.fbaipublicfiles.com/densepose/cse/densepose_rcnn_R_101_FPN_DL_soft_s1x/250713061/model_final_1d3314.pkl",
+ "https://raw.githubusercontent.com/facebookresearch/detectron2/main/projects/DensePose/configs/cse/densepose_rcnn_R_50_FPN_s1x.yaml": "https://dl.fbaipublicfiles.com/densepose/cse/densepose_rcnn_R_50_FPN_s1x/251155172/model_final_c4ea5f.pkl",
+}
+
+
+def cse_det_to_global(boxes_XYXY, S: torch.Tensor, imshape):
+ assert len(S.shape) == 3
+ H, W = imshape
+ N = len(boxes_XYXY)
+ segmentation = torch.zeros((N, H, W), dtype=torch.bool, device=S.device)
+ boxes_XYXY = boxes_XYXY.long()
+ for i in range(N):
+ x0, y0, x1, y1 = boxes_XYXY[i]
+ assert x0 >= 0 and y0 >= 0
+ assert x1 <= imshape[1]
+ assert y1 <= imshape[0]
+ h = y1 - y0
+ w = x1 - x0
+ segmentation[i:i+1, y0:y1, x0:x1] = resize(S[i:i+1], (h, w), interpolation=InterpolationMode.NEAREST) > 0
+ return segmentation
+
+
+class CSEDetector:
+
+ def __init__(
+ self,
+ cfg_url: str = "https://raw.githubusercontent.com/facebookresearch/detectron2/main/projects/DensePose/configs/cse/densepose_rcnn_R_101_FPN_DL_soft_s1x.yaml",
+ cfg_2_download: List[str] = [
+ "https://raw.githubusercontent.com/facebookresearch/detectron2/main/projects/DensePose/configs/cse/densepose_rcnn_R_101_FPN_DL_soft_s1x.yaml",
+ "https://raw.githubusercontent.com/facebookresearch/detectron2/main/projects/DensePose/configs/cse/Base-DensePose-RCNN-FPN.yaml",
+ "https://raw.githubusercontent.com/facebookresearch/detectron2/main/projects/DensePose/configs/cse/Base-DensePose-RCNN-FPN-Human.yaml"],
+ score_thres: float = 0.9,
+ nms_thresh: float = None,
+ ) -> None:
+ with tops.logger.capture_log_stdout():
+ cfg = get_cfg()
+ self.device = tops.get_device()
+ add_densepose_config(cfg)
+ cfg_path = tops.download_file(cfg_url)
+ for p in cfg_2_download:
+ tops.download_file(p)
+ with tops.logger.capture_log_stdout():
+ cfg.merge_from_file(cfg_path)
+ assert cfg_url in model_urls, cfg_url
+ model_path = tops.download_file(model_urls[cfg_url])
+ cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = score_thres
+ if nms_thresh is not None:
+ cfg.MODEL.ROI_HEADS.NMS_THRESH_TEST = nms_thresh
+ cfg.MODEL.WEIGHTS = str(model_path)
+ cfg.MODEL.DEVICE = str(self.device)
+ cfg.freeze()
+ with tops.logger.capture_log_stdout():
+ self.model = build_model(cfg)
+ self.model.eval()
+ DetectionCheckpointer(self.model).load(str(model_path))
+ self.input_format = cfg.INPUT.FORMAT
+ self.densepose_extractor = DensePoseOutputsExtractor()
+ self.class_to_mesh_name = get_class_to_mesh_name_mapping(cfg)
+
+ self.embedder = build_densepose_embedder(cfg)
+ self.mesh_vertex_embeddings = {
+ mesh_name: self.embedder(mesh_name).to(self.device)
+ for mesh_name in self.class_to_mesh_name.values()
+ if self.embedder.has_embeddings(mesh_name)
+ }
+ self.cfg = cfg
+ self.embed_map = self.mesh_vertex_embeddings["smpl_27554"]
+ tops.logger.log("CSEDetector built.")
+
+ def __call__(self, *args, **kwargs):
+ return self.forward(*args, **kwargs)
+
+ def resize_im(self, im):
+ H, W = im.shape[1:]
+ newH, newW = ResizeShortestEdge.get_output_shape(
+ H, W, self.cfg.INPUT.MIN_SIZE_TEST, self.cfg.INPUT.MAX_SIZE_TEST)
+ return resize(
+ im, (newH, newW), InterpolationMode.BILINEAR, antialias=True)
+
+ @torch.no_grad()
+ def forward(self, im):
+ assert im.dtype == torch.uint8
+ if self.input_format == "BGR":
+ im = im.flip(0)
+ H, W = im.shape[1:]
+ im = self.resize_im(im)
+ output = self.model([{"image": im, "height": H, "width": W}])[0]["instances"]
+ scores = output.get("scores")
+ if len(scores) == 0:
+ return dict(
+ instance_segmentation=torch.empty((0, 0, 112, 112), dtype=torch.bool, device=im.device),
+ instance_embedding=torch.empty((0, 16, 112, 112), dtype=torch.float32, device=im.device),
+ embed_map=self.mesh_vertex_embeddings["smpl_27554"],
+ bbox_XYXY=torch.empty((0, 4), dtype=torch.long, device=im.device),
+ im_segmentation=torch.empty((0, H, W), dtype=torch.bool, device=im.device),
+ scores=torch.empty((0), dtype=torch.float, device=im.device)
+ )
+ pred_densepose, boxes_xywh, classes = self.densepose_extractor(output)
+ assert isinstance(pred_densepose, DensePoseEmbeddingPredictorOutput), pred_densepose
+ S = pred_densepose.coarse_segm.argmax(dim=1) # Segmentation channel Nx2xHxW (2 because only 2 classes)
+ E = pred_densepose.embedding
+ mesh_name = self.class_to_mesh_name[classes[0]]
+ assert mesh_name == "smpl_27554"
+ x0, y0, w, h = [boxes_xywh[:, i] for i in range(4)]
+ boxes_XYXY = torch.stack((x0, y0, x0+w, y0+h), dim=-1)
+ boxes_XYXY = boxes_XYXY.round_().long()
+
+ non_empty_boxes = (boxes_XYXY[:, :2] == boxes_XYXY[:, 2:]).any(dim=1).logical_not()
+ S = S[non_empty_boxes]
+ E = E[non_empty_boxes]
+ boxes_XYXY = boxes_XYXY[non_empty_boxes]
+ scores = scores[non_empty_boxes]
+ im_segmentation = cse_det_to_global(boxes_XYXY, S, [H, W])
+ return dict(
+ instance_segmentation=S, instance_embedding=E,
+ bbox_XYXY=boxes_XYXY,
+ im_segmentation=im_segmentation,
+ scores=scores.view(-1))
diff --git a/project/models/deprecated_deep_privacy2/dp2/detection/models/keypoint_maskrcnn.py b/project/models/deprecated_deep_privacy2/dp2/detection/models/keypoint_maskrcnn.py
new file mode 100644
index 0000000..8ddc8b2
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/detection/models/keypoint_maskrcnn.py
@@ -0,0 +1,111 @@
+import numpy as np
+import torch
+from detectron2.checkpoint import DetectionCheckpointer
+from detectron2.modeling.roi_heads import CascadeROIHeads, StandardROIHeads
+from detectron2.data.transforms import ResizeShortestEdge
+from detectron2.structures import Instances
+from detectron2 import model_zoo
+from detectron2.config import instantiate
+from detectron2.config import LazyCall as L
+from PIL import Image
+import tops
+import functools
+from torchvision.transforms.functional import resize
+
+
+def get_rn50_fpn_keypoint_rcnn(weight_path: str):
+ from detectron2.modeling.poolers import ROIPooler
+ from detectron2.modeling.roi_heads import KRCNNConvDeconvUpsampleHead
+ from detectron2.layers import ShapeSpec
+ model = model_zoo.get_config("common/models/mask_rcnn_fpn.py").model
+ model.roi_heads.update(
+ num_classes=1,
+ keypoint_in_features=["p2", "p3", "p4", "p5"],
+ keypoint_pooler=L(ROIPooler)(
+ output_size=14,
+ scales=(1.0 / 4, 1.0 / 8, 1.0 / 16, 1.0 / 32),
+ sampling_ratio=0,
+ pooler_type="ROIAlignV2",
+ ),
+ keypoint_head=L(KRCNNConvDeconvUpsampleHead)(
+ input_shape=ShapeSpec(channels=256, width=14, height=14),
+ num_keypoints=17,
+ conv_dims=[512] * 8,
+ loss_normalizer="visible",
+ ),
+ )
+
+ # Detectron1 uses 2000 proposals per-batch, but this option is per-image in detectron2.
+ # 1000 proposals per-image is found to hurt box AP.
+ # Therefore we increase it to 1500 per-image.
+ model.proposal_generator.post_nms_topk = (1500, 1000)
+
+ # Keypoint AP degrades (though box AP improves) when using plain L1 loss
+ model.roi_heads.box_predictor.smooth_l1_beta = 0.5
+ model = instantiate(model)
+
+ dataloader = model_zoo.get_config("common/data/coco_keypoint.py").dataloader
+ test_transform = instantiate(dataloader.test.mapper.augmentations)
+ DetectionCheckpointer(model).load(weight_path)
+ return model, test_transform
+
+
+models = {
+ "rn50_fpn_maskrcnn": functools.partial(get_rn50_fpn_keypoint_rcnn, weight_path="https://api.loke.aws.unit.no/dlr-gui-backend-resources-content/v2/contents/links/532a57f3-594b-4ec9-a6db-ef2e328ad60ae337668e-a83c-4222-9fa0-cec6f91adf4841b9a42e-a28e-403e-8b96-d55ac443b8c6")
+}
+
+
+class KeypointMaskRCNN:
+
+ def __init__(self, model_name: str, score_threshold: float) -> None:
+ assert model_name in models, f"Did not find {model_name} in models"
+ model, test_transform = models[model_name]()
+ self.model = model.eval().to(tops.get_device())
+ if isinstance(self.model.roi_heads, CascadeROIHeads):
+ for head in self.model.roi_heads.box_predictors:
+ assert hasattr(head, "test_score_thresh")
+ head.test_score_thresh = score_threshold
+ else:
+ assert isinstance(self.model.roi_heads, StandardROIHeads)
+ assert hasattr(self.model.roi_heads.box_predictor, "test_score_thresh")
+ self.model.roi_heads.box_predictor.test_score_thresh = score_threshold
+
+ self.test_transform = test_transform
+ assert len(self.test_transform) == 1
+ self.test_transform = self.test_transform[0]
+ assert isinstance(self.test_transform, ResizeShortestEdge)
+ assert self.test_transform.interp == Image.BILINEAR
+ self.image_format = self.model.input_format
+
+ def resize_im(self, im):
+ H, W = im.shape[-2:]
+ if self.test_transform.is_range:
+ size = np.random.randint(
+ self.test_transform.short_edge_length[0], self.test_transform.short_edge_length[1] + 1)
+ else:
+ size = np.random.choice(self.test_transform.short_edge_length)
+ newH, newW = ResizeShortestEdge.get_output_shape(H, W, size, self.test_transform.max_size)
+ return resize(
+ im, (newH, newW), antialias=True)
+
+ def __call__(self, *args, **kwargs):
+ return self.forward(*args, **kwargs)
+
+ @torch.no_grad()
+ def forward(self, im: torch.Tensor):
+ assert im.ndim == 3
+ if self.image_format == "BGR":
+ im = im.flip(0)
+ H, W = im.shape[-2:]
+ im = im.float()
+ im = self.resize_im(im)
+
+ inputs = dict(image=im, height=H, width=W)
+ # instances contains
+ # dict_keys(['pred_boxes', 'scores', 'pred_classes', 'pred_masks', 'pred_keypoints', 'pred_keypoint_heatmaps'])
+ instances = self.model([inputs])[0]["instances"]
+ return dict(
+ scores=instances.get("scores").cpu(),
+ segmentation=instances.get("pred_masks").cpu(),
+ keypoints=instances.get("pred_keypoints").cpu()
+ )
diff --git a/project/models/deprecated_deep_privacy2/dp2/detection/models/mask_rcnn.py b/project/models/deprecated_deep_privacy2/dp2/detection/models/mask_rcnn.py
new file mode 100644
index 0000000..ed64706
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/detection/models/mask_rcnn.py
@@ -0,0 +1,78 @@
+import torch
+import tops
+from detectron2.modeling import build_model
+from detectron2.checkpoint import DetectionCheckpointer
+from detectron2.structures import Boxes
+from detectron2.data import MetadataCatalog
+from detectron2 import model_zoo
+from typing import Dict
+from detectron2.data.transforms import ResizeShortestEdge
+from torchvision.transforms.functional import resize
+
+
+model_urls = {
+ "COCO-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_3x.yaml": "https://dl.fbaipublicfiles.com/detectron2/COCO-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_3x/139653917/model_final_2d9806.pkl",
+
+}
+
+
+class MaskRCNNDetector:
+
+ def __init__(
+ self,
+ cfg_name: str = "COCO-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_3x.yaml",
+ score_thres: float = 0.9,
+ class_filter=["person"], # ["car", "bicycle","truck", "bus", "backpack"]
+ fp16_inference: bool = False
+ ) -> None:
+ cfg = model_zoo.get_config(cfg_name)
+ cfg.MODEL.DEVICE = str(tops.get_device())
+ cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = score_thres
+ cfg.freeze()
+ self.cfg = cfg
+ with tops.logger.capture_log_stdout():
+ self.model = build_model(cfg)
+ DetectionCheckpointer(self.model).load(model_urls[cfg_name])
+ self.model.eval()
+ self.input_format = cfg.INPUT.FORMAT
+ self.class_names = MetadataCatalog.get(cfg.DATASETS.TRAIN[0]).thing_classes
+ self.class_to_keep = set([self.class_names.index(cls_) for cls_ in class_filter])
+ self.person_class = self.class_names.index("person")
+ self.fp16_inference = fp16_inference
+ tops.logger.log("Mask R-CNN built.")
+
+ def __call__(self, *args, **kwargs):
+ return self.forward(*args, **kwargs)
+
+ def resize_im(self, im):
+ H, W = im.shape[1:]
+ newH, newW = ResizeShortestEdge.get_output_shape(
+ H, W, self.cfg.INPUT.MIN_SIZE_TEST, self.cfg.INPUT.MAX_SIZE_TEST)
+ return resize(
+ im, (newH, newW), antialias=True)
+
+ @torch.no_grad()
+ def forward(self, im: torch.Tensor):
+ if self.input_format == "BGR":
+ im = im.flip(0)
+ else:
+ assert self.input_format == "RGB"
+ H, W = im.shape[-2:]
+ im = self.resize_im(im)
+ with torch.cuda.amp.autocast(enabled=self.fp16_inference):
+ output = self.model([{"image": im, "height": H, "width": W}])[0]["instances"]
+ scores = output.get("scores")
+ N = len(scores)
+ classes = output.get("pred_classes")
+ idx2keep = [i for i in range(N) if classes[i].tolist() in self.class_to_keep]
+ classes = classes[idx2keep]
+ assert isinstance(output.get("pred_boxes"), Boxes)
+ segmentation = output.get("pred_masks")[idx2keep]
+ assert segmentation.dtype == torch.bool
+ is_person = classes == self.person_class
+ return {
+ "scores": output.get("scores")[idx2keep],
+ "segmentation": segmentation,
+ "classes": output.get("pred_classes")[idx2keep],
+ "is_person": is_person
+ }
diff --git a/project/models/deprecated_deep_privacy2/dp2/detection/models/vit_pose/backbone.py b/project/models/deprecated_deep_privacy2/dp2/detection/models/vit_pose/backbone.py
new file mode 100644
index 0000000..f78712d
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/detection/models/vit_pose/backbone.py
@@ -0,0 +1,311 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+# Code adapted from: https://github.com/gpastal24/ViTPose-Pytorch
+import torch
+from functools import partial
+import torch.nn as nn
+import torch.utils.checkpoint as checkpoint
+
+from timm.models.layers import drop_path, to_2tuple, trunc_normal_
+
+
+class DropPath(nn.Module):
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
+ """
+
+ def __init__(self, drop_prob=None):
+ super(DropPath, self).__init__()
+ self.drop_prob = drop_prob
+
+ def forward(self, x):
+ return drop_path(x, self.drop_prob, self.training)
+
+ def extra_repr(self):
+ return 'p={}'.format(self.drop_prob)
+
+
+class Mlp(nn.Module):
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
+ super().__init__()
+ out_features = out_features or in_features
+ hidden_features = hidden_features or in_features
+ self.fc1 = nn.Linear(in_features, hidden_features)
+ self.act = act_layer()
+ self.fc2 = nn.Linear(hidden_features, out_features)
+ self.drop = nn.Dropout(drop)
+
+ def forward(self, x):
+ x = self.fc1(x)
+ x = self.act(x)
+ x = self.fc2(x)
+ x = self.drop(x)
+ return x
+
+
+class Attention(nn.Module):
+ def __init__(
+ self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.,
+ proj_drop=0., attn_head_dim=None,):
+ super().__init__()
+ self.num_heads = num_heads
+ head_dim = dim // num_heads
+ self.dim = dim
+
+ if attn_head_dim is not None:
+ head_dim = attn_head_dim
+ all_head_dim = head_dim * self.num_heads
+
+ self.scale = qk_scale or head_dim ** -0.5
+
+ self.qkv = nn.Linear(dim, all_head_dim * 3, bias=qkv_bias)
+
+ self.attn_drop = nn.Dropout(attn_drop)
+ self.proj = nn.Linear(all_head_dim, dim)
+ self.proj_drop = nn.Dropout(proj_drop)
+
+ def forward(self, x):
+ B, N, C = x.shape
+ qkv = self.qkv(x)
+ qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
+ q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
+
+ q = q * self.scale
+ attn = (q @ k.transpose(-2, -1))
+
+ attn = attn.softmax(dim=-1)
+ attn = self.attn_drop(attn)
+
+ x = (attn @ v).transpose(1, 2).reshape(B, N, -1)
+ x = self.proj(x)
+ x = self.proj_drop(x)
+
+ return x
+
+
+class Block(nn.Module):
+
+ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None,
+ drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU,
+ norm_layer=nn.LayerNorm, attn_head_dim=None
+ ):
+ super().__init__()
+
+ self.norm1 = norm_layer(dim)
+ self.attn = Attention(
+ dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
+ attn_drop=attn_drop, proj_drop=drop, attn_head_dim=attn_head_dim
+ )
+
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
+ self.norm2 = norm_layer(dim)
+ mlp_hidden_dim = int(dim * mlp_ratio)
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
+
+ def forward(self, x):
+ x = x + self.drop_path(self.attn(self.norm1(x)))
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
+ return x
+
+
+class PatchEmbed(nn.Module):
+ """ Image to Patch Embedding
+ """
+
+ def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, ratio=1):
+ super().__init__()
+ img_size = to_2tuple(img_size)
+ patch_size = to_2tuple(patch_size)
+ num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0]) * (ratio ** 2)
+ self.patch_shape = (int(img_size[0] // patch_size[0] * ratio), int(img_size[1] // patch_size[1] * ratio))
+ self.origin_patch_shape = (int(img_size[0] // patch_size[0]), int(img_size[1] // patch_size[1]))
+ self.img_size = img_size
+ self.patch_size = patch_size
+ self.num_patches = num_patches
+
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=(
+ patch_size[0] // ratio), padding=4 + 2 * (ratio//2-1))
+
+ def forward(self, x, **kwargs):
+ B, C, H, W = x.shape
+ x = self.proj(x)
+ Hp, Wp = x.shape[2], x.shape[3]
+
+ x = x.flatten(2).transpose(1, 2)
+ return x, (Hp, Wp)
+
+
+class HybridEmbed(nn.Module):
+ """ CNN Feature Map Embedding
+ Extract feature map from CNN, flatten, project to embedding dim.
+ """
+
+ def __init__(self, backbone, img_size=224, feature_size=None, in_chans=3, embed_dim=768):
+ super().__init__()
+ assert isinstance(backbone, nn.Module)
+ img_size = to_2tuple(img_size)
+ self.img_size = img_size
+ self.backbone = backbone
+ if feature_size is None:
+ with torch.no_grad():
+ training = backbone.training
+ if training:
+ backbone.eval()
+ o = self.backbone(torch.zeros(1, in_chans, img_size[0], img_size[1]))[-1]
+ feature_size = o.shape[-2:]
+ feature_dim = o.shape[1]
+ backbone.train(training)
+ else:
+ feature_size = to_2tuple(feature_size)
+ feature_dim = self.backbone.feature_info.channels()[-1]
+ self.num_patches = feature_size[0] * feature_size[1]
+ self.proj = nn.Linear(feature_dim, embed_dim)
+
+ def forward(self, x):
+ x = self.backbone(x)[-1]
+ x = x.flatten(2).transpose(1, 2)
+ x = self.proj(x)
+ return x
+
+
+# @BACKBONES.register_module()
+class ViT(nn.Module):
+
+ def __init__(self,
+ img_size=224, patch_size=16, in_chans=3, num_classes=80, embed_dim=768, depth=12,
+ num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0.,
+ drop_path_rate=0., hybrid_backbone=None, norm_layer=None, use_checkpoint=False,
+ frozen_stages=-1, ratio=1, last_norm=True,
+ patch_padding='pad', freeze_attn=False, freeze_ffn=False,
+ ):
+ # Protect mutable default arguments
+ super(ViT, self).__init__()
+ norm_layer = norm_layer or partial(nn.LayerNorm, eps=1e-6)
+ self.num_classes = num_classes
+ self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
+ self.frozen_stages = frozen_stages
+ self.use_checkpoint = use_checkpoint
+ self.patch_padding = patch_padding
+ self.freeze_attn = freeze_attn
+ self.freeze_ffn = freeze_ffn
+ self.depth = depth
+
+ if hybrid_backbone is not None:
+ self.patch_embed = HybridEmbed(
+ hybrid_backbone, img_size=img_size, in_chans=in_chans, embed_dim=embed_dim)
+ else:
+ self.patch_embed = PatchEmbed(
+ img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim, ratio=ratio)
+ num_patches = self.patch_embed.num_patches
+
+ # since the pretraining model has class token
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))
+
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
+
+ self.blocks = nn.ModuleList([
+ Block(
+ dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer,
+ )
+ for i in range(depth)])
+
+ self.last_norm = norm_layer(embed_dim) if last_norm else nn.Identity()
+
+ if self.pos_embed is not None:
+ trunc_normal_(self.pos_embed, std=.02)
+
+ self._freeze_stages()
+
+ def _freeze_stages(self):
+ """Freeze parameters."""
+ if self.frozen_stages >= 0:
+ self.patch_embed.eval()
+ for param in self.patch_embed.parameters():
+ param.requires_grad = False
+
+ for i in range(1, self.frozen_stages + 1):
+ m = self.blocks[i]
+ m.eval()
+ for param in m.parameters():
+ param.requires_grad = False
+
+ if self.freeze_attn:
+ for i in range(0, self.depth):
+ m = self.blocks[i]
+ m.attn.eval()
+ m.norm1.eval()
+ for param in m.attn.parameters():
+ param.requires_grad = False
+ for param in m.norm1.parameters():
+ param.requires_grad = False
+
+ if self.freeze_ffn:
+ self.pos_embed.requires_grad = False
+ self.patch_embed.eval()
+ for param in self.patch_embed.parameters():
+ param.requires_grad = False
+ for i in range(0, self.depth):
+ m = self.blocks[i]
+ m.mlp.eval()
+ m.norm2.eval()
+ for param in m.mlp.parameters():
+ param.requires_grad = False
+ for param in m.norm2.parameters():
+ param.requires_grad = False
+
+ def init_weights(self, pretrained=None):
+ """Initialize the weights in backbone.
+ Args:
+ pretrained (str, optional): Path to pre-trained weights.
+ Defaults to None.
+ """
+ super().init_weights(pretrained, patch_padding=self.patch_padding)
+
+ if pretrained is None:
+ def _init_weights(m):
+ if isinstance(m, nn.Linear):
+ trunc_normal_(m.weight, std=.02)
+ if isinstance(m, nn.Linear) and m.bias is not None:
+ nn.init.constant_(m.bias, 0)
+ elif isinstance(m, nn.LayerNorm):
+ nn.init.constant_(m.bias, 0)
+ nn.init.constant_(m.weight, 1.0)
+
+ self.apply(_init_weights)
+
+ def get_num_layers(self):
+ return len(self.blocks)
+
+ @torch.jit.ignore
+ def no_weight_decay(self):
+ return {'pos_embed', 'cls_token'}
+
+ def forward_features(self, x):
+ B, C, H, W = x.shape
+ x, (Hp, Wp) = self.patch_embed(x)
+
+ if self.pos_embed is not None:
+ # fit for multiple GPU training
+ # since the first element for pos embed (sin-cos manner) is zero, it will cause no difference
+ x = x + self.pos_embed[:, 1:] + self.pos_embed[:, :1]
+
+ for blk in self.blocks:
+ if self.use_checkpoint:
+ x = checkpoint.checkpoint(blk, x)
+ else:
+ x = blk(x)
+
+ x = self.last_norm(x)
+
+ xp = x.permute(0, 2, 1).reshape(B, -1, Hp, Wp).contiguous()
+
+ return xp
+
+ def forward(self, x):
+ x = self.forward_features(x)
+ return x
+
+ def train(self, mode=True):
+ """Convert the model into training mode."""
+ super().train(mode)
+ self._freeze_stages()
diff --git a/project/models/deprecated_deep_privacy2/dp2/detection/models/vit_pose/topdown_heatmap_simple_head.py b/project/models/deprecated_deep_privacy2/dp2/detection/models/vit_pose/topdown_heatmap_simple_head.py
new file mode 100644
index 0000000..85c08a7
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/detection/models/vit_pose/topdown_heatmap_simple_head.py
@@ -0,0 +1,505 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+# Code adapted from: https://github.com/gpastal24/ViTPose-Pytorch
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+# Copyright (c) OpenMMLab. All rights reserved.
+from abc import ABCMeta, abstractmethod
+
+# from mmpose.core.evaluation.top_down_eval import keypoints_from_heatmaps
+
+
+class TopdownHeatmapBaseHead(nn.Module):
+ """Base class for top-down heatmap heads.
+
+ All top-down heatmap heads should subclass it.
+ All subclass should overwrite:
+
+ Methods:`get_loss`, supporting to calculate loss.
+ Methods:`get_accuracy`, supporting to calculate accuracy.
+ Methods:`forward`, supporting to forward model.
+ Methods:`inference_model`, supporting to inference model.
+ """
+
+ __metaclass__ = ABCMeta
+
+ @abstractmethod
+ def get_loss(self, **kwargs):
+ """Gets the loss."""
+
+ @abstractmethod
+ def get_accuracy(self, **kwargs):
+ """Gets the accuracy."""
+
+ @abstractmethod
+ def forward(self, **kwargs):
+ """Forward function."""
+
+ @abstractmethod
+ def inference_model(self, **kwargs):
+ """Inference function."""
+
+ def decode(self, img_metas, output, **kwargs):
+ """Decode keypoints from heatmaps.
+
+ Args:
+ img_metas (list(dict)): Information about data augmentation
+ By default this includes:
+
+ - "image_file: path to the image file
+ - "center": center of the bbox
+ - "scale": scale of the bbox
+ - "rotation": rotation of the bbox
+ - "bbox_score": score of bbox
+ output (np.ndarray[N, K, H, W]): model predicted heatmaps.
+ """
+ # batch_size = len(img_metas)
+
+ # if 'bbox_id' in img_metas[0]:
+ # bbox_ids = []
+ # else:
+ # bbox_ids = None
+
+ # c = np.zeros((batch_size, 2), dtype=np.float32)
+ # s = np.zeros((batch_size, 2), dtype=np.float32)
+ # image_paths = []
+ # score = np.ones(batch_size)
+ # for i in range(batch_size):
+ # c[i, :] = img_metas[i]['center']
+ # s[i, :] = img_metas[i]['scale']
+ # image_paths.append(img_metas[i]['image_file'])
+
+ # if 'bbox_score' in img_metas[i]:
+ # score[i] = np.array(img_metas[i]['bbox_score']).reshape(-1)
+ # if bbox_ids is not None:
+ # bbox_ids.append(img_metas[i]['bbox_id'])
+
+ # preds, maxvals = keypoints_from_heatmaps(
+ # output,
+ # c,
+ # s,
+ # unbiased=self.test_cfg.get('unbiased_decoding', False),
+ # post_process=self.test_cfg.get('post_process', 'default'),
+ # kernel=self.test_cfg.get('modulate_kernel', 11),
+ # valid_radius_factor=self.test_cfg.get('valid_radius_factor',
+ # 0.0546875),
+ # use_udp=self.test_cfg.get('use_udp', False),
+ # target_type=self.test_cfg.get('target_type', 'GaussianHeatmap'))
+
+ # all_preds = np.zeros((batch_size, preds.shape[1], 3), dtype=np.float32)
+ # all_boxes = np.zeros((batch_size, 6), dtype=np.float32)
+ # all_preds[:, :, 0:2] = preds[:, :, 0:2]
+ # all_preds[:, :, 2:3] = maxvals
+ # all_boxes[:, 0:2] = c[:, 0:2]
+ # all_boxes[:, 2:4] = s[:, 0:2]
+ # all_boxes[:, 4] = np.prod(s * 200.0, axis=1)
+ # all_boxes[:, 5] = score
+
+ # result = {}
+
+ # result['preds'] = all_preds
+ # result['boxes'] = all_boxes
+ # result['image_paths'] = image_paths
+ # result['bbox_ids'] = bbox_ids
+
+ return None
+
+ @staticmethod
+ def _get_deconv_cfg(deconv_kernel):
+ """Get configurations for deconv layers."""
+ if deconv_kernel == 4:
+ padding = 1
+ output_padding = 0
+ elif deconv_kernel == 3:
+ padding = 1
+ output_padding = 1
+ elif deconv_kernel == 2:
+ padding = 0
+ output_padding = 0
+ else:
+ raise ValueError(f'Not supported num_kernels ({deconv_kernel}).')
+
+ return deconv_kernel, padding, output_padding
+
+
+def build_conv_layer(cfg, *args, **kwargs) -> nn.Module:
+ """LICENSE"""
+
+ if cfg is None:
+ cfg_ = dict(type='Conv2d')
+ else:
+ if not isinstance(cfg, dict):
+ raise TypeError('cfg must be a dict')
+ if 'type' not in cfg:
+ raise KeyError('the cfg dict must contain the key "type"')
+ cfg_ = cfg.copy()
+
+ layer_type = cfg_.pop('type')
+ if layer_type != 'Conv2d':
+ raise KeyError(f'Unrecognized layer type {layer_type}')
+ else:
+ conv_layer = nn.Conv2d
+
+ layer = conv_layer(*args, **kwargs, **cfg_)
+
+ return layer
+
+
+def build_upsample_layer(cfg, *args, **kwargs) -> nn.Module:
+
+ if not isinstance(cfg, dict):
+ raise TypeError(f'cfg must be a dict, but got {type(cfg)}')
+ if 'type' not in cfg:
+ raise KeyError(
+ f'the cfg dict must contain the key "type", but got {cfg}')
+ cfg_ = cfg.copy()
+
+ layer_type = cfg_.pop('type')
+ if layer_type != 'deconv':
+ raise KeyError(f'Unrecognized upsample type {layer_type}')
+ else:
+ upsample = nn.ConvTranspose2d
+
+ if upsample is nn.Upsample:
+ cfg_['mode'] = layer_type
+ layer = upsample(*args, **kwargs, **cfg_)
+ return layer
+
+# @HEADS.register_module()
+
+
+class TopdownHeatmapSimpleHead(TopdownHeatmapBaseHead):
+ """Top-down heatmap simple head. paper ref: Bin Xiao et al. ``Simple
+ Baselines for Human Pose Estimation and Tracking``.
+
+ TopdownHeatmapSimpleHead is consisted of (>=0) number of deconv layers
+ and a simple conv2d layer.
+
+ Args:
+ in_channels (int): Number of input channels
+ out_channels (int): Number of output channels
+ num_deconv_layers (int): Number of deconv layers.
+ num_deconv_layers should >= 0. Note that 0 means
+ no deconv layers.
+ num_deconv_filters (list|tuple): Number of filters.
+ If num_deconv_layers > 0, the length of
+ num_deconv_kernels (list|tuple): Kernel sizes.
+ in_index (int|Sequence[int]): Input feature index. Default: 0
+ input_transform (str|None): Transformation type of input features.
+ Options: 'resize_concat', 'multiple_select', None.
+ Default: None.
+
+ - 'resize_concat': Multiple feature maps will be resized to the
+ same size as the first one and then concat together.
+ Usually used in FCN head of HRNet.
+ - 'multiple_select': Multiple feature maps will be bundle into
+ a list and passed into decode head.
+ - None: Only one select feature map is allowed.
+ align_corners (bool): align_corners argument of F.interpolate.
+ Default: False.
+ loss_keypoint (dict): Config for keypoint loss. Default: None.
+ """
+
+ def __init__(self,
+ in_channels,
+ out_channels,
+ num_deconv_layers=3,
+ num_deconv_filters=(256, 256, 256),
+ num_deconv_kernels=(4, 4, 4),
+ extra=None,
+ in_index=0,
+ input_transform=None,
+ align_corners=False,
+ loss_keypoint=None,
+ train_cfg=None,
+ test_cfg=None,
+ upsample=0,):
+ super().__init__()
+
+ self.in_channels = in_channels
+ self.loss = None
+ self.upsample = upsample
+
+ self.train_cfg = {} if train_cfg is None else train_cfg
+ self.test_cfg = {} if test_cfg is None else test_cfg
+ self.target_type = self.test_cfg.get('target_type', 'GaussianHeatmap')
+
+ self._init_inputs(in_channels, in_index, input_transform)
+ self.in_index = in_index
+ self.align_corners = align_corners
+
+ if extra is not None and not isinstance(extra, dict):
+ raise TypeError('extra should be dict or None.')
+
+ if num_deconv_layers > 0:
+ self.deconv_layers = self._make_deconv_layer(
+ num_deconv_layers,
+ num_deconv_filters,
+ num_deconv_kernels,
+ )
+ elif num_deconv_layers == 0:
+ self.deconv_layers = nn.Identity()
+ else:
+ raise ValueError(
+ f'num_deconv_layers ({num_deconv_layers}) should >= 0.')
+
+ identity_final_layer = False
+ if extra is not None and 'final_conv_kernel' in extra:
+ assert extra['final_conv_kernel'] in [0, 1, 3]
+ if extra['final_conv_kernel'] == 3:
+ padding = 1
+ elif extra['final_conv_kernel'] == 1:
+ padding = 0
+ else:
+ # 0 for Identity mapping.
+ identity_final_layer = True
+ kernel_size = extra['final_conv_kernel']
+ else:
+ kernel_size = 1
+ padding = 0
+
+ if identity_final_layer:
+ self.final_layer = nn.Identity()
+ else:
+ conv_channels = num_deconv_filters[
+ -1] if num_deconv_layers > 0 else self.in_channels
+
+ layers = []
+ if extra is not None:
+ num_conv_layers = extra.get('num_conv_layers', 0)
+ num_conv_kernels = extra.get('num_conv_kernels',
+ [1] * num_conv_layers)
+
+ for i in range(num_conv_layers):
+ layers.append(
+ build_conv_layer(
+ dict(type='Conv2d'),
+ in_channels=conv_channels,
+ out_channels=conv_channels,
+ kernel_size=num_conv_kernels[i],
+ stride=1,
+ padding=(num_conv_kernels[i] - 1) // 2))
+ layers.append(
+ nn.BatchNorm2d(conv_channels)
+ )
+ layers.append(nn.ReLU(inplace=True))
+
+ layers.append(
+ build_conv_layer(
+ cfg=dict(type='Conv2d'),
+ in_channels=conv_channels,
+ out_channels=out_channels,
+ kernel_size=kernel_size,
+ stride=1,
+ padding=padding))
+
+ if len(layers) > 1:
+ self.final_layer = nn.Sequential(*layers)
+ else:
+ self.final_layer = layers[0]
+
+ def get_loss(self, output, target, target_weight):
+ """Calculate top-down keypoint loss.
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+ - heatmaps height: H
+ - heatmaps weight: W
+
+ Args:
+ output (torch.Tensor[N,K,H,W]): Output heatmaps.
+ target (torch.Tensor[N,K,H,W]): Target heatmaps.
+ target_weight (torch.Tensor[N,K,1]):
+ Weights across different joint types.
+ """
+
+ losses = dict()
+
+ assert not isinstance(self.loss, nn.Sequential)
+ assert target.dim() == 4 and target_weight.dim() == 3
+ losses['heatmap_loss'] = self.loss(output, target, target_weight)
+
+ return losses
+
+ def get_accuracy(self, output, target, target_weight):
+ """Calculate accuracy for top-down keypoint loss.
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+ - heatmaps height: H
+ - heatmaps weight: W
+
+ Args:
+ output (torch.Tensor[N,K,H,W]): Output heatmaps.
+ target (torch.Tensor[N,K,H,W]): Target heatmaps.
+ target_weight (torch.Tensor[N,K,1]):
+ Weights across different joint types.
+ """
+
+ accuracy = dict()
+
+ if self.target_type == 'GaussianHeatmap':
+ _, avg_acc, _ = pose_pck_accuracy(
+ output.detach().cpu().numpy(),
+ target.detach().cpu().numpy(),
+ target_weight.detach().cpu().numpy().squeeze(-1) > 0)
+ accuracy['acc_pose'] = float(avg_acc)
+
+ return accuracy
+
+ def forward(self, x):
+ """Forward function."""
+ x = self._transform_inputs(x)
+ x = self.deconv_layers(x)
+ x = self.final_layer(x)
+ return x
+
+ def inference_model(self, x, flip_pairs=None):
+ """Inference function.
+
+ Returns:
+ output_heatmap (np.ndarray): Output heatmaps.
+
+ Args:
+ x (torch.Tensor[N,K,H,W]): Input features.
+ flip_pairs (None | list[tuple]):
+ Pairs of keypoints which are mirrored.
+ """
+ output = self.forward(x)
+
+ if flip_pairs is not None:
+ output_heatmap = flip_back(
+ output.detach().cpu().numpy(),
+ flip_pairs,
+ target_type=self.target_type)
+ # feature is not aligned, shift flipped heatmap for higher accuracy
+ if self.test_cfg.get('shift_heatmap', False):
+ output_heatmap[:, :, :, 1:] = output_heatmap[:, :, :, :-1]
+ else:
+ output_heatmap = output.detach().cpu().numpy()
+ return output_heatmap
+
+ def _init_inputs(self, in_channels, in_index, input_transform):
+ """Check and initialize input transforms.
+
+ The in_channels, in_index and input_transform must match.
+ Specifically, when input_transform is None, only single feature map
+ will be selected. So in_channels and in_index must be of type int.
+ When input_transform is not None, in_channels and in_index must be
+ list or tuple, with the same length.
+
+ Args:
+ in_channels (int|Sequence[int]): Input channels.
+ in_index (int|Sequence[int]): Input feature index.
+ input_transform (str|None): Transformation type of input features.
+ Options: 'resize_concat', 'multiple_select', None.
+
+ - 'resize_concat': Multiple feature maps will be resize to the
+ same size as first one and than concat together.
+ Usually used in FCN head of HRNet.
+ - 'multiple_select': Multiple feature maps will be bundle into
+ a list and passed into decode head.
+ - None: Only one select feature map is allowed.
+ """
+
+ if input_transform is not None:
+ assert input_transform in ['resize_concat', 'multiple_select']
+ self.input_transform = input_transform
+ self.in_index = in_index
+ if input_transform is not None:
+ assert isinstance(in_channels, (list, tuple))
+ assert isinstance(in_index, (list, tuple))
+ assert len(in_channels) == len(in_index)
+ if input_transform == 'resize_concat':
+ self.in_channels = sum(in_channels)
+ else:
+ self.in_channels = in_channels
+ else:
+ assert isinstance(in_channels, int)
+ assert isinstance(in_index, int)
+ self.in_channels = in_channels
+
+ def _transform_inputs(self, inputs):
+ """Transform inputs for decoder.
+
+ Args:
+ inputs (list[Tensor] | Tensor): multi-level img features.
+
+ Returns:
+ Tensor: The transformed inputs
+ """
+ if not isinstance(inputs, list):
+ if not isinstance(inputs, list):
+ if self.upsample > 0:
+ inputs = resize(
+ input=F.relu(inputs),
+ scale_factor=self.upsample,
+ mode='bilinear',
+ align_corners=self.align_corners
+ )
+ return inputs
+
+ if self.input_transform == 'resize_concat':
+ inputs = [inputs[i] for i in self.in_index]
+ upsampled_inputs = [
+ resize(
+ input=x,
+ size=inputs[0].shape[2:],
+ mode='bilinear',
+ align_corners=self.align_corners) for x in inputs
+ ]
+ inputs = torch.cat(upsampled_inputs, dim=1)
+ elif self.input_transform == 'multiple_select':
+ inputs = [inputs[i] for i in self.in_index]
+ else:
+ inputs = inputs[self.in_index]
+
+ return inputs
+
+ def _make_deconv_layer(self, num_layers, num_filters, num_kernels):
+ """Make deconv layers."""
+ if num_layers != len(num_filters):
+ error_msg = f'num_layers({num_layers}) ' \
+ f'!= length of num_filters({len(num_filters)})'
+ raise ValueError(error_msg)
+ if num_layers != len(num_kernels):
+ error_msg = f'num_layers({num_layers}) ' \
+ f'!= length of num_kernels({len(num_kernels)})'
+ raise ValueError(error_msg)
+
+ layers = []
+ for i in range(num_layers):
+ kernel, padding, output_padding = \
+ self._get_deconv_cfg(num_kernels[i])
+
+ planes = num_filters[i]
+ layers.append(
+ build_upsample_layer(
+ dict(type='deconv'),
+ in_channels=self.in_channels,
+ out_channels=planes,
+ kernel_size=kernel,
+ stride=2,
+ padding=padding,
+ output_padding=output_padding,
+ bias=False))
+ layers.append(nn.BatchNorm2d(planes))
+ layers.append(nn.ReLU(inplace=True))
+ self.in_channels = planes
+
+ return nn.Sequential(*layers)
+
+ def init_weights(self):
+ """Initialize model weights."""
+ for _, m in self.deconv_layers.named_modules():
+ if isinstance(m, nn.ConvTranspose2d):
+ normal_init(m, std=0.001)
+ elif isinstance(m, nn.BatchNorm2d):
+ constant_init(m, 1)
+ for m in self.final_layer.modules():
+ if isinstance(m, nn.Conv2d):
+ normal_init(m, std=0.001, bias=0)
+ elif isinstance(m, nn.BatchNorm2d):
+ constant_init(m, 1)
diff --git a/project/models/deprecated_deep_privacy2/dp2/detection/models/vit_pose/vit_pose.py b/project/models/deprecated_deep_privacy2/dp2/detection/models/vit_pose/vit_pose.py
new file mode 100644
index 0000000..50f95f3
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/detection/models/vit_pose/vit_pose.py
@@ -0,0 +1,218 @@
+# Code adapted from: https://github.com/gpastal24/ViTPose-Pytorch
+from .topdown_heatmap_simple_head import TopdownHeatmapSimpleHead
+import torch
+from .backbone import ViT
+import torchvision.transforms.functional as F
+import torch.nn as nn
+import tops
+
+model_large = dict(
+ type="TopDown",
+ pretrained=None,
+ backbone=dict(
+ type="ViT",
+ img_size=(256, 192),
+ patch_size=16,
+ embed_dim=1024,
+ depth=24,
+ num_heads=16,
+ ratio=1,
+ use_checkpoint=False,
+ mlp_ratio=4,
+ qkv_bias=True,
+ drop_path_rate=0.5,
+ ),
+ keypoint_head=dict(
+ type="TopdownHeatmapSimpleHead",
+ in_channels=1024,
+ num_deconv_layers=2,
+ num_deconv_filters=(256, 256),
+ num_deconv_kernels=(4, 4),
+ extra=dict(
+ final_conv_kernel=1,
+ ),
+ out_channels=17,
+ loss_keypoint=dict(type="JointsMSELoss", use_target_weight=True),
+ ),
+ train_cfg=dict(),
+ test_cfg=dict(
+ flip_test=True,
+ post_process="default",
+ shift_heatmap=False,
+ target_type="GaussianHeatmap",
+ modulate_kernel=11,
+ use_udp=True,
+ ),
+)
+
+
+model_base = dict(
+ type="TopDown",
+ pretrained=None,
+ backbone=dict(
+ type="ViT",
+ img_size=(256, 192),
+ patch_size=16,
+ embed_dim=768,
+ depth=12,
+ num_heads=12,
+ ratio=1,
+ use_checkpoint=False,
+ mlp_ratio=4,
+ qkv_bias=True,
+ drop_path_rate=0.3,
+ ),
+ keypoint_head=dict(
+ type="TopdownHeatmapSimpleHead",
+ in_channels=768,
+ num_deconv_layers=2,
+ num_deconv_filters=(256, 256),
+ num_deconv_kernels=(4, 4),
+ extra=dict(
+ final_conv_kernel=1,
+ ),
+ out_channels=17,
+ loss_keypoint=dict(type="JointsMSELoss", use_target_weight=True),
+ ),
+ train_cfg=dict(),
+ test_cfg=dict(),
+)
+model_huge = dict(
+ type='TopDown',
+ pretrained=None,
+ backbone=dict(
+ type='ViT',
+ img_size=(256, 192),
+ patch_size=16,
+ embed_dim=1280,
+ depth=32,
+ num_heads=16,
+ ratio=1,
+ use_checkpoint=False,
+ mlp_ratio=4,
+ qkv_bias=True,
+ drop_path_rate=0.55,
+ ),
+ keypoint_head=dict(
+ type='TopdownHeatmapSimpleHead',
+ in_channels=1280,
+ num_deconv_layers=2,
+ num_deconv_filters=(256, 256),
+ num_deconv_kernels=(4, 4),
+ extra=dict(final_conv_kernel=1, ),
+ out_channels=17,
+ loss_keypoint=dict(type='JointsMSELoss', use_target_weight=True)),
+ train_cfg=dict(),
+ test_cfg=dict(
+ flip_test=True,
+ post_process='default',
+ shift_heatmap=False,
+ target_type="GaussianHeatmap",
+ modulate_kernel=11,
+ use_udp=True))
+
+
+class VitPoseModel(nn.Module):
+ def __init__(self, model_name):
+ super().__init__()
+ assert model_name in ["vit_base", "vit_large", "vit_huge"]
+ model = {
+ "vit_base": model_base,
+ "vit_large": model_large,
+ "vit_huge": model_huge
+ }[model_name]
+ weight_url = {
+ "vit_base": "https://api.loke.aws.unit.no/dlr-gui-backend-resources-content/v2/contents/links/90235a26-3b8c-427d-a264-c68155abecdcfcfcd8a9-0388-4575-b85b-607d3c0a9b149bef8f0f-a0f9-4662-a561-1b47ba5f1636",
+ "vit_large": "https://api.loke.aws.unit.no/dlr-gui-backend-resources-content/v2/contents/links/a580a44c-0afd-43ac-a2cb-9956c32b1d1a78c51ecb-81bb-4345-8710-13904cb9dbbe0703db2d-8534-42e0-ac4d-518ab51fe7db",
+ "vit_huge": "https://api.loke.aws.unit.no/dlr-gui-backend-resources-content/v2/contents/links/a33b6ada-4d2f-4ef7-8f83-b33f58b69f5b2a62e181-2131-467d-a900-027157a08571d761fad4-785b-4b84-8596-8932c7857e44"
+ }[model_name]
+ file_name = {
+ "vit_base": "vit-b-multi-coco-595b5e128b.pth",
+ "vit_large": "vit-l-multi-coco-9475d27cec.pth",
+ "vit_huge": "vit-h-multi-coco-dbc06d4337.pth",
+ }[model_name]
+ # Set check_hash to true if you suspect a download error.
+ weight_path = tops.download_file(
+ weight_url, file_name=file_name, check_hash=False)
+
+ self.keypoint_head = tops.to_cuda(TopdownHeatmapSimpleHead(
+ in_channels=model["keypoint_head"]["in_channels"],
+ out_channels=model["keypoint_head"]["out_channels"],
+ num_deconv_filters=model["keypoint_head"]["num_deconv_filters"],
+ num_deconv_kernels=model["keypoint_head"]["num_deconv_kernels"],
+ num_deconv_layers=model["keypoint_head"]["num_deconv_layers"],
+ extra=model["keypoint_head"]["extra"],
+ ))
+ # print(head)
+ self.backbone = tops.to_cuda(ViT(
+ img_size=model["backbone"]["img_size"],
+ patch_size=model["backbone"]["patch_size"],
+ embed_dim=model["backbone"]["embed_dim"],
+ depth=model["backbone"]["depth"],
+ num_heads=model["backbone"]["num_heads"],
+ ratio=model["backbone"]["ratio"],
+ mlp_ratio=model["backbone"]["mlp_ratio"],
+ qkv_bias=model["backbone"]["qkv_bias"],
+ drop_path_rate=model["backbone"]["drop_path_rate"],
+ ))
+ ckpt = torch.load(weight_path, map_location=tops.get_device())
+ self.load_state_dict(ckpt["state_dict"])
+ self.backbone.eval()
+ self.keypoint_head.eval()
+
+ def forward(self, img: torch.Tensor, boxes_ltrb: torch.Tensor):
+ assert img.ndim == 3
+ assert img.dtype == torch.uint8
+ assert boxes_ltrb.ndim == 2 and boxes_ltrb.shape[1] == 4
+ assert boxes_ltrb.dtype == torch.long
+ boxes_ltrb = boxes_ltrb.clamp(0)
+ padded_boxes = torch.zeros_like(boxes_ltrb)
+ images = torch.zeros((len(boxes_ltrb), 3, 256, 192), device=img.device, dtype=torch.float32)
+
+ for i, (x0, y0, x1, y1) in enumerate(boxes_ltrb):
+ x1 = min(img.shape[-1], x1)
+ y1 = min(img.shape[-2], y1)
+ correction_factor = 256 / 192 * (x1 - x0) / (y1 - y0)
+ if correction_factor > 1:
+ # increase y side
+ center = y0 + (y1 - y0) // 2
+ length = (y1-y0).mul(correction_factor).round().long()
+ y0_new = center - length.div(2).long()
+ y1_new = center + length.div(2).long()
+ image_crop = img[:, y0:y1, x0:x1]
+ # print(y1,y2,x1,x2)
+ pad = ((y0_new-y0).abs(), (y1_new-y1).abs())
+# pad = (int(abs(y0_new-y0))), int(abs(y1_new-y1))
+ image_crop = torch.nn.functional.pad(image_crop, [*(0, 0), *pad])
+ padded_boxes[i] = torch.tensor([x0, y0_new, x1, y1_new])
+ else:
+ center = x0 + (x1 - x0) // 2
+ length = (x1-x0).div(correction_factor).round().long()
+ x0_new = center - length.div(2).long()
+ x1_new = center + length.div(2).long()
+ image_crop = img[:, y0:y1, x0:x1]
+ pad = ((x0_new-x0).abs(), (x1_new-x1).abs())
+ image_crop = torch.nn.functional.pad(image_crop, [*pad, ])
+ padded_boxes[i] = torch.tensor([x0_new, y0, x1_new, y1])
+ image_crop = F.resize(image_crop.float(), (256, 192), antialias=True)
+ image_crop = F.normalize(image_crop, mean=[0.485*255, 0.456*255,
+ 0.406*255], std=[0.229*255, 0.224*255, 0.225*255])
+ images[i] = image_crop
+
+ x = self.backbone(images)
+ out = self.keypoint_head(x)
+ pts = torch.empty((out.shape[0], out.shape[1], 3), dtype=torch.float32, device=img.device)
+ # For each human, for each joint: y, x, confidence
+ b, indices = torch.max(out, dim=2)
+ b, indices = torch.max(b, dim=2)
+
+ c, indicesc = torch.max(out, dim=3)
+ c, indicesc = torch.max(c, dim=2)
+ dim1 = torch.tensor(1./64, device=img.device)
+ dim2 = torch.tensor(1./48, device=img.device)
+ for i in range(0, out.shape[0]):
+ pts[i, :, 0] = indicesc[i, :] * dim1 * (padded_boxes[i][3] - padded_boxes[i][1]) + padded_boxes[i][1]
+ pts[i, :, 1] = indices[i, :] * dim2 * (padded_boxes[i][2] - padded_boxes[i][0]) + padded_boxes[i][0]
+ pts[i, :, 2] = c[i, :]
+ pts = pts[:, :, [1, 0, 2]]
+ return pts
diff --git a/project/models/deprecated_deep_privacy2/dp2/detection/models/vit_pose_maskrcnn.py b/project/models/deprecated_deep_privacy2/dp2/detection/models/vit_pose_maskrcnn.py
new file mode 100644
index 0000000..1bf43d5
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/detection/models/vit_pose_maskrcnn.py
@@ -0,0 +1,73 @@
+import torch
+import lzma
+from pathlib import Path
+from dp2.detection.base import BaseDetector
+from .mask_rcnn import MaskRCNNDetector
+from ..structures import PersonDetection
+from tops import logger
+from .vit_pose.vit_pose import VitPoseModel
+from ..utils import masks_to_boxes
+
+
+def box1_inside_box2(box1: torch.Tensor, box2: torch.Tensor):
+ assert len(box1.shape) == 2
+ assert len(box2.shape) == 2
+ box1_inside = torch.zeros(box1.shape[0], device=box1.device, dtype=torch.bool)
+ # This can be batched
+ for i, box in enumerate(box1):
+ is_outside_lefttop = (box[None, [0, 1]] <= box2[:, [0, 1]]).any(dim=1)
+ is_outside_rightbot = (box[None, [2, 3]] >= box2[:, [2, 3]]).any(dim=1)
+ is_outside = is_outside_lefttop.logical_or(is_outside_rightbot)
+ box1_inside[i] = is_outside.logical_not().any()
+ return box1_inside
+
+
+class MaskRCNNVitPose(BaseDetector):
+
+ def __init__(
+ self,
+ mask_rcnn_cfg,
+ post_process_cfg,
+ score_threshold: float,
+ **kwargs
+ ) -> None:
+ super().__init__(kwargs["cache_directory"])
+ self.mask_rcnn = MaskRCNNDetector(**mask_rcnn_cfg, score_thres=score_threshold)
+ self.vit_pose = VitPoseModel("vit_huge")
+
+ self.post_process_cfg = post_process_cfg
+
+ def __call__(self, *args, **kwargs):
+ return self.forward(*args, **kwargs)
+
+ def load_from_cache(self, cache_path: Path):
+ logger.log(f"Loading detection from cache path: {cache_path}",)
+ with lzma.open(cache_path, "rb") as fp:
+ state_dict = torch.load(fp, map_location="cpu")
+ kwargs = dict(
+ post_process_cfg=self.post_process_cfg,
+ )
+ return [
+ state["cls"].from_state_dict(**kwargs, state_dict=state)
+ for state in state_dict
+ ]
+
+ @torch.no_grad()
+ def forward(self, im: torch.Tensor):
+ maskrcnn_dets = self.mask_rcnn(im)
+
+ maskrcnn_person = {
+ k: v[maskrcnn_dets["is_person"]] for k, v in maskrcnn_dets.items()
+ }
+ boxes = masks_to_boxes(maskrcnn_person["segmentation"])
+ keypoints = self.vit_pose(im, boxes).cpu()
+ keypoints[:, :, -1] = keypoints[:, :, -1] >= 0.3
+ persons_without_cse = PersonDetection(
+ maskrcnn_person["segmentation"], **self.post_process_cfg,
+ orig_imshape_CHW=im.shape,
+ keypoints=keypoints,
+ )
+ persons_without_cse.pre_process()
+
+ all_detections = [persons_without_cse]
+ return all_detections
diff --git a/project/models/deprecated_deep_privacy2/dp2/detection/person_detector.py b/project/models/deprecated_deep_privacy2/dp2/detection/person_detector.py
new file mode 100644
index 0000000..1bbd0df
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/detection/person_detector.py
@@ -0,0 +1,135 @@
+import torch
+import lzma
+from dp2.detection.base import BaseDetector
+from .utils import combine_cse_maskrcnn_dets
+from .models.cse import CSEDetector
+from .models.mask_rcnn import MaskRCNNDetector
+from .models.keypoint_maskrcnn import KeypointMaskRCNN
+from .structures import CSEPersonDetection, PersonDetection
+from pathlib import Path
+
+
+class CSEPersonDetector(BaseDetector):
+ def __init__(
+ self,
+ score_threshold: float,
+ mask_rcnn_cfg: dict,
+ cse_cfg: dict,
+ cse_post_process_cfg: dict,
+ **kwargs
+ ) -> None:
+ super().__init__(**kwargs)
+ self.mask_rcnn = MaskRCNNDetector(**mask_rcnn_cfg, score_thres=score_threshold)
+ self.cse_detector = CSEDetector(**cse_cfg, score_thres=score_threshold)
+ self.post_process_cfg = cse_post_process_cfg
+ self.iou_combine_threshold = self.post_process_cfg.pop("iou_combine_threshold")
+
+ def __call__(self, *args, **kwargs):
+ return self.forward(*args, **kwargs)
+
+ def load_from_cache(self, cache_path: Path):
+ with lzma.open(cache_path, "rb") as fp:
+ state_dict = torch.load(fp)
+ kwargs = dict(
+ post_process_cfg=self.post_process_cfg,
+ embed_map=self.cse_detector.embed_map,
+ )
+ return [
+ state["cls"].from_state_dict(**kwargs, state_dict=state)
+ for state in state_dict
+ ]
+
+ @torch.no_grad()
+ def forward(self, im: torch.Tensor, cse_dets=None):
+ mask_dets = self.mask_rcnn(im)
+ if cse_dets is None:
+ cse_dets = self.cse_detector(im)
+ segmentation = mask_dets["segmentation"]
+ segmentation, cse_dets, _ = combine_cse_maskrcnn_dets(
+ segmentation, cse_dets, self.iou_combine_threshold
+ )
+ det = CSEPersonDetection(
+ segmentation=segmentation,
+ cse_dets=cse_dets,
+ embed_map=self.cse_detector.embed_map,
+ orig_imshape_CHW=im.shape,
+ **self.post_process_cfg
+ )
+ return [det]
+
+
+class MaskRCNNPersonDetector(BaseDetector):
+ def __init__(
+ self,
+ score_threshold: float,
+ mask_rcnn_cfg: dict,
+ cse_post_process_cfg: dict,
+ **kwargs
+ ) -> None:
+ super().__init__(**kwargs)
+ self.mask_rcnn = MaskRCNNDetector(**mask_rcnn_cfg, score_thres=score_threshold)
+ self.post_process_cfg = cse_post_process_cfg
+
+ def __call__(self, *args, **kwargs):
+ return self.forward(*args, **kwargs)
+
+ def load_from_cache(self, cache_path: Path):
+ with lzma.open(cache_path, "rb") as fp:
+ state_dict = torch.load(fp)
+ kwargs = dict(
+ post_process_cfg=self.post_process_cfg,
+ )
+ return [
+ state["cls"].from_state_dict(**kwargs, state_dict=state)
+ for state in state_dict
+ ]
+
+ @torch.no_grad()
+ def forward(self, im: torch.Tensor):
+ mask_dets = self.mask_rcnn(im)
+ segmentation = mask_dets["segmentation"]
+ det = PersonDetection(
+ segmentation, **self.post_process_cfg, orig_imshape_CHW=im.shape
+ )
+ return [det]
+
+
+class KeypointMaskRCNNPersonDetector(BaseDetector):
+ def __init__(
+ self,
+ score_threshold: float,
+ mask_rcnn_cfg: dict,
+ cse_post_process_cfg: dict,
+ **kwargs
+ ) -> None:
+ super().__init__(**kwargs)
+ self.mask_rcnn = KeypointMaskRCNN(
+ **mask_rcnn_cfg, score_threshold=score_threshold
+ )
+ self.post_process_cfg = cse_post_process_cfg
+
+ def __call__(self, *args, **kwargs):
+ return self.forward(*args, **kwargs)
+
+ def load_from_cache(self, cache_path: Path):
+ with lzma.open(cache_path, "rb") as fp:
+ state_dict = torch.load(fp)
+ kwargs = dict(
+ post_process_cfg=self.post_process_cfg,
+ )
+ return [
+ state["cls"].from_state_dict(**kwargs, state_dict=state)
+ for state in state_dict
+ ]
+
+ @torch.no_grad()
+ def forward(self, im: torch.Tensor):
+ mask_dets = self.mask_rcnn(im)
+ segmentation = mask_dets["segmentation"]
+ det = PersonDetection(
+ segmentation,
+ **self.post_process_cfg,
+ orig_imshape_CHW=im.shape,
+ keypoints=mask_dets["keypoints"]
+ )
+ return [det]
diff --git a/project/models/deprecated_deep_privacy2/dp2/detection/structures.py b/project/models/deprecated_deep_privacy2/dp2/detection/structures.py
new file mode 100644
index 0000000..5a973d6
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/detection/structures.py
@@ -0,0 +1,518 @@
+import torch
+import numpy as np
+from dp2 import utils
+from dp2.utils import vis_utils, crop_box
+from .utils import (
+ cut_pad_resize, masks_to_boxes,
+ get_kernel, transform_embedding, initialize_cse_boxes
+)
+from .box_utils import get_expanded_bbox, include_box
+import torchvision
+import tops
+from .box_utils_fdf import expand_bbox as expand_bbox_fdf
+from dp2.data.transforms.transforms import InsertJointMap
+
+
+class VehicleDetection:
+
+ def __init__(self, segmentation: torch.BoolTensor) -> None:
+ self.segmentation = segmentation
+ self.boxes = masks_to_boxes(segmentation)
+ assert self.boxes.shape[1] == 4, self.boxes.shape
+ self.n_detections = self.segmentation.shape[0]
+ area = (self.boxes[:, 3] - self.boxes[:, 1]) * (self.boxes[:, 2] - self.boxes[:, 0])
+
+ sorted_idx = torch.argsort(area, descending=True)
+ self.segmentation = self.segmentation[sorted_idx]
+ self.boxes = self.boxes[sorted_idx].cpu()
+
+ def pre_process(self):
+ pass
+
+ def get_crop(self, idx: int, im):
+ assert idx < len(self)
+ box = self.boxes[idx]
+ im = crop_box(self.im, box)
+ mask = crop_box(self.segmentation[idx])
+ mask = mask == 0
+ return dict(img=im, mask=mask.float(), boxes=box)
+
+ def visualize(self, im):
+ if len(self) == 0:
+ return im
+ im = vis_utils.draw_mask(im.clone(), self.segmentation.logical_not())
+ return im
+
+ def __len__(self):
+ return self.n_detections
+
+ @staticmethod
+ def from_state_dict(state_dict, **kwargs):
+ numel = np.prod(state_dict["shape"])
+ arr = np.unpackbits(state_dict["segmentation"].numpy(), count=numel)
+ segmentation = tops.to_cuda(torch.from_numpy(arr)).view(state_dict["shape"])
+ return VehicleDetection(segmentation)
+
+ def state_dict(self, **kwargs):
+ segmentation = torch.from_numpy(np.packbits(self.segmentation.bool().cpu().numpy()))
+ return dict(segmentation=segmentation, cls=self.__class__, shape=self.segmentation.shape)
+
+
+class FaceDetection:
+
+ def __init__(self,
+ boxes_ltrb: torch.LongTensor, target_imsize, fdf128_expand: bool,
+ keypoints: torch.Tensor = None,
+ **kwargs) -> None:
+
+ self.boxes = boxes_ltrb.cpu()
+ assert self.boxes.shape[1] == 4, self.boxes.shape
+ self.target_imsize = tuple(target_imsize)
+ # Sory by area to paste in largest faces last
+ area = (self.boxes[:, 2] - self.boxes[:, 0]) * (self.boxes[:, 3] - self.boxes[:, 1]).view(-1)
+ idx = area.argsort(descending=False)
+ self.boxes = self.boxes[idx]
+ self.fdf128_expand = fdf128_expand
+ self.orig_keypoints = keypoints
+ if keypoints is not None:
+ self.orig_keypoints = self.orig_keypoints[idx]
+ assert keypoints.shape == (len(boxes_ltrb), 17, 2) or \
+ keypoints.shape == (len(boxes_ltrb), 7, 2), keypoints.shape
+
+ def visualize(self, im):
+ if len(self) == 0:
+ return im
+ orig_device = im.device
+ for box in self.boxes:
+ simple_expand = False if self.fdf128_expand else True
+ e_box = torch.from_numpy(expand_bbox_fdf(box.numpy(), im.shape[-2:], simple_expand))
+ im = torchvision.utils.draw_bounding_boxes(im.cpu(), e_box[None], colors=(0, 0, 255), width=2)
+ im = torchvision.utils.draw_bounding_boxes(im.cpu(), self.boxes, colors=(255, 0, 0), width=2)
+ if self.orig_keypoints is not None:
+ _, _, connectivity = vis_utils.get_coco_keypoints()
+ connectivity = connectivity[:5]
+ im = vis_utils.draw_keypoints(im, self.orig_keypoints, radius=1, connectivity=connectivity, width=3)
+
+ return im.to(device=orig_device)
+
+ def get_crop(self, idx: int, im):
+ assert idx < len(self)
+ box = self.boxes[idx].numpy()
+ simple_expand = False if self.fdf128_expand else True
+ expanded_boxes = expand_bbox_fdf(box, im.shape[-2:], simple_expand)
+ im = cut_pad_resize(im, expanded_boxes, self.target_imsize, fdf_resize=True)
+
+ # Find the square mask corresponding to box.
+ box_mask = box.copy().astype(float)
+ box_mask[[0, 2]] -= expanded_boxes[0]
+ box_mask[[1, 3]] -= expanded_boxes[1]
+
+ width = expanded_boxes[2] - expanded_boxes[0]
+ resize_factor = self.target_imsize[0] / width
+ box_mask = (box_mask * resize_factor).astype(int)
+ mask = torch.ones((1, *self.target_imsize), device=im.device, dtype=torch.float32)
+ crop_box(mask, box_mask).fill_(0)
+ if self.orig_keypoints is None:
+ return dict(
+ img=im[None], mask=mask[None],
+ boxes=torch.from_numpy(expanded_boxes).view(1, -1))
+
+ keypoint = self.orig_keypoints[idx, :7, :2].clone()
+ keypoint[:, 0] -= expanded_boxes[0]
+ keypoint[:, 1] -= expanded_boxes[1]
+ w = expanded_boxes[2] - expanded_boxes[0]
+ keypoint /= w
+ keypoint = keypoint.clamp(0, 1)
+ keypoint = torch.cat((keypoint, torch.ones(
+ keypoint.shape[0], 1, device=keypoint.device, dtype=keypoint.dtype)), dim=-1)
+ return dict(
+ img=im[None], mask=mask[None],
+ boxes=torch.from_numpy(expanded_boxes).view(1, -1),
+ keypoints=keypoint[None])
+
+ def __len__(self):
+ return len(self.boxes)
+
+ @staticmethod
+ def from_state_dict(state_dict, **kwargs):
+ return FaceDetection(
+ state_dict["boxes"].cpu(),
+ keypoints=state_dict["orig_keypoints"] if "orig_keypoints" in state_dict else None,
+ **kwargs)
+
+ def state_dict(self, **kwargs):
+ return dict(
+ boxes=self.boxes,
+ cls=self.__class__,
+ orig_keypoints=self.orig_keypoints)
+
+ def pre_process(self):
+ pass
+
+
+def remove_dilate_in_pad(mask: torch.Tensor, exp_box, orig_imshape):
+ """
+ Dilation happens after padding, which could place dilation in the padded area.
+ Remove this.
+ """
+ x0, y0, x1, y1 = exp_box
+ H, W = orig_imshape
+ # Padding in original image space
+ p_y0 = max(0, -y0)
+ p_y1 = max(y1 - H, 0)
+ p_x0 = max(0, -x0)
+ p_x1 = max(x1 - W, 0)
+ resize_ratio = mask.shape[-2] / (y1 - y0)
+ p_x0, p_y0, p_x1, p_y1 = [(_ * resize_ratio).floor().long() for _ in [p_x0, p_y0, p_x1, p_y1]]
+ mask[..., :p_y0, :] = 0
+ mask[..., :p_x0] = 0
+ mask[..., mask.shape[-2] - p_y1:, :] = 0
+ mask[..., mask.shape[-1] - p_x1:] = 0
+
+
+class CSEPersonDetection:
+
+ def __init__(self,
+ segmentation, cse_dets,
+ target_imsize,
+ exp_bbox_cfg, exp_bbox_filter,
+ dilation_percentage: float,
+ embed_map: torch.Tensor,
+ orig_imshape_CHW,
+ normalize_embedding: bool) -> None:
+ self.segmentation = segmentation
+ self.cse_dets = cse_dets
+ self.target_imsize = list(target_imsize)
+ self.pre_processed = False
+ self.exp_bbox_cfg = exp_bbox_cfg
+ self.exp_bbox_filter = exp_bbox_filter
+ self.dilation_percentage = dilation_percentage
+ self.embed_map = embed_map
+ self.embed_map_cpu = embed_map.cpu()
+ self.normalize_embedding = normalize_embedding
+ if self.normalize_embedding:
+ embed_map_mean = self.embed_map.mean(dim=0, keepdim=True)
+ embed_map_rstd = ((self.embed_map - embed_map_mean).square().mean(dim=0, keepdim=True) + 1e-8).rsqrt()
+ self.embed_map_normalized = (self.embed_map - embed_map_mean) * embed_map_rstd
+ self.orig_imshape_CHW = orig_imshape_CHW
+
+ @torch.no_grad()
+ def pre_process(self):
+ if self.pre_processed:
+ return
+ boxes = initialize_cse_boxes(self.segmentation, self.cse_dets["bbox_XYXY"]).cpu()
+ expanded_boxes = []
+ included_boxes = []
+ for i in range(len(boxes)):
+ exp_box = get_expanded_bbox(
+ boxes[i], self.orig_imshape_CHW[1:], self.segmentation[i], **self.exp_bbox_cfg,
+ target_aspect_ratio=self.target_imsize[0] / self.target_imsize[1])
+ if not include_box(exp_box, imshape=self.orig_imshape_CHW[1:], **self.exp_bbox_filter):
+ continue
+ included_boxes.append(i)
+ expanded_boxes.append(exp_box)
+ expanded_boxes = torch.LongTensor(expanded_boxes).view(-1, 4)
+ self.segmentation = self.segmentation[included_boxes]
+ self.cse_dets = {k: v[included_boxes] for k, v in self.cse_dets.items()}
+
+ self.mask = torch.empty((len(expanded_boxes), *self.target_imsize), device=tops.get_device(), dtype=torch.bool)
+ area = self.segmentation.sum(dim=[1, 2]).view(len(expanded_boxes))
+ for i, box in enumerate(expanded_boxes):
+ self.mask[i] = cut_pad_resize(self.segmentation[i:i + 1], box, self.target_imsize)[0]
+
+ dilation_kernel = get_kernel(
+ int((self.target_imsize[0] * self.target_imsize[1])**0.5 * self.dilation_percentage))
+ self.maskrcnn_mask = self.mask.clone().logical_not()[:, None]
+ self.mask = utils.binary_dilation(self.mask[:, None], dilation_kernel)
+ for i in range(len(expanded_boxes)):
+ remove_dilate_in_pad(self.mask[i], expanded_boxes[i], self.orig_imshape_CHW[1:])
+ self.boxes = expanded_boxes.cpu()
+ self.dilated_boxes = get_dilated_boxes(self.boxes, self.mask)
+
+ self.pre_processed = True
+ self.n_detections = len(self.boxes)
+ self.mask = self.mask.logical_not()
+
+ E_mask = torch.zeros((self.n_detections, 1, *self.target_imsize), device=self.mask.device, dtype=torch.bool)
+ self.vertices = torch.zeros_like(E_mask, dtype=torch.long)
+ for i in range(self.n_detections):
+ E_, E_mask[i] = transform_embedding(
+ self.cse_dets["instance_embedding"][i],
+ self.cse_dets["instance_segmentation"][i],
+ self.boxes[i],
+ self.cse_dets["bbox_XYXY"][i].cpu(),
+ self.target_imsize
+ )
+ self.vertices[i] = utils.from_E_to_vertex(
+ E_[None], E_mask[i:i + 1].logical_not(), self.embed_map).squeeze()[None]
+ self.E_mask = E_mask
+
+ sorted_idx = torch.argsort(area, descending=False)
+ self.mask = self.mask[sorted_idx]
+ self.boxes = self.boxes[sorted_idx.cpu()]
+ self.vertices = self.vertices[sorted_idx]
+ self.E_mask = self.E_mask[sorted_idx]
+ self.maskrcnn_mask = self.maskrcnn_mask[sorted_idx]
+
+ def get_crop(self, idx: int, im):
+ self.pre_process()
+ assert idx < len(self)
+ box = self.boxes[idx]
+ mask = self.mask[idx]
+ im = cut_pad_resize(im, box, self.target_imsize).unsqueeze(0)
+
+ vertices_ = self.vertices[idx]
+ E_mask_ = self.E_mask[idx].float()
+ if self.normalize_embedding:
+ embedding = self.embed_map_normalized[vertices_.squeeze(dim=0)].permute(2, 0, 1) * E_mask_
+ else:
+ embedding = self.embed_map[vertices_.squeeze(dim=0)].permute(2, 0, 1) * E_mask_
+
+ return dict(
+ img=im,
+ mask=mask.float()[None],
+ boxes=box.reshape(1, -1),
+ E_mask=E_mask_[None],
+ vertices=vertices_[None],
+ embed_map=self.embed_map,
+ embedding=embedding[None],
+ maskrcnn_mask=self.maskrcnn_mask[idx].float()[None]
+ )
+
+ def __len__(self):
+ self.pre_process()
+ return self.n_detections
+
+ def state_dict(self, after_preprocess=False):
+ """
+ The processed annotations occupy more space than the original detections.
+ """
+ if not after_preprocess:
+ return {
+ "combined_segmentation": self.segmentation.bool(),
+ "cse_instance_segmentation": self.cse_dets["instance_segmentation"].bool(),
+ "cse_instance_embedding": self.cse_dets["instance_embedding"],
+ "cse_bbox_XYXY": self.cse_dets["bbox_XYXY"].long(),
+ "cls": self.__class__,
+ "orig_imshape_CHW": self.orig_imshape_CHW
+ }
+ self.pre_process()
+ def compress_bool(x): return torch.from_numpy(np.packbits(x.bool().cpu().numpy()))
+ return dict(
+ E_mask=compress_bool(self.E_mask),
+ mask=compress_bool(self.mask),
+ maskrcnn_mask=compress_bool(self.maskrcnn_mask),
+ vertices=self.vertices.to(torch.int16).cpu(),
+ cls=self.__class__,
+ boxes=self.boxes,
+ orig_imshape_CHW=self.orig_imshape_CHW,
+ )
+
+ @staticmethod
+ def from_state_dict(
+ state_dict, embed_map,
+ post_process_cfg, **kwargs):
+ after_preprocess = "segmentation" not in state_dict and "combined_segmentation" not in state_dict
+ if after_preprocess:
+ detection = CSEPersonDetection(
+ segmentation=None, cse_dets=None, embed_map=embed_map,
+ orig_imshape_CHW=state_dict["orig_imshape_CHW"],
+ **post_process_cfg)
+ detection.vertices = tops.to_cuda(state_dict["vertices"].long())
+ numel = np.prod(detection.vertices.shape)
+
+ def unpack_bool(x):
+ x = torch.from_numpy(np.unpackbits(x.numpy(), count=numel))
+ return x.view(*detection.vertices.shape)
+ detection.E_mask = tops.to_cuda(unpack_bool(state_dict["E_mask"]))
+ detection.mask = tops.to_cuda(unpack_bool(state_dict["mask"]))
+ detection.maskrcnn_mask = tops.to_cuda(unpack_bool(state_dict["maskrcnn_mask"]))
+ detection.n_detections = len(detection.mask)
+ detection.pre_processed = True
+
+ if isinstance(state_dict["boxes"], np.ndarray):
+ state_dict["boxes"] = torch.from_numpy(state_dict["boxes"])
+ detection.boxes = state_dict["boxes"]
+ return detection
+
+ cse_dets = dict(
+ instance_segmentation=state_dict["cse_instance_segmentation"],
+ instance_embedding=state_dict["cse_instance_embedding"],
+ embed_map=embed_map,
+ bbox_XYXY=state_dict["cse_bbox_XYXY"])
+ cse_dets = {k: tops.to_cuda(v) for k, v in cse_dets.items()}
+
+ segmentation = state_dict["combined_segmentation"]
+ return CSEPersonDetection(
+ segmentation, cse_dets, embed_map=embed_map,
+ orig_imshape_CHW=state_dict["orig_imshape_CHW"],
+ **post_process_cfg)
+
+ def visualize(self, im):
+ self.pre_process()
+ if len(self) == 0:
+ return im
+ im = vis_utils.draw_cropped_masks(
+ im.cpu(), self.mask.cpu(), self.boxes, visualize_instances=False)
+ E = self.embed_map_cpu[self.vertices.long().cpu()].squeeze(1).permute(0, 3, 1, 2)
+ im = vis_utils.draw_cse_all(
+ E, self.E_mask.squeeze(1).bool().cpu(), im,
+ self.boxes, self.embed_map_cpu)
+ im = torchvision.utils.draw_bounding_boxes(im, self.boxes, colors=(255, 0, 0), width=2)
+ return im
+
+
+def shift_and_preprocess_keypoints(keypoints: torch.Tensor, boxes):
+ keypoints = keypoints.clone()
+ N = boxes.shape[0]
+ tops.assert_shape(keypoints, (N, None, 3))
+ tops.assert_shape(boxes, (N, 4))
+ x0, y0, x1, y1 = [_.view(-1, 1) for _ in boxes.T]
+
+ w = x1 - x0
+ h = y1 - y0
+ keypoints[:, :, 0] = (keypoints[:, :, 0] - x0) / w
+ keypoints[:, :, 1] = (keypoints[:, :, 1] - y0) / h
+ def check_outside(x): return (x < 0).logical_or(x > 1)
+ is_outside = check_outside(keypoints[:, :, 0]).logical_or(check_outside(keypoints[:, :, 1]))
+ keypoints[:, :, 2] = keypoints[:, :, 2] > 0
+ keypoints[:, :, 2] = (keypoints[:, :, 2] > 0).logical_and(is_outside.logical_not())
+ return keypoints
+
+
+class PersonDetection:
+
+ def __init__(
+ self,
+ segmentation,
+ target_imsize,
+ exp_bbox_cfg, exp_bbox_filter,
+ dilation_percentage: float,
+ orig_imshape_CHW,
+ kp_vis_thr=None,
+ keypoints=None,
+ insert_joint_map=False,
+ **kwargs) -> None:
+ self.segmentation = segmentation
+ self.target_imsize = list(target_imsize)
+ self.pre_processed = False
+ self.exp_bbox_cfg = exp_bbox_cfg
+ self.exp_bbox_filter = exp_bbox_filter
+ self.dilation_percentage = dilation_percentage
+ self.orig_imshape_CHW = orig_imshape_CHW
+ self.orig_keypoints = keypoints
+ if keypoints is not None:
+ assert kp_vis_thr is not None
+ self.kp_vis_thr = kp_vis_thr
+ if insert_joint_map:
+ self.joint_map_transform = InsertJointMap(target_imsize)
+
+
+ @torch.no_grad()
+ def pre_process(self):
+ if self.pre_processed:
+ return
+ boxes = masks_to_boxes(self.segmentation).cpu()
+ expanded_boxes = []
+ included_boxes = []
+ for i in range(len(boxes)):
+ exp_box = get_expanded_bbox(
+ boxes[i], self.orig_imshape_CHW[1:], self.segmentation[i], **self.exp_bbox_cfg,
+ target_aspect_ratio=self.target_imsize[0] / self.target_imsize[1])
+ if not include_box(exp_box, imshape=self.orig_imshape_CHW[1:], **self.exp_bbox_filter):
+ continue
+ included_boxes.append(i)
+ expanded_boxes.append(exp_box)
+ expanded_boxes = torch.LongTensor(expanded_boxes).view(-1, 4)
+ self.segmentation = self.segmentation[included_boxes]
+ if self.orig_keypoints is not None:
+ self.keypoints = self.orig_keypoints[included_boxes].clone()
+ self.keypoints[:, :, 2] = self.keypoints[:, :, 2] >= self.kp_vis_thr
+ area = self.segmentation.sum(dim=[1, 2]).view(len(expanded_boxes)).cpu()
+ self.mask = torch.empty((len(expanded_boxes), *self.target_imsize), device=tops.get_device(), dtype=torch.bool)
+ for i, box in enumerate(expanded_boxes):
+ self.mask[i] = cut_pad_resize(self.segmentation[i:i + 1], box, self.target_imsize)[0]
+ if self.orig_keypoints is not None:
+ self.keypoints = shift_and_preprocess_keypoints(self.keypoints, expanded_boxes)
+ dilation_kernel = get_kernel(
+ int((self.target_imsize[0] * self.target_imsize[1])**0.5 * self.dilation_percentage))
+ self.maskrcnn_mask = self.mask.clone().logical_not()[:, None]
+ self.mask = utils.binary_dilation(self.mask[:, None], dilation_kernel)
+ for i in range(len(expanded_boxes)):
+ remove_dilate_in_pad(self.mask[i], expanded_boxes[i], self.orig_imshape_CHW[1:])
+ self.boxes = expanded_boxes
+ self.dilated_boxes = get_dilated_boxes(self.boxes, self.mask)
+
+ self.pre_processed = True
+ self.n_detections = len(self.boxes)
+ self.mask = self.mask.logical_not()
+
+ sorted_idx = torch.argsort(area, descending=False)
+ self.mask = self.mask[sorted_idx]
+ self.boxes = self.boxes[sorted_idx.cpu()]
+ self.segmentation = self.segmentation[sorted_idx]
+ self.maskrcnn_mask = self.maskrcnn_mask[sorted_idx]
+ if self.orig_keypoints is not None:
+ self.keypoints = self.keypoints[sorted_idx.cpu()]
+
+ def get_crop(self, idx: int, im: torch.Tensor):
+ assert idx < len(self)
+ self.pre_process()
+ box = self.boxes[idx]
+ mask = self.mask[idx][None].float()
+ im = cut_pad_resize(im, box, self.target_imsize).unsqueeze(0)
+ batch = dict(
+ img=im, mask=mask, boxes=box.reshape(1, -1),
+ maskrcnn_mask=self.maskrcnn_mask[idx][None].float())
+ if self.orig_keypoints is not None:
+ batch["keypoints"] = self.keypoints[idx:idx + 1]
+ if hasattr(self, "joint_map_transform"):
+ batch = self.joint_map_transform(batch)
+ return batch
+
+ def __len__(self):
+ self.pre_process()
+ return self.n_detections
+
+ def state_dict(self, **kwargs):
+ return dict(
+ segmentation=self.segmentation.bool(),
+ cls=self.__class__,
+ orig_imshape_CHW=self.orig_imshape_CHW,
+ keypoints=self.orig_keypoints
+ )
+
+ @staticmethod
+ def from_state_dict(
+ state_dict,
+ post_process_cfg, **kwargs):
+ return PersonDetection(
+ state_dict["segmentation"],
+ orig_imshape_CHW=state_dict["orig_imshape_CHW"],
+ **post_process_cfg,
+ keypoints=state_dict["keypoints"])
+
+ def visualize(self, im):
+ self.pre_process()
+ im = im.cpu()
+ if len(self) == 0:
+ return im
+ im = vis_utils.draw_cropped_masks(im.clone(), self.mask.cpu(), self.boxes, visualize_instances=False)
+ if self.orig_keypoints is not None:
+ im = vis_utils.draw_cropped_keypoints(im, self.keypoints, self.boxes)
+ im = torchvision.utils.draw_bounding_boxes(im, self.boxes, colors=(255, 0, 0), width=2)
+ return im
+
+
+def get_dilated_boxes(exp_bbox: torch.LongTensor, mask):
+ """
+ mask: resized mask
+ """
+ assert exp_bbox.shape[0] == mask.shape[0]
+ boxes = masks_to_boxes(mask.squeeze(1)).cpu()
+ H, W = exp_bbox[:, 3] - exp_bbox[:, 1], exp_bbox[:, 2] - exp_bbox[:, 0]
+ boxes[:, [0, 2]] = (boxes[:, [0, 2]] * W[:, None] / mask.shape[-1]).long()
+ boxes[:, [1, 3]] = (boxes[:, [1, 3]] * H[:, None] / mask.shape[-2]).long()
+ boxes[:, [0, 2]] += exp_bbox[:, 0:1]
+ boxes[:, [1, 3]] += exp_bbox[:, 1:2]
+ return boxes
diff --git a/project/models/deprecated_deep_privacy2/dp2/detection/utils.py b/project/models/deprecated_deep_privacy2/dp2/detection/utils.py
new file mode 100644
index 0000000..31bd8cc
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/detection/utils.py
@@ -0,0 +1,179 @@
+import cv2
+import numpy as np
+import torch
+import tops
+from skimage.morphology import disk
+from torchvision.transforms.functional import resize, InterpolationMode
+from functools import lru_cache
+
+
+@lru_cache(maxsize=200)
+def get_kernel(n: int):
+ kernel = disk(n, dtype=bool)
+ return tops.to_cuda(torch.from_numpy(kernel).bool())
+
+
+def transform_embedding(E: torch.Tensor, S: torch.Tensor, exp_bbox, E_bbox, target_imshape):
+ """
+ Transforms the detected embedding/mask directly to the target image shape
+ """
+
+ C, HE, WE = E.shape
+ assert E_bbox[0] >= exp_bbox[0], (E_bbox, exp_bbox)
+ assert E_bbox[2] >= exp_bbox[0]
+ assert E_bbox[1] >= exp_bbox[1]
+ assert E_bbox[3] >= exp_bbox[1]
+ assert E_bbox[2] <= exp_bbox[2]
+ assert E_bbox[3] <= exp_bbox[3]
+
+ x0 = int(np.round((E_bbox[0] - exp_bbox[0]) / (exp_bbox[2] - exp_bbox[0]) * target_imshape[1]))
+ x1 = int(np.round((E_bbox[2] - exp_bbox[0]) / (exp_bbox[2] - exp_bbox[0]) * target_imshape[1]))
+ y0 = int(np.round((E_bbox[1] - exp_bbox[1]) / (exp_bbox[3] - exp_bbox[1]) * target_imshape[0]))
+ y1 = int(np.round((E_bbox[3] - exp_bbox[1]) / (exp_bbox[3] - exp_bbox[1]) * target_imshape[0]))
+ new_E = torch.zeros((C, *target_imshape), device=E.device, dtype=torch.float32)
+ new_S = torch.zeros((target_imshape), device=S.device, dtype=torch.bool)
+
+ E = resize(E, (y1-y0, x1-x0), antialias=True, interpolation=InterpolationMode.BILINEAR)
+ new_E[:, y0:y1, x0:x1] = E
+ S = resize(S[None].float(), (y1-y0, x1-x0), antialias=True, interpolation=InterpolationMode.BILINEAR)[0] > 0
+ new_S[y0:y1, x0:x1] = S
+ return new_E, new_S
+
+
+def pairwise_mask_iou(mask1: torch.Tensor, mask2: torch.Tensor):
+ """
+ mask: shape [N, H, W]
+ """
+ assert len(mask1.shape) == 3
+ assert len(mask2.shape) == 3
+ assert mask1.device == mask2.device, (mask1.device, mask2.device)
+ assert mask2.dtype == mask2.dtype
+ assert mask1.dtype == torch.bool
+ assert mask1.shape[1:] == mask2.shape[1:]
+ N1, H1, W1 = mask1.shape
+ N2, H2, W2 = mask2.shape
+ iou = torch.zeros((N1, N2), dtype=torch.float32)
+ for i in range(N1):
+ cur = mask1[i:i+1]
+ inter = torch.logical_and(cur, mask2).flatten(start_dim=1).float().sum(dim=1).cpu()
+ union = torch.logical_or(cur, mask2).flatten(start_dim=1).float().sum(dim=1).cpu()
+ iou[i] = inter / union
+ return iou
+
+
+def find_best_matches(mask1: torch.Tensor, mask2: torch.Tensor, iou_threshold: float):
+ N1 = mask1.shape[0]
+ N2 = mask2.shape[0]
+ ious = pairwise_mask_iou(mask1, mask2).cpu().numpy()
+ indices = np.array([idx for idx, iou in np.ndenumerate(ious)])
+ ious = ious.flatten()
+ mask = ious >= iou_threshold
+ ious = ious[mask]
+ indices = indices[mask]
+
+ # do not sort by iou to keep ordering of mask rcnn / cse sorting.
+ taken1 = np.zeros((N1), dtype=bool)
+ taken2 = np.zeros((N2), dtype=bool)
+ matches = []
+ for i, j in indices:
+ if taken1[i].any() or taken2[j].any():
+ continue
+ matches.append((i, j))
+ taken1[i] = True
+ taken2[j] = True
+ return matches
+
+
+def combine_cse_maskrcnn_dets(segmentation: torch.Tensor, cse_dets: dict, iou_threshold: float):
+ assert 0 < iou_threshold <= 1
+ matches = find_best_matches(segmentation, cse_dets["im_segmentation"], iou_threshold)
+ H, W = segmentation.shape[1:]
+ new_seg = torch.zeros((len(matches), H, W), dtype=torch.bool, device=segmentation.device)
+ cse_im_seg = cse_dets["im_segmentation"]
+ for idx, (i, j) in enumerate(matches):
+ new_seg[idx] = torch.logical_or(segmentation[i], cse_im_seg[j])
+ cse_dets = dict(
+ instance_segmentation=cse_dets["instance_segmentation"][[j for (i, j) in matches]],
+ instance_embedding=cse_dets["instance_embedding"][[j for (i, j) in matches]],
+ bbox_XYXY=cse_dets["bbox_XYXY"][[j for (i, j) in matches]],
+ scores=cse_dets["scores"][[j for (i, j) in matches]],
+ )
+ return new_seg, cse_dets, np.array(matches).reshape(-1, 2)
+
+
+def initialize_cse_boxes(segmentation: torch.Tensor, cse_boxes: torch.Tensor):
+ """
+ cse_boxes can be outside of segmentation.
+ """
+ boxes = masks_to_boxes(segmentation)
+
+ assert boxes.shape == cse_boxes.shape, (boxes.shape, cse_boxes.shape)
+ combined = torch.stack((boxes, cse_boxes), dim=-1)
+ boxes = torch.cat((
+ combined[:, :2].min(dim=2).values,
+ combined[:, 2:].max(dim=2).values,
+ ), dim=1)
+ return boxes
+
+
+def cut_pad_resize(x: torch.Tensor, bbox, target_shape, fdf_resize=False):
+ """
+ Crops or pads x to fit in the bbox and resize to target shape.
+ """
+ C, H, W = x.shape
+ x0, y0, x1, y1 = bbox
+
+ if y0 > 0 and x0 > 0 and x1 <= W and y1 <= H:
+ new_x = x[:, y0:y1, x0:x1]
+ else:
+ new_x = torch.zeros(((C, y1-y0, x1-x0)), dtype=x.dtype, device=x.device)
+ y0_t = max(0, -y0)
+ y1_t = min(y1-y0, (y1-y0)-(y1-H))
+ x0_t = max(0, -x0)
+ x1_t = min(x1-x0, (x1-x0)-(x1-W))
+ x0 = max(0, x0)
+ y0 = max(0, y0)
+ x1 = min(x1, W)
+ y1 = min(y1, H)
+ new_x[:, y0_t:y1_t, x0_t:x1_t] = x[:, y0:y1, x0:x1]
+ # Nearest upsampling often generates more sharp synthesized identities.
+ interp = InterpolationMode.BICUBIC
+ if (y1-y0) < target_shape[0] and (x1-x0) < target_shape[1]:
+ interp = InterpolationMode.NEAREST
+ antialias = interp == InterpolationMode.BICUBIC
+ if x1 - x0 == target_shape[1] and y1 - y0 == target_shape[0]:
+ return new_x
+ if x.dtype == torch.bool:
+ new_x = resize(new_x.float(), target_shape, interpolation=InterpolationMode.NEAREST) > 0.5
+ elif x.dtype == torch.float32:
+ new_x = resize(new_x, target_shape, interpolation=interp, antialias=antialias)
+ elif x.dtype == torch.uint8:
+ if fdf_resize: # FDF dataset is created with cv2 INTER_AREA.
+ # Incorrect resizing generates noticeable poorer inpaintings.
+ upsampling = ((y1-y0) * (x1-x0)) < (target_shape[0] * target_shape[1])
+ if upsampling:
+ new_x = resize(new_x.float(), target_shape, interpolation=InterpolationMode.BICUBIC,
+ antialias=True).round().clamp(0, 255).byte()
+ else:
+ device = new_x.device
+ new_x = new_x.permute(1, 2, 0).cpu().numpy()
+ new_x = cv2.resize(new_x, target_shape[::-1], interpolation=cv2.INTER_AREA)
+ new_x = torch.from_numpy(np.rollaxis(new_x, 2)).to(device)
+ else:
+ new_x = resize(new_x.float(), target_shape, interpolation=interp,
+ antialias=antialias).round().clamp(0, 255).byte()
+ else:
+ raise ValueError(f"Not supported dtype: {x.dtype}")
+ return new_x
+
+
+def masks_to_boxes(segmentation: torch.Tensor):
+ assert len(segmentation.shape) == 3
+ x = segmentation.any(dim=1).byte() # Compress rows
+ x0 = x.argmax(dim=1)
+
+ x1 = segmentation.shape[2] - x.flip(dims=(1,)).argmax(dim=1)
+ y = segmentation.any(dim=2).byte()
+ y0 = y.argmax(dim=1)
+ y1 = segmentation.shape[1] - y.flip(dims=(1,)).argmax(dim=1)
+ return torch.stack([x0, y0, x1, y1], dim=1)
diff --git a/project/models/deprecated_deep_privacy2/dp2/discriminator/__init__.py b/project/models/deprecated_deep_privacy2/dp2/discriminator/__init__.py
new file mode 100644
index 0000000..2c2c41a
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/discriminator/__init__.py
@@ -0,0 +1 @@
+from .sg2_discriminator import SG2Discriminator
diff --git a/project/models/deprecated_deep_privacy2/dp2/discriminator/diffaug.py b/project/models/deprecated_deep_privacy2/dp2/discriminator/diffaug.py
new file mode 100644
index 0000000..4932c3f
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/discriminator/diffaug.py
@@ -0,0 +1,85 @@
+# Differentiable Augmentation for Data-Efficient GAN Training
+# Shengyu Zhao, Zhijian Liu, Ji Lin, Jun-Yan Zhu, and Song Han
+# https://arxiv.org/pdf/2006.10738
+# Code modified from: https://github.com/autonomousvision/projected_gan/blob/main/pg_modules/diffaug.py
+import torch
+from typing import List, Optional, Tuple
+from torch.nn.functional import interpolate
+from torchvision.transforms.functional import affine
+
+
+def diff_augment(img, condition=None, policies: Optional[List[str]] = None):
+ if policies is None:
+ return img, condition
+ for policy in policies:
+ fns = AUGMENT_FNS[policy]
+ for fn in fns:
+ img, condition = fn(img, condition)
+ return img, condition
+
+
+def rand_brightness(img: torch.Tensor, condition: torch.Tensor) -> Tuple[torch.Tensor]:
+ aug = torch.rand(img.size(0), 1, 1, 1, dtype=img.dtype, device=img.device) - 0.5
+ img = img + aug
+ if condition is not None:
+ condition = condition + aug
+ return img, condition
+
+
+def rand_saturation(img: torch.Tensor, condition: torch.Tensor) -> Tuple[torch.Tensor]:
+ aug = torch.rand(img.size(0), 1, 1, 1, dtype=img.dtype, device=img.device) * 2
+ x_mean = img.mean(dim=1, keepdim=True)
+ img = (img - x_mean) * aug + x_mean
+ if condition is not None:
+ if condition.shape != x_mean.shape:
+ x_mean = interpolate(x_mean, size=condition.shape[-2:], antialias=True, mode="bilinear")
+ condition = (condition - x_mean) * aug + x_mean
+ return img, condition
+
+
+def rand_contrast(img: torch.Tensor, condition: torch.Tensor) -> Tuple[torch.Tensor]:
+ x_mean = img.mean(dim=[1, 2, 3], keepdim=True)
+ aug = torch.rand(img.size(0), 1, 1, 1, dtype=img.dtype, device=img.device) + 0.5
+ img = (img - x_mean) * aug + x_mean
+ if condition is not None:
+ condition = (condition - x_mean) * aug + x_mean
+ return img, condition
+
+
+def rand_cutout(img: torch.Tensor, condition: torch.Tensor, ratio=.2) -> Tuple[torch.Tensor]:
+ cutout_size = int(img.size(2) * ratio + 0.5), int(img.size(3) * ratio + 0.5)
+ offset_x = torch.randint(0, img.size(2) + (1 - cutout_size[0] % 2), size=[img.size(0), 1, 1], device=img.device)
+ offset_y = torch.randint(0, img.size(3) + (1 - cutout_size[1] % 2), size=[img.size(0), 1, 1], device=img.device)
+ grid_batch, grid_x, grid_y = torch.meshgrid(
+ torch.arange(img.size(0), dtype=torch.long, device=img.device),
+ torch.arange(cutout_size[0], dtype=torch.long, device=img.device),
+ torch.arange(cutout_size[1], dtype=torch.long, device=img.device),
+ indexing="ij")
+ grid_x = torch.clamp(grid_x + offset_x - cutout_size[0] // 2, min=0, max=img.size(2) - 1)
+ grid_y = torch.clamp(grid_y + offset_y - cutout_size[1] // 2, min=0, max=img.size(3) - 1)
+ mask = torch.ones(img.size(0), img.size(2), img.size(3), dtype=img.dtype, device=img.device)
+ mask[grid_batch, grid_x, grid_y] = 0
+ img = img * mask.unsqueeze(1)
+ if condition is not None:
+ if condition.shape != mask.shape:
+ mask = mask.unsqueeze(1)
+ mask = interpolate(mask, condition.shape[-2:], mode="nearest")
+ condition = condition * mask
+ return img, condition
+
+
+def rand_translation(img: torch.Tensor, condition: torch.Tensor, ratio=.2) -> Tuple[torch.Tensor]:
+ xy_shift = (torch.rand(size=(2,)) * 2 - 1).tolist()
+ xy_shift[0] *= img.shape[-1] * ratio
+ xy_shift[1] *= img.shape[-2] * ratio
+ img = affine(img, angle=0, translate=xy_shift, scale=1, shear=[0, 0])
+ if condition is not None:
+ condition = affine(condition, angle=0, translate=xy_shift, scale=1, shear=[0, 0])
+ return img, condition
+
+
+AUGMENT_FNS = {
+ 'color': [rand_brightness, rand_saturation, rand_contrast],
+ 'cutout': [rand_cutout],
+ "translate": [rand_translation],
+}
diff --git a/project/models/deprecated_deep_privacy2/dp2/discriminator/projected_gan/__init__.py b/project/models/deprecated_deep_privacy2/dp2/discriminator/projected_gan/__init__.py
new file mode 100644
index 0000000..1bde60f
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/discriminator/projected_gan/__init__.py
@@ -0,0 +1 @@
+from .discriminator import ProjectedDiscriminator
diff --git a/project/models/deprecated_deep_privacy2/dp2/discriminator/projected_gan/discriminator.py b/project/models/deprecated_deep_privacy2/dp2/discriminator/projected_gan/discriminator.py
new file mode 100644
index 0000000..a2fe91c
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/discriminator/projected_gan/discriminator.py
@@ -0,0 +1,135 @@
+from typing import List
+import numpy as np
+import torch
+import torch.nn as nn
+from dp2 import utils
+from .projector import F_RandomProj
+from ..diffaug import diff_augment
+from torch.nn.utils import spectral_norm
+
+
+def conv2d(*args, **kwargs):
+ return spectral_norm(nn.Conv2d(*args, **kwargs))
+
+
+def down_block(in_planes, out_planes):
+ return nn.Sequential(
+ conv2d(in_planes, out_planes, 4, 2, 1),
+ nn.BatchNorm2d(out_planes),
+ nn.LeakyReLU(0.2, inplace=True),
+ )
+
+
+def down_block_patch(in_planes, out_planes):
+ return nn.Sequential(
+ down_block(in_planes, out_planes),
+ conv2d(out_planes, out_planes, 1, 1, 0, bias=False),
+ nn.BatchNorm2d(out_planes),
+ nn.LeakyReLU(0.2, inplace=True),
+ )
+
+
+class SingleDisc(nn.Module):
+ def __init__(
+ self, cin, start_sz, end_sz, patch,
+ last_ksize
+ ):
+ super().__init__()
+ channel_dict = {4: 512, 8: 512, 16: 256, 32: 128, 64: 64,
+ 128: 64, 256: 32, 512: 16, 1024: 8,
+ }
+
+ # interpolate for start sz that are not powers of two
+ if start_sz not in channel_dict.keys():
+ sizes = np.array(list(channel_dict.keys()))
+ start_sz = sizes[np.argmin(abs(sizes - start_sz))]
+ self.start_sz = start_sz
+ channel_dict[start_sz] = cin
+
+ layers = []
+ # Down Blocks
+ DB = down_block_patch if patch else down_block
+ while start_sz > end_sz:
+ layers.append(DB(channel_dict[start_sz], channel_dict[start_sz // 2]))
+ start_sz = start_sz // 2
+ p = 0 if last_ksize == 4 else 1
+ layers.append(conv2d(channel_dict[end_sz], 1, last_ksize, padding=p, bias=True))
+ self.main = nn.Sequential(*layers)
+
+ def forward(self, x):
+ return self.main(x)
+
+
+class MultiScaleD(nn.Module):
+ def __init__(self, channels, resolutions, num_discs, patch, last_ksize):
+ super().__init__()
+ assert num_discs in [1, 2, 3, 4]
+ # the first disc is on the lowest level of the backbone
+ self.disc_in_channels = channels[:num_discs]
+ self.disc_in_res = resolutions[:num_discs]
+
+ self.mini_discs = nn.ModuleList()
+ for i, (cin, res) in enumerate(zip(self.disc_in_channels, self.disc_in_res)):
+ start_sz = res if not patch else 16
+ self.mini_discs.append(
+ SingleDisc(cin=cin, start_sz=start_sz, end_sz=8, patch=patch, last_ksize=last_ksize)
+ )
+
+ def forward(self, features):
+ all_logits = []
+ for feat, disc in zip(features, self.mini_discs):
+ all_logits.append(disc(feat))
+ return all_logits
+
+
+class ProjectedDiscriminator(torch.nn.Module):
+ def __init__(
+ self,
+ backbones: List[dict],
+ num_discs,
+ diffaug_policy,
+ patch,
+ last_ksize,
+ ):
+ super().__init__()
+ self.feature_networks = nn.ModuleList()
+ self.discriminators = nn.ModuleList()
+ for b in backbones:
+ feature_network = F_RandomProj(**b)
+ if feature_network.jit_script:
+ feature_network = torch.jit.script(feature_network)
+ self.feature_networks.append(feature_network)
+ in_channels = feature_network.CHANNELS
+ discriminator = MultiScaleD(
+ channels=in_channels,
+ resolutions=feature_network.RESOLUTIONS,
+ num_discs=num_discs,
+ patch=patch,
+ last_ksize=last_ksize,
+ )
+ self.discriminators.append(discriminator)
+ utils.set_requires_grad(self.feature_networks, False)
+ utils.set_requires_grad(self.discriminators, True)
+ self.diffaug_policy = diffaug_policy
+
+ def train(self, mode=True):
+ self.feature_networks = self.feature_networks.train(False)
+ self.discriminators = self.discriminators.train(mode)
+ return self
+
+ def eval(self):
+ return self.train(False)
+
+ def forward(self, img: torch.Tensor, fnet_grad=True, **kwargs):
+ img = img.add(1).div(2)
+
+ logits = []
+ for backbone, D in zip(self.feature_networks, self.discriminators):
+ # Discriminator forward pass does not need gradient for feature network.
+ with torch.set_grad_enabled(fnet_grad):
+ x = img.sub(backbone.mean).div(backbone.std)
+ x, _ = diff_augment(x, None, self.diffaug_policy)
+ features = backbone(x)
+
+ logits.append(D(features))
+ return dict(logits=logits)
diff --git a/project/models/deprecated_deep_privacy2/dp2/discriminator/projected_gan/feature_nets.py b/project/models/deprecated_deep_privacy2/dp2/discriminator/projected_gan/feature_nets.py
new file mode 100644
index 0000000..0b14576
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/discriminator/projected_gan/feature_nets.py
@@ -0,0 +1,82 @@
+# Code adapted from: https://github.com/autonomousvision/projected_gan
+from typing import List
+import torchvision
+import torch
+import torch.nn as nn
+import timm
+import tops
+from torchvision.models.feature_extraction import create_feature_extractor
+
+
+class FeatureExtractor(nn.Module):
+ def __init__(self, model, layer_names) -> None:
+ super().__init__()
+ self.model = create_feature_extractor(model, return_nodes=layer_names)
+
+ def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
+ return list(self.model(x).values())
+
+
+class FeatureExtractorByLayers(nn.Module):
+
+ def __init__(self, *layers) -> None:
+ super().__init__()
+ self.layers = nn.ModuleList(layers)
+
+ def forward(self, x) -> List[torch.Tensor]:
+ features = []
+ for layer in self.layers:
+ x = layer(x)
+ features.append(x)
+ return features
+
+
+def _make_efficientnet(model_type):
+ model = timm.create_model(model_type, pretrained=True)
+ layer0 = nn.Sequential(
+ model.conv_stem, model.bn1, *model.blocks[0:2]
+ )
+ layer1 = nn.Sequential(*model.blocks[2:3])
+ layer2 = nn.Sequential(*model.blocks[3:5])
+ layer3 = nn.Sequential(*model.blocks[5:9])
+ return FeatureExtractorByLayers(layer0, layer1, layer2, layer3)
+
+
+def _make_resnet50(weight_path=None):
+ model = torchvision.models.resnet50(pretrained=weight_path is None)
+ if weight_path is not None:
+ state_dict = tops.load_file_or_url(weight_path)
+ model.load_state_dict(state_dict)
+ return FeatureExtractor(
+ model, ["layer1", "layer2", "layer3", "layer4"]
+ )
+
+
+def _make_resnet50_swav(weight_path):
+ model = torch.hub.load("facebookresearch/swav", weight_path)
+ return FeatureExtractor(
+ model, ["layer1", "layer2", "layer3", "layer4"]
+ )
+
+
+def _make_resnet50_clip(clip_type="RN50"):
+ import clip
+ model, preprocess = clip.load(clip_type, device="cpu")
+ return FeatureExtractor(
+ model.visual,
+ layer_names=["layer1", "layer2", "layer3", "layer4"]
+ )
+
+
+def _make_resnet50_cse(cfg_url, **kwargs):
+ from dp2.detection.models.cse import CSEDetector
+ model = CSEDetector(cfg_url=cfg_url).model.cpu()
+ return FeatureExtractorByLayers(
+ nn.Sequential(
+ model.backbone.bottom_up.stem,
+ model.backbone.bottom_up.res2,
+ ),
+ model.backbone.bottom_up.res3,
+ model.backbone.bottom_up.res4,
+ model.backbone.bottom_up.res5
+ )
diff --git a/project/models/deprecated_deep_privacy2/dp2/discriminator/projected_gan/projector.py b/project/models/deprecated_deep_privacy2/dp2/discriminator/projected_gan/projector.py
new file mode 100644
index 0000000..e2bbeaa
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/discriminator/projected_gan/projector.py
@@ -0,0 +1,115 @@
+# Code adapted from: https://github.com/autonomousvision/projected_gan
+from typing import List, Optional
+import torch
+import torch.nn as nn
+from tops.config import instantiate
+
+
+class FeatureFusionBlock(nn.Module):
+ def __init__(self, features, expand):
+ super().__init__()
+
+ self.expand = expand
+ out_features = features
+ if self.expand:
+ out_features = features//2
+
+ self.out_conv = nn.Conv2d(features, out_features, kernel_size=1)
+ self.skip_add = nn.quantized.FloatFunctional()
+
+ def forward(self, x0: torch.Tensor, x1: Optional[torch.Tensor]):
+ output = x0
+ if x1 is not None:
+ output = self.skip_add.add(output, x1)
+ output = nn.functional.interpolate(
+ output, scale_factor=2., mode="bilinear", align_corners=True)
+ return self.out_conv(output)
+
+
+class ProjectorCSM(nn.Module):
+ def __init__(self, pretrained, cout, proj_type: int) -> None:
+ super().__init__()
+ assert proj_type in [0, 1, 2], "Invalid projection type"
+ im_res = 256
+ tmp = torch.zeros(1, 3, im_res, im_res)
+ self.RESOLUTIONS = [im_res//4, im_res//8, im_res//16, im_res//32]
+ in_channels = [out.shape[1] for out in pretrained(tmp)]
+ self.CHANNELS = in_channels
+ if proj_type == 0:
+ return
+ out_channels = [cout, cout*2, cout*4, cout*8]
+ self.layer0_ccm = nn.Conv2d(in_channels[0], out_channels[0], kernel_size=1)
+ self.layer1_ccm = nn.Conv2d(in_channels[1], out_channels[1], kernel_size=1)
+ self.layer2_ccm = nn.Conv2d(in_channels[2], out_channels[2], kernel_size=1)
+ self.layer3_ccm = nn.Conv2d(in_channels[3], out_channels[3], kernel_size=1)
+ self.CHANNELS = out_channels
+ # Build CCM
+ if proj_type == 1:
+ return
+ # build CSM
+ self.layer3_csm = FeatureFusionBlock(out_channels[3], expand=True)
+ self.layer2_csm = FeatureFusionBlock(out_channels[2], expand=True)
+ self.layer1_csm = FeatureFusionBlock(out_channels[1], expand=True)
+ self.layer0_csm = FeatureFusionBlock(out_channels[0], expand=False)
+ self.CHANNELS = [cout, cout, cout*2, cout*4]
+ # CSM upsamples x2 so the feature map resolution doubles
+ self.RESOLUTIONS = [res*2 for res in self.RESOLUTIONS]
+ self.proj_type = proj_type
+
+ def forward(self, x: List[torch.Tensor]) -> List[torch.Tensor]:
+ x0, x1, x2, x3 = x
+ if self.proj_type == 0:
+ return x
+ out0_channel_mixed = self.layer0_ccm(x0)
+ out1_channel_mixed = self.layer1_ccm(x1)
+ out2_channel_mixed = self.layer2_ccm(x2)
+ out3_channel_mixed = self.layer3_ccm(x3)
+ if self.proj_type == 1:
+ return [out0_channel_mixed, out1_channel_mixed, out2_channel_mixed, out3_channel_mixed]
+ # from bottom to top
+ out3_scale_mixed = self.layer3_csm(out3_channel_mixed, None)
+ out2_scale_mixed = self.layer2_csm(out3_scale_mixed, out2_channel_mixed)
+ out1_scale_mixed = self.layer1_csm(out2_scale_mixed, out1_channel_mixed)
+ out0_scale_mixed = self.layer0_csm(out1_scale_mixed, out0_channel_mixed)
+ return [out0_scale_mixed, out1_scale_mixed, out2_scale_mixed, out3_scale_mixed]
+
+
+class F_RandomProj(nn.Module):
+ def __init__(
+ self,
+ backbone_cfg,
+ interp_size,
+ input_BGR,
+ jit_script,
+ mean=None,
+ std=None,
+ cout=64,
+ proj_type=2, # 0 = no projection, 1 = cross channel mixing, 2 = cross scale mixing
+ eval_mode=True
+ ):
+ super().__init__()
+ self.pretrained = instantiate(backbone_cfg)
+ if eval_mode:
+ self.pretrained = self.pretrained.eval()
+ if mean is None:
+ mean = self.pretrained.mean
+ std = self.pretrained.std
+ self.register_buffer("mean", torch.tensor(mean).view(1, -1, 1, 1))
+ self.register_buffer("std", torch.tensor(std).view(1, -1, 1, 1))
+ # build pretrained feature network and random decoder (scratch)
+ self.projector = ProjectorCSM(self.pretrained, cout, proj_type)
+ self.CHANNELS = self.projector.CHANNELS
+ self.RESOLUTIONS = self.projector.RESOLUTIONS
+ self.input_BGR = input_BGR
+ self.interp_size = interp_size
+ self.jit_script = jit_script
+ if interp_size is not None:
+ self.interp_size = list(interp_size)
+
+ def forward(self, x):
+ if self.interp_size is not None:
+ x = nn.functional.interpolate(x, self.interp_size, mode="bilinear", align_corners=True)
+ if self.input_BGR:
+ x = x.flip(1)
+ features = self.pretrained(x)
+ return self.projector(features)
diff --git a/project/models/deprecated_deep_privacy2/dp2/discriminator/projected_gan/vit.py b/project/models/deprecated_deep_privacy2/dp2/discriminator/projected_gan/vit.py
new file mode 100644
index 0000000..aab19b8
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/discriminator/projected_gan/vit.py
@@ -0,0 +1,139 @@
+import torch
+import torch.nn as nn
+import math
+import torch.nn.functional as F
+import timm
+import tops
+
+
+class ProjectedViT(nn.Module):
+
+ def __init__(self, model_name, weight_path) -> None:
+ super().__init__()
+ model = timm.create_model(model_name, pretrained=weight_path is None)
+ if weight_path is not None:
+ filepath = tops.download_file(weight_path)
+ state_dict = torch.load(filepath, map_location="cpu")
+ state = state_dict["model"] if "model" in state_dict else state_dict
+ model.load_state_dict(state, strict=False)
+ start_index = 2 if "deit" in model_name else 1
+ patch_size = [16, 16]
+ if "tiny" in model_name:
+ proj_features = [24, 48, 96, 192]
+ layer_hooks = [2, 5, 8, 11]
+ vit_dim = 192
+
+ elif "small" in model_name:
+ proj_features = [48, 96, 192, 384]
+ layer_hooks = [2, 5, 8, 11]
+ vit_dim = 384
+
+ elif "base" in model_name:
+ proj_features = [96, 192, 384, 768]
+ layer_hooks = [2, 5, 8, 11]
+ vit_dim = 768
+ elif "large" in model_name: # Depth 24
+ proj_features = [256, 512, 1024, 1024]
+ layer_hooks = [5, 11, 17, 23]
+ vit_dim = 1024
+ elif "huge" in model_name: # Depth 32
+ proj_features = [320, 640, 1280, 1280]
+ layer_hooks = [8, 15, 23, 31]
+ vit_dim = 1280
+ patch_size = [14, 14]
+
+ model.slice_start_idx = start_index # Accessed in forward_flex
+ model.patch_size = patch_size
+ # We inject this function into the VisionTransformer instances so that
+ # we can use it with interpolated position embeddings without modifying the library source.
+ model.layer_hooks = layer_hooks
+ self.model = model
+ self.layer1 = nn.Sequential(
+ nn.Conv2d(vit_dim, proj_features[0], 1),
+ nn.ConvTranspose2d(proj_features[0], proj_features[0], 4, stride=4)
+ )
+
+ self.layer2 = nn.Sequential(
+ nn.Conv2d(vit_dim, proj_features[1], 1),
+ nn.ConvTranspose2d(proj_features[1], proj_features[1], 2, stride=2),
+ )
+
+ self.layer3 = nn.Sequential(
+ nn.Conv2d(vit_dim, proj_features[2], 1),
+ )
+
+ self.layer4 = nn.Sequential(
+ nn.Conv2d(vit_dim, proj_features[3], 1),
+ nn.Conv2d(proj_features[3], proj_features[3], 3, stride=2, padding=1),
+ )
+ self.model.blocks = self.model.blocks[:max(self.model.layer_hooks)+1]
+
+ def forward_vit(self, x):
+ b, c, h, w = x.shape
+ pos_embed = _resize_pos_embed(
+ self.model.pos_embed, h // self.model.patch_size[1], w // self.model.patch_size[0], self.model.slice_start_idx
+ )
+
+ if hasattr(self.model.patch_embed, "backbone"):
+ x = self.model.patch_embed.backbone(x)
+ if isinstance(x, (list, tuple)):
+ x = x[-1] # last feature if backbone outputs list/tuple of features
+ x = self.model.patch_embed.proj(x).flatten(2).transpose(1, 2)
+
+ if hasattr(self.model, "dist_token") and self.model.dist_token is not None:
+ cls_tokens = self.model.cls_token.expand(
+ b, -1, -1
+ ) # stole cls_tokens impl from Phil Wang, thanks
+ dist_token = self.model.dist_token.expand(b, -1, -1)
+ x = torch.cat((cls_tokens, dist_token, x), dim=1)
+ else:
+ cls_tokens = self.model.cls_token.expand(
+ b, -1, -1
+ ) # stole cls_tokens impl from Phil Wang, thanks
+ x = torch.cat((cls_tokens, x), dim=1)
+
+ x = x + pos_embed
+ x = self.model.pos_drop(x)
+ feats = []
+ for i, blk in enumerate(self.model.blocks):
+ x = blk(x)
+ if i in self.model.layer_hooks:
+ feats.append(x)
+ return feats
+
+ def forward(self, x: torch.Tensor):
+ b, c, h, w = x.shape
+ features = self.forward_vit(x)
+ features = [x[:, self.model.slice_start_idx:] for x in features]
+ features = [ # n l c -> n c h w
+ torch.transpose(x, 1, 2).unflatten(dim=-1, sizes=(h//self.model.patch_size[0], w//self.model.patch_size[1]))
+ for x in features
+ ]
+
+ x0, x1, x2, x3 = features
+ x0 = self.layer1(x0)
+ x1 = self.layer2(x1)
+ x2 = self.layer3(x2)
+ x3 = self.layer4(x3)
+ return x0, x1, x2, x3
+
+
+def _make_vit_timm(model_name, weight_path=None):
+ return ProjectedViT(model_name, weight_path)
+
+
+def _resize_pos_embed(posemb: torch.Tensor, gs_h: int, gs_w: int, slice_start_idx: int) -> torch.Tensor:
+ posemb_tok, posemb_grid = (
+ posemb[:, : slice_start_idx],
+ posemb[0, slice_start_idx:],
+ )
+
+ gs_old = int(math.sqrt(len(posemb_grid)))
+
+ posemb_grid = posemb_grid.reshape(1, gs_old, gs_old, -1).permute(0, 3, 1, 2)
+ posemb_grid = F.interpolate(posemb_grid, size=(gs_h, gs_w), mode="bilinear", align_corners=False)
+ posemb_grid = posemb_grid.permute(0, 2, 3, 1).reshape(1, gs_h * gs_w, -1)
+
+ posemb = torch.cat([posemb_tok, posemb_grid], dim=1)
+
+ return posemb
diff --git a/project/models/deprecated_deep_privacy2/dp2/discriminator/projected_gan/vit_openclip.py b/project/models/deprecated_deep_privacy2/dp2/discriminator/projected_gan/vit_openclip.py
new file mode 100644
index 0000000..9ebe8d8
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/discriminator/projected_gan/vit_openclip.py
@@ -0,0 +1,128 @@
+import torch
+import torch.nn as nn
+try:
+ import open_clip
+ from open_clip.model import VisualTransformer
+except ImportError:
+ print("Could not import openclip")
+from einops import rearrange
+from .vit import _resize_pos_embed
+
+
+class OpenCLIPViT(nn.Module):
+
+ def __init__(self, model_name, pretrained_dataset) -> None:
+ super().__init__()
+ assert model_name in [
+ "ViT-B-32", "ViT-B-16", "ViT-L-14", "ViT-H-14", "ViT-g-14"
+ ]
+ assert model_name not in ["ViT-H-14", "ViT-g-14"]
+ if model_name == "ViT-B-16":
+ proj_features = [96, 192, 384, 768]
+ layer_hooks = [2, 5, 8, 11]
+ vit_dim = 768
+ patch_size = [16, 16]
+ if model_name == "ViT-L-14":
+ patch_size = [14, 14]
+ vit_dim = 1024
+ layer_hooks = [5, 11, 17, 23]
+ proj_features = [256, 512, 1024, 1024]
+ if model_name == "ViT-B-32":
+ patch_size = [32, 32]
+ vit_dim = 768
+ proj_features = [96, 192, 384, 768]
+ layer_hooks = [2, 5, 8, 11]
+ # preprocess consists of resize -> center crop -> rgb -> normalize
+ model, _, preprocess = open_clip.create_model_and_transforms(model_name, pretrained_dataset)
+ model = model.visual
+ print(model)
+
+ self.slice_start_idx = 1 # Accessed in forward_flex
+ self.patch_size = patch_size
+ # We inject this function into the VisionTransformer instances so that
+ # we can use it with interpolated position embeddings without modifying the library source.
+ model.layer_hooks = layer_hooks
+ self.model = model
+ self.model.transformer.resblocks = self.model.transformer.resblocks[:max(self.model.layer_hooks)+1]
+ if patch_size[0] == 32:
+ self._make_proj_layers_vit32(vit_dim, proj_features)
+ else:
+ self._make_proj_layers(vit_dim, proj_features)
+
+ def _make_proj_layers_vit32(self, vit_dim, proj_features):
+ self.layer1 = nn.Sequential(
+ nn.Conv2d(vit_dim, proj_features[0], 1),
+ nn.ConvTranspose2d(proj_features[0], proj_features[0], 8, stride=8)
+ )
+
+ self.layer2 = nn.Sequential(
+ nn.Conv2d(vit_dim, proj_features[1], 1),
+ nn.ConvTranspose2d(proj_features[1], proj_features[1], 4, stride=4),
+ )
+
+ self.layer3 = nn.Sequential(
+ nn.Conv2d(vit_dim, proj_features[2], 1),
+ nn.ConvTranspose2d(proj_features[2], proj_features[2], 2, stride=2),
+ )
+
+ self.layer4 = nn.Sequential(
+ nn.Conv2d(vit_dim, proj_features[3], 1),
+ )
+
+ def _make_proj_layers(self, vit_dim, proj_features):
+ self.layer1 = nn.Sequential(
+ nn.Conv2d(vit_dim, proj_features[0], 1),
+ nn.ConvTranspose2d(proj_features[0], proj_features[0], 4, stride=4)
+ )
+
+ self.layer2 = nn.Sequential(
+ nn.Conv2d(vit_dim, proj_features[1], 1),
+ nn.ConvTranspose2d(proj_features[1], proj_features[1], 2, stride=2),
+ )
+
+ self.layer3 = nn.Sequential(
+ nn.Conv2d(vit_dim, proj_features[2], 1),
+ )
+
+ self.layer4 = nn.Sequential(
+ nn.Conv2d(vit_dim, proj_features[3], 1),
+ nn.Conv2d(proj_features[3], proj_features[3], 3, stride=2, padding=1),
+ )
+
+ def forward_vit(self, x):
+ assert isinstance(self.model, VisualTransformer)
+ b, c, h, w = x.shape
+ pos_embed = _resize_pos_embed(
+ self.model.positional_embedding[None], h // self.patch_size[1], w // self.patch_size[0], self.slice_start_idx
+ )[0]
+
+ x = self.model.conv1(x)
+ x = rearrange(x, "n c h w -> n (h w) c")
+ x = torch.cat(
+ [self.model.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device),
+ x], dim=1) # shape = [*, grid ** 2 + 1, width]
+ x = x + pos_embed
+ x = self.model.ln_pre(x)
+ x = rearrange(x, "b l c -> l b c")
+ feats = []
+ for i, l in enumerate(self.model.transformer.resblocks):
+ x = l(x)
+ if i in self.model.layer_hooks:
+ feats.append(x)
+ return feats
+
+ def forward(self, x: torch.Tensor):
+ b, c, h, w = x.shape
+ features = self.forward_vit(x) # Outputs l n c
+ features = [x[self.slice_start_idx:] for x in features]
+ features = [
+ rearrange(f, "(h w) n c -> n c h w", h=h//self.patch_size[0])
+ for f in features
+ ]
+
+ x0, x1, x2, x3 = features
+ x0 = self.layer1(x0)
+ x1 = self.layer2(x1)
+ x2 = self.layer3(x2)
+ x3 = self.layer4(x3)
+ return x0, x1, x2, x3
diff --git a/project/models/deprecated_deep_privacy2/dp2/discriminator/sg2_discriminator.py b/project/models/deprecated_deep_privacy2/dp2/discriminator/sg2_discriminator.py
new file mode 100644
index 0000000..269675d
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/discriminator/sg2_discriminator.py
@@ -0,0 +1,79 @@
+from sg3_torch_utils.ops import upfirdn2d
+import torch
+import numpy as np
+import torch.nn as nn
+from .. import layers
+from ..layers.sg2_layers import DiscriminatorEpilogue, ResidualBlock, Block
+
+
+class SG2Discriminator(layers.Module):
+
+ def __init__(
+ self,
+ cnum: int,
+ max_cnum_mul: int,
+ imsize,
+ min_fmap_resolution: int,
+ im_channels: int,
+ input_condition: bool,
+ conv_clamp: int,
+ input_cse: bool,
+ cse_nc: int,
+ fix_residual: bool,
+ ):
+ super().__init__()
+
+ cse_nc = 0 if cse_nc is None else cse_nc
+ self._max_imsize = max(imsize)
+ self._cnum = cnum
+ self._max_cnum_mul = max_cnum_mul
+ self._min_fmap_resolution = min_fmap_resolution
+ self._input_condition = input_condition
+ self.input_cse = input_cse
+ self.layers = nn.ModuleList()
+
+ out_ch = self.get_chsize(self._max_imsize)
+ self.from_rgb = Block(
+ im_channels + input_condition*(im_channels+1) + input_cse*(cse_nc+1),
+ out_ch, conv_clamp=conv_clamp
+ )
+ n_levels = int(np.log2(self._max_imsize) - np.log2(min_fmap_resolution))+1
+
+ for i in range(n_levels):
+ resolution = [x//2**i for x in imsize]
+ in_ch = self.get_chsize(max(resolution))
+ out_ch = self.get_chsize(max(max(resolution)//2, min_fmap_resolution))
+
+ down = 2
+ if i == 0:
+ down = 1
+ block = ResidualBlock(
+ in_ch, out_ch, down=down, conv_clamp=conv_clamp,
+ fix_residual=fix_residual
+ )
+ self.layers.append(block)
+ self.output_layer = DiscriminatorEpilogue(
+ out_ch, resolution, conv_clamp=conv_clamp)
+
+ self.register_buffer('resample_filter', upfirdn2d.setup_filter([1, 3, 3, 1]))
+
+ def forward(self, img, condition, mask, embedding=None, E_mask=None, **kwargs):
+ to_cat = [img]
+ if self._input_condition:
+ to_cat.extend([condition, mask, ])
+ if self.input_cse:
+ to_cat.extend([embedding, E_mask])
+ x = torch.cat(to_cat, dim=1)
+ x = self.from_rgb(x)
+
+ for i, layer in enumerate(self.layers):
+ x = layer(x)
+
+ x = self.output_layer(x)
+ return dict(score=x)
+
+ def get_chsize(self, imsize):
+ n = int(np.log2(self._max_imsize) - np.log2(imsize))
+ mul = min(2 ** n, self._max_cnum_mul)
+ ch = self._cnum * mul
+ return int(ch)
diff --git a/project/models/deprecated_deep_privacy2/dp2/gan_trainer.py b/project/models/deprecated_deep_privacy2/dp2/gan_trainer.py
new file mode 100644
index 0000000..149e0f6
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/gan_trainer.py
@@ -0,0 +1,325 @@
+import atexit
+from collections import defaultdict
+import logging
+import typing
+import torch
+import time
+from dp2.utils import vis_utils
+from dp2 import utils
+from tops import logger, checkpointer
+import tops
+from easydict import EasyDict
+
+
+def accumulate_gradients(params, fp16_ddp_accumulate):
+ if len(params) == 0:
+ return
+ params = [param for param in params if param.grad is not None]
+ flat = torch.cat([param.grad.flatten() for param in params])
+ orig_dtype = flat.dtype
+ if tops.world_size() > 1:
+ if fp16_ddp_accumulate:
+ flat = flat.half() / tops.world_size()
+ else:
+ flat /= tops.world_size()
+ torch.distributed.all_reduce(flat)
+ flat = flat.to(orig_dtype)
+ grads = flat.split([param.numel() for param in params])
+ for param, grad in zip(params, grads):
+ param.grad = grad.reshape(param.shape)
+
+
+def accumulate_buffers(module: torch.nn.Module):
+ buffers = [buf for buf in module.buffers()]
+ if len(buffers) == 0:
+ return
+ flat = torch.cat([buf.flatten() for buf in buffers])
+ if tops.world_size() > 1:
+ torch.distributed.all_reduce(flat)
+ flat /= tops.world_size()
+ bufs = flat.split([buf.numel() for buf in buffers])
+ for old, new in zip(buffers, bufs):
+ old.copy_(new.reshape(old.shape), non_blocking=True)
+
+
+def check_ddp_consistency(module):
+ if tops.world_size() == 1:
+ return
+ assert isinstance(module, torch.nn.Module)
+ assert isinstance(module, torch.nn.Module)
+ params_buffs = list(module.named_parameters()) + list(module.named_buffers())
+ for name, tensor in params_buffs:
+ fullname = type(module).__name__ + '.' + name
+ tensor = tensor.detach()
+ if tensor.is_floating_point():
+ tensor = torch.nan_to_num(tensor)
+ other = tensor.clone()
+ torch.distributed.broadcast(tensor=other, src=0)
+ assert (tensor == other).all(), fullname
+
+
+class AverageMeter():
+ def __init__(self) -> None:
+ self.to_log = dict()
+ self.n = defaultdict(int)
+ pass
+
+ @torch.no_grad()
+ def update(self, values: dict):
+ for key, value in values.items():
+ self.n[key] += 1
+ if key in self.to_log:
+ self.to_log[key] += value.mean().detach()
+ else:
+ self.to_log[key] = value.mean().detach()
+
+ def get_average(self):
+ return {key: value / self.n[key] for key, value in self.to_log.items()}
+
+
+class GANTrainer:
+
+ def __init__(
+ self,
+ G: torch.nn.Module,
+ D: torch.nn.Module,
+ G_EMA: torch.nn.Module,
+ D_optim: torch.optim.Optimizer,
+ G_optim: torch.optim.Optimizer,
+ dl_train: typing.Iterator,
+ dl_val: typing.Iterable,
+ scaler_D: torch.cuda.amp.GradScaler,
+ scaler_G: torch.cuda.amp.GradScaler,
+ ims_per_log: int,
+ max_images_to_train: int,
+ loss_handler,
+ ims_per_val: int,
+ evaluate_fn,
+ batch_size: int,
+ broadcast_buffers: bool,
+ fp16_ddp_accumulate: bool,
+ save_state: bool,
+ *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ self.G = G
+ self.D = D
+ self.G_EMA = G_EMA
+ self.D_optim = D_optim
+ self.G_optim = G_optim
+ self.dl_train = dl_train
+ self.dl_val = dl_val
+ self.scaler_D = scaler_D
+ self.scaler_G = scaler_G
+ self.loss_handler = loss_handler
+ self.max_images_to_train = max_images_to_train
+ self.images_per_val = ims_per_val
+ self.images_per_log = ims_per_log
+ self.evaluate_fn = evaluate_fn
+ self.batch_size = batch_size
+ self.broadcast_buffers = broadcast_buffers
+ self.fp16_ddp_accumulate = fp16_ddp_accumulate
+
+ self.train_state = EasyDict(
+ next_log_step=0,
+ next_val_step=ims_per_val,
+ total_time=0
+ )
+
+ checkpointer.register_models(dict(
+ generator=G, discriminator=D, EMA_generator=G_EMA,
+ D_optimizer=D_optim,
+ G_optimizer=G_optim,
+ train_state=self.train_state,
+ scaler_D=self.scaler_D,
+ scaler_G=self.scaler_G
+ ))
+ if checkpointer.has_checkpoint():
+ checkpointer.load_registered_models()
+ logger.log(f"Resuming training from: global step: {logger.global_step()}")
+ else:
+ logger.add_dict({
+ "stats/discriminator_parameters": tops.num_parameters(self.D),
+ "stats/generator_parameters": tops.num_parameters(self.G),
+ }, commit=False)
+ if save_state:
+ # If the job is unexpectedly killed, there could be a mismatch between previously saved checkpoint and the current checkpoint.
+ atexit.register(checkpointer.save_registered_models)
+
+ self._ims_per_log = ims_per_log
+
+ self.to_log = AverageMeter()
+ self.trainable_params_D = [param for param in self.D.parameters() if param.requires_grad]
+ self.trainable_params_G = [param for param in self.G.parameters() if param.requires_grad]
+ logger.add_dict({
+ "stats/discriminator_trainable_parameters": sum(p.numel() for p in self.trainable_params_D),
+ "stats/generator_trainable_parameters": sum(p.numel() for p in self.trainable_params_G),
+ }, commit=False, level=logging.INFO)
+ check_ddp_consistency(self.D)
+ check_ddp_consistency(self.G)
+ check_ddp_consistency(self.G_EMA.generator)
+
+ def train_loop(self):
+ self.log_time()
+ while logger.global_step() <= self.max_images_to_train:
+ batch = next(self.dl_train)
+ self.G_EMA.update_beta()
+ self.to_log.update(self.step_D(batch))
+ self.to_log.update(self.step_G(batch))
+ self.G_EMA.update(self.G)
+
+ if logger.global_step() >= self.train_state.next_log_step:
+ to_log = {f"loss/{key}": item.item() for key, item in self.to_log.get_average().items()}
+ to_log.update({"amp/grad_scale_G": self.scaler_G.get_scale()})
+ to_log.update({"amp/grad_scale_D": self.scaler_D.get_scale()})
+ self.to_log = AverageMeter()
+ logger.add_dict(to_log, commit=True)
+ self.train_state.next_log_step += self.images_per_log
+ if self.scaler_D.get_scale() < 1e-8 or self.scaler_G.get_scale() < 1e-8:
+ print("Stopping training as gradient scale < 1e-8")
+ logger.log("Stopping training as gradient scale < 1e-8")
+ break
+
+ if logger.global_step() >= self.train_state.next_val_step:
+ self.evaluate()
+ self.log_time()
+ self.save_images()
+ self.train_state.next_val_step += self.images_per_val
+ logger.step(self.batch_size*tops.world_size())
+ logger.log(f"Reached end of training at step {logger.global_step()}.")
+ checkpointer.save_registered_models()
+
+ def estimate_ims_per_hour(self):
+ batch = next(self.dl_train)
+ n_ims = int(100e3)
+ n_steps = int(n_ims / (self.batch_size * tops.world_size()))
+ n_ims = n_steps * self.batch_size * tops.world_size()
+ for i in range(10): # Warmup
+ self.G_EMA.update_beta()
+ self.step_D(batch)
+ self.step_G(batch)
+ self.G_EMA.update(self.G)
+ start_time = time.time()
+ for i in utils.tqdm_(list(range(n_steps))):
+ self.G_EMA.update_beta()
+ self.step_D(batch)
+ self.step_G(batch)
+ self.G_EMA.update(self.G)
+ total_time = time.time() - start_time
+ ims_per_sec = n_ims / total_time
+ ims_per_hour = ims_per_sec * 60*60
+ ims_per_day = ims_per_hour * 24
+ logger.log(f"Images per hour: {ims_per_hour/1e6:.3f}M")
+ logger.log(f"Images per day: {ims_per_day/1e6:.3f}M")
+ import math
+ ims_per_4_day = int(math.ceil(ims_per_day / tops.world_size() * 4))
+ logger.log(f"Images per 4 days: {ims_per_4_day}")
+ logger.add_dict({
+ "stats/ims_per_day": ims_per_day,
+ "stats/ims_per_4_day": ims_per_4_day
+ })
+
+ def log_time(self):
+ if not hasattr(self, "start_time"):
+ self.start_time = time.time()
+ self.last_time_step = logger.global_step()
+ return
+ n_images = logger.global_step() - self.last_time_step
+ if n_images == 0:
+ return
+ n_secs = time.time() - self.start_time
+ n_ims_per_sec = n_images / n_secs
+ training_time_hours = n_secs / 60 / 60
+ self.train_state.total_time += training_time_hours
+ remaining_images = self.max_images_to_train - logger.global_step()
+ remaining_time = remaining_images / n_ims_per_sec / 60 / 60
+ logger.add_dict({
+ "stats/n_ims_per_sec": n_ims_per_sec,
+ "stats/total_traing_time_hours": self.train_state.total_time,
+ "stats/remaining_time_hours": remaining_time
+ })
+ self.last_time_step = logger.global_step()
+ self.start_time = time.time()
+
+ def save_images(self):
+ dl_val = iter(self.dl_val)
+ batch = next(dl_val)
+ # TRUNCATED visualization
+ ims_to_log = 8
+ self.G_EMA.eval()
+ z = self.G.get_z(batch["img"])
+ fakes_truncated = self.G_EMA.sample(**batch, truncation_value=0)["img"]
+ fakes_truncated = utils.denormalize_img(fakes_truncated).mul(255).byte()[:ims_to_log].cpu()
+ if "__key__" in batch:
+ batch.pop("__key__")
+ real = vis_utils.visualize_batch(**tops.to_cpu(batch))[:ims_to_log]
+ to_vis = torch.cat((real, fakes_truncated))
+ logger.add_images("images/truncated", to_vis, nrow=2)
+
+ # Diverse images
+ ims_diverse = 3
+ batch = next(dl_val)
+ to_vis = []
+
+ for i in range(ims_diverse):
+ z = self.G.get_z(batch["img"])[:1].repeat(batch["img"].shape[0], 1)
+ fakes = utils.denormalize_img(self.G_EMA(**batch, z=z)["img"]).mul(255).byte()[:ims_to_log].cpu()
+ to_vis.append(fakes)
+ if "__key__" in batch:
+ batch.pop("__key__")
+ reals = vis_utils.visualize_batch(**tops.to_cpu(batch))[:ims_to_log]
+ to_vis.insert(0, reals)
+ to_vis = torch.cat(to_vis)
+ logger.add_images("images/diverse", to_vis, nrow=ims_diverse+1)
+
+ self.G_EMA.train()
+ pass
+
+ def evaluate(self):
+ logger.log("Stating evaluation.")
+ self.G_EMA.eval()
+ try:
+ checkpointer.save_registered_models(max_keep=3)
+ except Exception:
+ logger.log("Could not save checkpoint.")
+ if self.broadcast_buffers:
+ check_ddp_consistency(self.G)
+ check_ddp_consistency(self.D)
+ metrics = self.evaluate_fn(generator=self.G_EMA, dataloader=self.dl_val)
+ metrics = {f"metrics/{k}": v for k, v in metrics.items()}
+ logger.add_dict(metrics, level=logger.logger.INFO)
+
+ def step_D(self, batch):
+ utils.set_requires_grad(self.trainable_params_D, True)
+ utils.set_requires_grad(self.trainable_params_G, False)
+ tops.zero_grad(self.D)
+ loss, to_log = self.loss_handler.D_loss(batch, grad_scaler=self.scaler_D)
+ with torch.autograd.profiler.record_function("D_step"):
+ self.scaler_D.scale(loss).backward()
+ accumulate_gradients(self.trainable_params_D, fp16_ddp_accumulate=self.fp16_ddp_accumulate)
+ if self.broadcast_buffers:
+ accumulate_buffers(self.D)
+ accumulate_buffers(self.G)
+ # Step will not unscale if unscale is called previously.
+ self.scaler_D.step(self.D_optim)
+ self.scaler_D.update()
+ utils.set_requires_grad(self.trainable_params_D, False)
+ utils.set_requires_grad(self.trainable_params_G, False)
+ return to_log
+
+ def step_G(self, batch):
+ utils.set_requires_grad(self.trainable_params_D, False)
+ utils.set_requires_grad(self.trainable_params_G, True)
+ tops.zero_grad(self.G)
+ loss, to_log = self.loss_handler.G_loss(batch, grad_scaler=self.scaler_G)
+ with torch.autograd.profiler.record_function("G_step"):
+ self.scaler_G.scale(loss).backward()
+ accumulate_gradients(self.trainable_params_G, fp16_ddp_accumulate=self.fp16_ddp_accumulate)
+ if self.broadcast_buffers:
+ accumulate_buffers(self.G)
+ accumulate_buffers(self.D)
+ self.scaler_G.step(self.G_optim)
+ self.scaler_G.update()
+ utils.set_requires_grad(self.trainable_params_D, False)
+ utils.set_requires_grad(self.trainable_params_G, False)
+ return to_log
diff --git a/project/models/deprecated_deep_privacy2/dp2/generator/__init__.py b/project/models/deprecated_deep_privacy2/dp2/generator/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/project/models/deprecated_deep_privacy2/dp2/generator/base.py b/project/models/deprecated_deep_privacy2/dp2/generator/base.py
new file mode 100644
index 0000000..179e9fb
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/generator/base.py
@@ -0,0 +1,153 @@
+import torch
+import numpy as np
+import tqdm
+import tops
+from ..layers import Module
+from ..layers.sg2_layers import FullyConnectedLayer
+
+
+class BaseGenerator(Module):
+
+ def __init__(self, z_channels: int):
+ super().__init__()
+ self.z_channels = z_channels
+ self.latent_space = "Z"
+
+ @torch.no_grad()
+ def get_z(
+ self,
+ x: torch.Tensor = None,
+ z: torch.Tensor = None,
+ truncation_value: float = None,
+ batch_size: int = None,
+ dtype=None, device=None) -> torch.Tensor:
+ """Generates a latent variable for generator.
+ """
+ if z is not None:
+ return z
+ if x is not None:
+ batch_size = x.shape[0]
+ dtype = x.dtype
+ device = x.device
+ if device is None:
+ device = tops.get_device()
+ if truncation_value == 0:
+ return torch.zeros((batch_size, self.z_channels), device=device, dtype=dtype)
+ z = torch.randn((batch_size, self.z_channels), device=device, dtype=dtype)
+ if truncation_value is None:
+ return z
+ while z.abs().max() > truncation_value:
+ m = z.abs() > truncation_value
+ z[m] = torch.rand_like(z)[m]
+ return z
+
+ def sample(self, truncation_value, z=None, **kwargs):
+ """
+ Samples via interpolating to the mean (0).
+ """
+ if truncation_value is None:
+ return self.forward(**kwargs)
+ truncation_value = max(0, truncation_value)
+ truncation_value = min(truncation_value, 1)
+ if z is None:
+ z = self.get_z(kwargs["condition"])
+ z = z * truncation_value
+ return self.forward(**kwargs, z=z)
+
+
+class SG2StyleNet(torch.nn.Module):
+ def __init__(self,
+ z_dim, # Input latent (Z) dimensionality.
+ w_dim, # Intermediate latent (W) dimensionality.
+ num_layers=2, # Number of mapping layers.
+ lr_multiplier=0.01, # Learning rate multiplier for the mapping layers.
+ w_avg_beta=0.998, # Decay for tracking the moving average of W during training.
+ ):
+ super().__init__()
+ self.z_dim = z_dim
+ self.w_dim = w_dim
+ self.num_layers = num_layers
+ self.w_avg_beta = w_avg_beta
+ # Construct layers.
+ features = [self.z_dim] + [self.w_dim] * self.num_layers
+ for idx, in_features, out_features in zip(range(num_layers), features[:-1], features[1:]):
+ layer = FullyConnectedLayer(in_features, out_features, activation='lrelu', lr_multiplier=lr_multiplier)
+ setattr(self, f'fc{idx}', layer)
+ self.register_buffer('w_avg', torch.zeros([w_dim]))
+
+ def forward(self, z, update_emas=False, **kwargs):
+ tops.assert_shape(z, [None, self.z_dim])
+
+ # Embed, normalize, and concatenate inputs.
+ x = z.to(torch.float32)
+ x = x * (x.square().mean(1, keepdim=True) + 1e-8).rsqrt()
+ # Execute layers.
+ for idx in range(self.num_layers):
+ x = getattr(self, f'fc{idx}')(x)
+ # Update moving average of W.
+ if update_emas:
+ self.w_avg.copy_(x.float().detach().mean(dim=0).lerp(self.w_avg, self.w_avg_beta))
+
+ return x
+
+ def extra_repr(self):
+ return f'z_dim={self.z_dim:d}, w_dim={self.w_dim:d}'
+
+ def update_w(self, n=int(10e3), batch_size=32):
+ """
+ Calculate w_ema over n iterations.
+ Useful in cases where w_ema is calculated incorrectly during training.
+ """
+ n = n // batch_size
+ for i in tqdm.trange(n, desc="Updating w"):
+ z = torch.randn((batch_size, self.z_dim), device=tops.get_device())
+ self(z, update_emas=True)
+
+ def get_truncated(self, truncation_value, condition=None, z=None, n=None,**kwargs):
+ if n is None:
+ n = condition.shape[0] if condition is not None else z.shape[0]
+ if z is None:
+ z = torch.randn((n, self.z_dim), device=tops.get_device())
+ w = self(z)
+ truncation_value = max(0, truncation_value)
+ truncation_value = min(truncation_value, 1)
+ return self.w_avg.to(w.dtype).lerp(w, truncation_value)
+
+ def multi_modal_truncate(self, truncation_value, condition=None, w_indices=None, z=None, n=None,**kwargs):
+ truncation_value = max(0, truncation_value)
+ truncation_value = min(truncation_value, 1)
+ if n is None:
+ n = len(w_indices) if w_indices is not None else (condition.shape[0] if condition is not None else z.shape[0])
+ if z is None:
+ z = torch.randn((n, self.z_dim), device=tops.get_device())
+ w = self(z)
+ if w_indices is None:
+ w_indices = np.random.randint(0, len(self.w_centers), size=(len(w)))
+ w_centers = self.w_centers[w_indices].to(w.device)
+ w = w_centers.to(w.dtype).lerp(w, truncation_value)
+ return w
+
+class BaseStyleGAN(BaseGenerator):
+
+ def __init__(self, z_channels: int, w_dim: int):
+ super().__init__(z_channels)
+ self.style_net = SG2StyleNet(z_channels, w_dim)
+ self.latent_space = "W"
+
+ def get_w(self, z, update_emas):
+ return self.style_net(z, update_emas=update_emas)
+
+ @torch.no_grad()
+ def sample(self, truncation_value, **kwargs):
+ if truncation_value is None:
+ return self.forward(**kwargs)
+ w = self.style_net.get_truncated(truncation_value, **kwargs)
+ return self.forward(**kwargs, w=w)
+
+ def update_w(self, *args, **kwargs):
+ self.style_net.update_w(*args, **kwargs)
+
+ @torch.no_grad()
+ def multi_modal_truncate(self, truncation_value, w_indices=None, **kwargs):
+ w = self.style_net.multi_modal_truncate(truncation_value, w_indices=w_indices, **kwargs)
+ return self.forward(**kwargs, w=w)
diff --git a/project/models/deprecated_deep_privacy2/dp2/generator/deep_privacy1.py b/project/models/deprecated_deep_privacy2/dp2/generator/deep_privacy1.py
new file mode 100644
index 0000000..f87a29e
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/generator/deep_privacy1.py
@@ -0,0 +1,648 @@
+import torch
+import torch.nn as nn
+from easydict import EasyDict
+from .base import BaseGenerator
+import numpy as np
+from typing import List
+
+
+class LatentVariableConcat(nn.Module):
+
+ def __init__(self, conv2d_config):
+ super().__init__()
+
+ def forward(self, _inp):
+ x, mask, batch = _inp
+ z = batch["z"]
+ x = torch.cat((x, z), dim=1)
+ return (x, mask, batch)
+
+
+def get_padding(kernel_size: int, dilation: int, stride: int):
+ out = (dilation * (kernel_size - 1) - 1) / 2 + 1
+ return int(np.floor(out))
+
+
+class Conv2d(nn.Conv2d):
+
+ def __init__(self, in_channels, out_channels, kernel_size, stride=1,
+ padding=None, dilation=1, groups=1,
+ bias=True, padding_mode='zeros',
+ demodulation=False, wsconv=False, gain=1,
+ *args, **kwargs):
+ if padding is None:
+ padding = get_padding(kernel_size, dilation, stride)
+ super().__init__(
+ in_channels, out_channels, kernel_size, stride, padding, dilation,
+ groups, bias, padding_mode)
+ self.demodulation = demodulation
+ self.wsconv = wsconv
+ if self.wsconv:
+ fan_in = np.prod(self.weight.shape[1:]) / self.groups
+ self.ws_scale = gain / np.sqrt(fan_in)
+ nn.init.normal_(self.weight)
+ if bias:
+ nn.init.constant_(self.bias, val=0)
+ assert not self.padding_mode == "circular",\
+ "conv2d_forward does not support circular padding. Look at original pytorch code"
+
+ def _get_weight(self):
+ weight = self.weight
+ if self.wsconv:
+ weight = self.ws_scale * weight
+ if self.demodulation:
+ demod = torch.rsqrt(weight.pow(2).sum([1, 2, 3]) + 1e-7)
+ weight = weight * demod.view(self.out_channels, 1, 1, 1)
+ return weight
+
+ def conv2d_forward(self, x, weight, bias=True):
+ bias_ = None
+ if bias:
+ bias_ = self.bias
+ return nn.functional.conv2d(x, weight, bias_, self.stride,
+ self.padding, self.dilation, self.groups)
+
+ def forward(self, _inp):
+ x, mask = _inp
+ weight = self._get_weight()
+ return self.conv2d_forward(x, weight), mask
+
+ def __repr__(self):
+ return ", ".join([
+ super().__repr__(),
+ f"Demodulation={self.demodulation}",
+ f"Weight Scale={self.wsconv}",
+ f"Bias={self.bias is not None}"
+ ])
+
+
+class LeakyReLU(nn.LeakyReLU):
+
+ def forward(self, _inp):
+ x, mask = _inp
+ return super().forward(x), mask
+
+
+class AvgPool2d(nn.AvgPool2d):
+
+ def forward(self, _inp):
+ x, mask, *args = _inp
+ x = super().forward(x)
+ mask = super().forward(mask)
+ if len(args) > 0:
+ return (x, mask, *args)
+ return x, mask
+
+
+def up(x):
+ if x.shape[0] == 1 and x.shape[2] == 1 and x.shape[3] == 1:
+ # Analytical normalization
+ return x
+ return nn.functional.interpolate(
+ x, scale_factor=2, mode="nearest")
+
+
+class NearestUpsample(nn.Module):
+
+ def forward(self, _inp):
+ x, mask, *args = _inp
+ x = up(x)
+ mask = up(mask)
+ if len(args) > 0:
+ return (x, mask, *args)
+ return x, mask
+
+
+class PixelwiseNormalization(nn.Module):
+
+ def forward(self, _inp):
+ x, mask = _inp
+ norm = torch.rsqrt((x**2).mean(dim=1, keepdim=True) + 1e-7)
+ return x * norm, mask
+
+
+class Linear(nn.Linear):
+
+ def __init__(self, in_features, out_features):
+ super().__init__(in_features, out_features)
+ self.linear = nn.Linear(in_features, out_features)
+ fanIn = in_features
+ self.wtScale = 1 / np.sqrt(fanIn)
+
+ nn.init.normal_(self.weight)
+ nn.init.constant_(self.bias, val=0)
+
+ def _get_weight(self):
+ return self.weight * self.wtScale
+
+ def forward_linear(self, x, weight):
+ return nn.functional.linear(x, weight, self.bias)
+
+ def forward(self, x):
+ return self.forward_linear(x, self._get_weight())
+
+
+class OneHotPoseConcat(nn.Module):
+
+ def forward(self, _inp):
+ x, mask, batch = _inp
+ landmarks = batch["landmarks_oh"]
+ res = x.shape[-1]
+ landmark = landmarks[res]
+ x = torch.cat((x, landmark), dim=1)
+ del batch["landmarks_oh"][res]
+ return x, mask, batch
+
+
+def transition_features(x_old, x_new, transition_variable):
+ assert x_old.shape == x_new.shape,\
+ "Old shape: {}, New: {}".format(x_old.shape, x_new.shape)
+ return torch.lerp(x_old.float(), x_new.float(), transition_variable)
+
+
+class TransitionBlock(nn.Module):
+
+ def forward(self, _inp):
+ x, mask, batch = _inp
+ x = transition_features(
+ batch["x_old"], x, batch["transition_value"])
+ mask = transition_features(
+ batch["mask_old"], mask, batch["transition_value"])
+ del batch["x_old"]
+ del batch["mask_old"]
+ return x, mask, batch
+
+
+class UnetSkipConnection(nn.Module):
+
+ def __init__(self, conv2d_config: dict, in_channels: int,
+ out_channels: int, resolution: int,
+ residual: bool, enabled: bool):
+ super().__init__()
+ self.use_iconv = conv2d_config.conv.type == "iconv"
+ self._in_channels = in_channels
+ self._out_channels = out_channels
+ self._resolution = resolution
+ self._enabled = enabled
+ self._residual = residual
+ if self.use_iconv:
+ self.beta0 = torch.nn.Parameter(torch.tensor(1.))
+ self.beta1 = torch.nn.Parameter(torch.tensor(1.))
+ else:
+ if self._residual:
+ self.conv = build_base_conv(
+ conv2d_config, False, in_channels // 2,
+ out_channels, kernel_size=1, padding=0)
+ else:
+ self.conv = ConvAct(
+ conv2d_config, in_channels, out_channels,
+ kernel_size=1, padding=0)
+
+ def forward(self, _inp):
+ if not self._enabled:
+ return _inp
+ x, mask, batch = _inp
+ skip_x, skip_mask = batch["unet_features"][self._resolution]
+ assert x.shape == skip_x.shape, (x.shape, skip_x.shape)
+ del batch["unet_features"][self._resolution]
+ if self.use_iconv:
+ denom = skip_mask * self.beta0.relu() + mask * self.beta1.relu() + 1e-8
+ gamma = skip_mask * self.beta0.relu() / denom
+ x = skip_x * gamma + (1 - gamma) * x
+ mask = skip_mask * gamma + (1 - gamma) * mask
+ else:
+ if self._residual:
+ skip_x, skip_mask = self.conv((skip_x, skip_mask))
+ x = (x + skip_x) / np.sqrt(2)
+ if self._probabilistic:
+ mask = (mask + skip_mask) / np.sqrt(2)
+ else:
+ x = torch.cat((x, skip_x), dim=1)
+ x, mask = self.conv((x, mask))
+ return x, mask, batch
+
+ def __repr__(self):
+ return " ".join([
+ self.__class__.__name__,
+ f"In channels={self._in_channels}",
+ f"Out channels={self._out_channels}",
+ f"Residual: {self._residual}",
+ f"Enabled: {self._enabled}"
+ f"IConv: {self.use_iconv}"
+ ])
+
+
+def get_conv(ctype, post_act):
+ type2conv = {
+ "conv": Conv2d,
+ "gconv": GatedConv
+ }
+ # Do not apply for output layer
+ if not post_act and ctype in ["gconv", "iconv"]:
+ return type2conv["conv"]
+ assert ctype in type2conv
+ return type2conv[ctype]
+
+
+def build_base_conv(
+ conv2d_config, post_act: bool, *args, **kwargs) -> nn.Conv2d:
+ for k, v in conv2d_config.conv.items():
+ assert k not in kwargs
+ kwargs[k] = v
+ # Demodulation should not be used for output layers.
+ demodulation = conv2d_config.normalization == "demodulation" and post_act
+ kwargs["demodulation"] = demodulation
+ conv = get_conv(conv2d_config.conv.type, post_act)
+ return conv(*args, **kwargs)
+
+
+def build_post_activation(in_channels, conv2d_config) -> List[nn.Module]:
+ _layers = []
+ negative_slope = conv2d_config.leaky_relu_nslope
+ _layers.append(LeakyReLU(negative_slope, inplace=True))
+ if conv2d_config.normalization == "pixel_wise":
+ _layers.append(PixelwiseNormalization())
+ return _layers
+
+
+def build_avgpool(conv2d_config, kernel_size) -> nn.AvgPool2d:
+ return AvgPool2d(kernel_size)
+
+
+def build_convact(conv2d_config, *args, **kwargs):
+ conv = build_base_conv(conv2d_config, True, *args, **kwargs)
+ out_channels = conv.out_channels
+ post_act = build_post_activation(out_channels, conv2d_config)
+ return nn.Sequential(conv, *post_act)
+
+
+class ConvAct(nn.Module):
+
+ def __init__(self, conv2d_config, *args, **kwargs):
+ super().__init__()
+ self._conv2d_config = conv2d_config
+ conv = build_base_conv(conv2d_config, True, *args, **kwargs)
+ self.in_channels = conv.in_channels
+ self.out_channels = conv.out_channels
+ _layers = [conv]
+ _layers.extend(build_post_activation(self.out_channels, conv2d_config))
+ self.layers = nn.Sequential(*_layers)
+
+ def forward(self, _inp):
+ return self.layers(_inp)
+
+
+class GatedConv(Conv2d):
+
+ def __init__(self, in_channels, out_channels, *args, **kwargs):
+ out_channels *= 2
+ super().__init__(in_channels, out_channels, *args, **kwargs)
+ assert self.out_channels % 2 == 0
+ self.lrelu = nn.LeakyReLU(0.2, inplace=True)
+ self.sigmoid = nn.Sigmoid()
+
+ def conv2d_forward(self, x, weight, bias=True):
+ x_ = super().conv2d_forward(x, weight, bias)
+ x = x_[:, :self.out_channels // 2]
+ y = x_[:, self.out_channels // 2:]
+ x = self.lrelu(x)
+ y = y.sigmoid()
+ assert x.shape == y.shape, f"{x.shape}, {y.shape}"
+ return x * y
+
+
+class BasicBlock(nn.Module):
+
+ def __init__(
+ self, conv2d_config, resolution: int, in_channels: int,
+ out_channels: List[int], residual: bool):
+ super().__init__()
+ assert len(out_channels) == 2
+ self._resolution = resolution
+ self._residual = residual
+ self.out_channels = out_channels
+ _layers = []
+ _in_channels = in_channels
+ for out_ch in out_channels:
+ conv = build_base_conv(
+ conv2d_config, True, _in_channels, out_ch, kernel_size=3,
+ resolution=resolution)
+ _layers.append(conv)
+ _layers.extend(build_post_activation(_in_channels, conv2d_config))
+ _in_channels = out_ch
+ self.layers = nn.Sequential(*_layers)
+ if self._residual:
+ self.residual_conv = build_base_conv(
+ conv2d_config, post_act=False, in_channels=in_channels,
+ out_channels=out_channels[-1],
+ kernel_size=1, padding=0)
+ self.const = 1 / np.sqrt(2)
+
+ def forward(self, _inp):
+ x, mask, batch = _inp
+ y = x
+ mask_ = mask
+ assert y.shape[-1] == self._resolution or y.shape[-1] == 1
+ y, mask = self.layers((x, mask))
+ if self._residual:
+ residual, mask_ = self.residual_conv((x, mask_))
+ y = (y + residual) * self.const
+ mask = (mask + mask_) * self.const
+ return y, mask, batch
+
+ def extra_repr(self):
+ return f"Residual={self._residual}, Resolution={self._resolution}"
+
+
+class PoseNormalize(nn.Module):
+
+ @torch.no_grad()
+ def forward(self, x):
+ return x * 2 - 1
+
+
+class ScalarPoseFCNN(nn.Module):
+
+ def __init__(self, pose_size, hidden_size,
+ output_shape):
+ super().__init__()
+ pose_size = pose_size
+ self._hidden_size = hidden_size
+ output_size = np.prod(output_shape)
+ self.output_shape = output_shape
+ self.pose_preprocessor = nn.Sequential(
+ PoseNormalize(),
+ Linear(pose_size, hidden_size),
+ nn.LeakyReLU(.2),
+ Linear(hidden_size, output_size),
+ nn.LeakyReLU(.2)
+ )
+
+ def forward(self, _inp):
+ x, mask, batch = _inp
+ pose_info = batch["landmarks"]
+ del batch["landmarks"]
+ pose = self.pose_preprocessor(pose_info)
+ pose = pose.view(-1, *self.output_shape)
+ if x.shape[0] == 1 and x.shape[2] == 1 and x.shape[3] == 1:
+ # Analytical normalization propagation
+ pose = pose.mean(dim=2, keepdim=True).mean(dim=3, keepdims=True)
+ x = torch.cat((x, pose), dim=1)
+ return x, mask, batch
+
+ def __repr__(self):
+ return " ".join([
+ self.__class__.__name__,
+ f"hidden_size={self._hidden_size}",
+ f"output shape={self.output_shape}"
+ ])
+
+
+class Attention(nn.Module):
+
+ def __init__(self, in_channels):
+ super(Attention, self).__init__()
+ # Channel multiplier
+ self.in_channels = in_channels
+ self.theta = Conv2d(
+ self.in_channels, self.in_channels // 8, kernel_size=1, padding=0,
+ bias=False)
+ self.phi = Conv2d(
+ self.in_channels, self.in_channels // 8, kernel_size=1, padding=0,
+ bias=False)
+ self.g = Conv2d(
+ self.in_channels, self.in_channels // 2, kernel_size=1, padding=0,
+ bias=False)
+ self.o = Conv2d(
+ self.in_channels // 2, self.in_channels, kernel_size=1, padding=0,
+ bias=False)
+ # Learnable gain parameter
+ self.gamma = nn.Parameter(torch.tensor(0.), requires_grad=True)
+
+ def forward(self, _inp):
+ x, mask, batch = _inp
+ # Apply convs
+ theta, _ = self.theta((x, None))
+ phi = nn.functional.max_pool2d(self.phi((x, None))[0], [2, 2])
+ g = nn.functional.max_pool2d(self.g((x, None))[0], [2, 2])
+ # Perform reshapes
+ theta = theta.view(-1, self.in_channels // 8, x.shape[2] * x.shape[3])
+ phi = phi.view(-1, self.in_channels // 8, x.shape[2] * x.shape[3] // 4)
+ g = g.view(-1, self.in_channels // 2, x.shape[2] * x.shape[3] // 4)
+ # Matmul and softmax to get attention maps
+ beta = nn.functional.softmax(torch.bmm(theta.transpose(1, 2), phi), -1)
+ # Attention map times g path
+
+ o = self.o((torch.bmm(g, beta.transpose(1, 2)).view(-1,
+ self.in_channels // 2, x.shape[2], x.shape[3]), None))[0]
+ return self.gamma * o + x, mask, batch
+
+
+class MSGGenerator(BaseGenerator):
+
+ def __init__(self):
+ super().__init__(512)
+ max_imsize = 128
+ unet = dict(enabled=True, residual=False)
+
+ min_fmap_resolution = 4
+ model_size = 512
+ image_channels = 3
+ pose_size = 14
+ residual = False
+ conv_size = {
+ 4: model_size,
+ 8: model_size,
+ 16: model_size,
+ 32: model_size,
+ 64: model_size//2,
+ 128: model_size//4,
+ 256: model_size//8,
+ 512: model_size//16
+ }
+ self.removable_hooks = []
+ self.rgb_convolutions = nn.ModuleDict()
+ self.max_imsize = max_imsize
+ self._image_channels = image_channels
+ self._min_fmap_resolution = min_fmap_resolution
+ self._residual = residual
+ self._pose_size = pose_size
+ self.current_imsize = max_imsize
+ self._unet_cfg = unet
+ self.concat_input_mask = True
+ self.res2channels = {int(k): v for k, v in conv_size.items()}
+
+ self.conv2d_config = EasyDict(
+ pixel_normalization=True,
+ leaky_relu_nslope=.2,
+ normalization="pixel_wise",
+ conv=dict(
+ type="conv",
+ wsconv=True,
+ gain=1,
+ )
+ )
+ self._init_decoder()
+ self._init_encoder()
+
+ def _init_encoder(self):
+ self.encoder = nn.ModuleList()
+ imsize = self.max_imsize
+ self.from_rgb = build_convact(
+ self.conv2d_config,
+ in_channels=self._image_channels + self.concat_input_mask*2,
+ out_channels=self.res2channels[imsize],
+ kernel_size=1)
+ while imsize >= self._min_fmap_resolution:
+ current_size = self.res2channels[imsize]
+ next_size = self.res2channels[max(imsize//2, self._min_fmap_resolution)]
+ block = BasicBlock(
+ self.conv2d_config, imsize, current_size,
+ [current_size, next_size], self._residual)
+ self.encoder.add_module(f"basic_block{imsize}", block)
+ if imsize != self._min_fmap_resolution:
+ self.encoder.add_module(
+ f"downsample{imsize}", AvgPool2d(2))
+ imsize //= 2
+
+ def _init_decoder(self):
+ self.decoder = nn.ModuleList()
+ self.decoder.add_module(
+ "latent_concat", LatentVariableConcat(self.conv2d_config))
+ if self._pose_size > 0:
+ m = self._min_fmap_resolution
+ pose_shape = (16, m, m)
+ pose_fcnn = ScalarPoseFCNN(self._pose_size, 128, pose_shape)
+ self.decoder.add_module("pose_fcnn", pose_fcnn)
+ imsize = self._min_fmap_resolution
+ self.rgb_convolutions = nn.ModuleDict()
+ while imsize <= self.max_imsize:
+ current_size = self.res2channels[max(imsize//2, self._min_fmap_resolution)]
+ start_size = current_size
+ if imsize == self._min_fmap_resolution:
+ start_size += 32
+ if self._pose_size > 0:
+ start_size += 16
+ else:
+ self.decoder.add_module(f"upsample{imsize}", NearestUpsample())
+ skip = UnetSkipConnection(
+ self.conv2d_config, current_size*2, current_size, imsize,
+ **self._unet_cfg)
+ self.decoder.add_module(f"skip_connection{imsize}", skip)
+ next_size = self.res2channels[imsize]
+ block = BasicBlock(
+ self.conv2d_config, imsize, start_size, [start_size, next_size],
+ residual=self._residual)
+ self.decoder.add_module(f"basic_block{imsize}", block)
+
+ to_rgb = build_base_conv(
+ self.conv2d_config, False, in_channels=next_size,
+ out_channels=self._image_channels, kernel_size=1)
+ self.rgb_convolutions[str(imsize)] = to_rgb
+ imsize *= 2
+ self.norm_constant = len(self.rgb_convolutions)
+
+ def forward_decoder(self, x, mask, batch):
+ imsize_start = max(x.shape[-1] // 2, 1)
+ rgb = torch.zeros(
+ (x.shape[0], self._image_channels,
+ imsize_start, imsize_start),
+ dtype=x.dtype, device=x.device)
+ mask_size = 1
+ mask_out = torch.zeros(
+ (x.shape[0], mask_size,
+ imsize_start, imsize_start),
+ dtype=x.dtype, device=x.device)
+ imsize = self._min_fmap_resolution // 2
+ for module in self.decoder:
+ x, mask, batch = module((x, mask, batch))
+ if isinstance(module, BasicBlock):
+ imsize *= 2
+ rgb = up(rgb)
+ mask_out = up(mask_out)
+ conv = self.rgb_convolutions[str(imsize)]
+ rgb_, mask_ = conv((x, mask))
+ assert rgb_.shape == rgb.shape,\
+ f"rgb_ {rgb_.shape}, rgb: {rgb.shape}"
+ rgb = rgb + rgb_
+ return rgb / self.norm_constant, mask_out
+
+ def forward_encoder(self, x, mask, batch):
+ if self.concat_input_mask:
+ x = torch.cat((x, mask, 1 - mask), dim=1)
+ unet_features = {}
+ x, mask = self.from_rgb((x, mask))
+ for module in self.encoder:
+ x, mask, batch = module((x, mask, batch))
+ if isinstance(module, BasicBlock):
+ unet_features[module._resolution] = (x, mask)
+ return x, mask, unet_features
+
+ def forward(
+ self,
+ condition,
+ mask, keypoints=None, z=None,
+ **kwargs):
+ keypoints = keypoints[:, :, :2].flatten(start_dim=1).clip(-1, 1)
+ if z is None:
+ z = self.get_z(condition)
+ z = z.view(-1, 32, 4, 4)
+ batch = dict(
+ landmarks=keypoints,
+ z=z)
+ orig_mask = mask
+ x, mask, unet_features = self.forward_encoder(condition, mask, batch)
+ batch = dict(
+ landmarks=keypoints,
+ z=z,
+ unet_features=unet_features)
+ x, mask = self.forward_decoder(x, mask, batch)
+ x = condition * orig_mask + (1 - orig_mask) * x
+ return dict(img=x)
+
+ def load_state_dict(self, state_dict, strict=True):
+ if "parameters" in state_dict:
+ state_dict = state_dict["parameters"]
+ old_checkpoint = any("basic_block0" in key for key in state_dict)
+ if not old_checkpoint:
+ return super().load_state_dict(state_dict, strict=strict)
+ mapping = {}
+ imsize = self._min_fmap_resolution
+ i = 0
+ while imsize <= self.max_imsize:
+ old_key = f"decoder.basic_block{i}."
+ new_key = f"decoder.basic_block{imsize}."
+ mapping[old_key] = new_key
+ if i >= 1:
+ old_key = old_key.replace("basic_block", "skip_connection")
+ new_key = new_key.replace("basic_block", "skip_connection")
+ mapping[old_key] = new_key
+ mapping[old_key] = new_key
+ old_key = f"encoder.basic_block{i}."
+ new_key = f"encoder.basic_block{imsize}."
+ mapping[old_key] = new_key
+ old_key = "from_rgb.conv.layers.0."
+ new_key = "from_rgb.0."
+ mapping[old_key] = new_key
+ i += 1
+ imsize *= 2
+ new_sd = {}
+ for key, value in state_dict.items():
+ old_key = key
+ if "from_rgb" in key:
+ new_sd[key.replace("encoder.", "").replace(".conv.layers", "")] = value
+ continue
+ for subkey, new_subkey in mapping.items():
+ if subkey in key:
+ old_key = key
+ key = key.replace(subkey, new_subkey)
+
+ break
+ if "decoder.to_rgb" in key:
+ continue
+
+ new_sd[key] = value
+ return super().load_state_dict(new_sd, strict=strict)
+
+ def update_w(self, *args, **kwargs):
+ return
diff --git a/project/models/deprecated_deep_privacy2/dp2/generator/dummy_generators.py b/project/models/deprecated_deep_privacy2/dp2/generator/dummy_generators.py
new file mode 100644
index 0000000..c81b4d4
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/generator/dummy_generators.py
@@ -0,0 +1,60 @@
+import torch
+from .base import BaseGenerator
+from torchvision.transforms.functional import gaussian_blur
+import torch.nn.functional as F
+
+
+class PixelationGenerator(BaseGenerator):
+
+ def __init__(self, pixelation_size, **kwargs):
+ super().__init__(z_channels=0)
+ self.pixelation_size = pixelation_size
+ self.z_channels = 0
+ self.latent_space = None
+
+ def forward(self, img, condition, mask, **kwargs):
+ old_shape = img.shape[-2:]
+ img = F.interpolate(img, size=(
+ self.pixelation_size, self.pixelation_size), mode="bilinear", align_corners=True)
+ img = F.interpolate(img, size=old_shape, mode="bilinear", align_corners=True)
+ out = img*(1-mask) + condition*mask
+ return {"img": out}
+
+
+class MaskOutGenerator(BaseGenerator):
+
+ def __init__(self, noise: str, **kwargs):
+ super().__init__(z_channels=0)
+ self.noise = noise
+ self.z_channels = 0
+ assert self.noise in ["rand", "constant"]
+ self.latent_space = None
+
+ def forward(self, img, condition, mask, **kwargs):
+
+ if self.noise == "constant":
+ img = torch.zeros_like(img)
+ elif self.noise == "rand":
+ img = torch.rand_like(img)
+ out = img*(1-mask) + condition*mask
+ return {"img": out}
+
+
+class IdentityGenerator(BaseGenerator):
+
+ def __init__(self):
+ super().__init__(z_channels=0)
+
+ def forward(self, img, condition, mask, **kwargs):
+ return dict(img=img)
+
+
+class GaussianBlurGenerator(BaseGenerator):
+
+ def __init__(self):
+ super().__init__(z_channels=0)
+ self.sigma = 7
+
+ def forward(self, img, condition, mask, **kwargs):
+ img_blur = gaussian_blur(img, kernel_size=min(self.sigma*3, img.shape[-1]), sigma=self.sigma)
+ return dict(img=img * mask + (1-mask) * img_blur)
diff --git a/project/models/deprecated_deep_privacy2/dp2/generator/stylegan_unet.py b/project/models/deprecated_deep_privacy2/dp2/generator/stylegan_unet.py
new file mode 100644
index 0000000..6c3dfc4
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/generator/stylegan_unet.py
@@ -0,0 +1,211 @@
+import torch
+import numpy as np
+from dp2.layers import Sequential
+from dp2.layers.sg2_layers import Conv2d, FullyConnectedLayer, ResidualBlock
+from .base import BaseStyleGAN
+from typing import List, Tuple
+from .utils import spatial_embed_keypoints, mask_output
+
+
+def get_chsize(imsize, cnum, max_imsize, max_cnum_mul):
+ n = int(np.log2(max_imsize) - np.log2(imsize))
+ mul = min(2**n, max_cnum_mul)
+ ch = cnum * mul
+ return int(ch)
+
+
+class StyleGANUnet(BaseStyleGAN):
+ def __init__(
+ self,
+ scale_grad: bool,
+ im_channels: int,
+ min_fmap_resolution: int,
+ imsize: List[int],
+ cnum: int,
+ max_cnum_mul: int,
+ mask_output: bool,
+ conv_clamp: int,
+ input_cse: bool,
+ cse_nc: int,
+ n_middle_blocks: int,
+ input_keypoints: bool,
+ n_keypoints: int,
+ input_keypoint_indices: Tuple[int],
+ fix_errors: bool,
+ **kwargs
+ ) -> None:
+ super().__init__(**kwargs)
+ self.n_keypoints = n_keypoints
+ self.input_keypoint_indices = list(input_keypoint_indices)
+ self.input_keypoints = input_keypoints
+ assert not (input_cse and input_keypoints)
+ cse_nc = 0 if cse_nc is None else cse_nc
+ self.imsize = imsize
+ self._cnum = cnum
+ self._max_cnum_mul = max_cnum_mul
+ self._min_fmap_resolution = min_fmap_resolution
+ self._image_channels = im_channels
+ self._max_imsize = max(imsize)
+ self.input_cse = input_cse
+ self.gain_unet = np.sqrt(1/3)
+ n_levels = int(np.log2(self._max_imsize) - np.log2(min_fmap_resolution))+1
+ encoder_layers = []
+ self.from_rgb = Conv2d(
+ im_channels + 1 + input_cse*(cse_nc+1) + input_keypoints*len(self.input_keypoint_indices),
+ cnum, 1
+ )
+ for i in range(n_levels): # Encoder layers
+ resolution = [x//2**i for x in imsize]
+ in_ch = get_chsize(max(resolution), cnum, self._max_imsize, max_cnum_mul)
+ second_ch = in_ch
+ out_ch = get_chsize(max(resolution)//2, cnum, self._max_imsize, max_cnum_mul)
+ down = 2
+
+ if i == 0: # first (lowest) block. Downsampling is performed at the start of the block
+ down = 1
+ if i == n_levels - 1:
+ out_ch = second_ch
+ block = ResidualBlock(in_ch, out_ch, down=down, conv_clamp=conv_clamp, fix_residual=fix_errors)
+ encoder_layers.append(block)
+ self._encoder_out_shape = [
+ get_chsize(min_fmap_resolution, cnum, self._max_imsize, max_cnum_mul),
+ *resolution]
+
+ self.encoder = torch.nn.ModuleList(encoder_layers)
+
+ # initialize decoder
+ decoder_layers = []
+ for i in range(n_levels):
+ resolution = [x//2**(n_levels-1-i) for x in imsize]
+ in_ch = get_chsize(max(resolution)//2, cnum, self._max_imsize, max_cnum_mul)
+ out_ch = get_chsize(max(resolution), cnum, self._max_imsize, max_cnum_mul)
+ if i == 0: # first (lowest) block
+ in_ch = get_chsize(max(resolution), cnum, self._max_imsize, max_cnum_mul)
+
+ up = 1
+ if i != n_levels - 1:
+ up = 2
+ block = ResidualBlock(
+ in_ch, out_ch, conv_clamp=conv_clamp, gain_out=np.sqrt(1/3),
+ w_dim=self.style_net.w_dim, norm=True, up=up,
+ fix_residual=fix_errors
+ )
+ decoder_layers.append(block)
+ if i != 0:
+ unet_block = Conv2d(
+ in_ch, in_ch, kernel_size=1, conv_clamp=conv_clamp, norm=True,
+ gain=np.sqrt(1/3) if fix_errors else np.sqrt(.5))
+ setattr(self, f"unet_block{i}", unet_block)
+
+ # Initialize "middle blocks" that do not have down/up sample
+ middle_blocks = []
+ for i in range(n_middle_blocks):
+ ch = get_chsize(min_fmap_resolution, cnum, self._max_imsize, max_cnum_mul)
+ block = ResidualBlock(
+ ch, ch, conv_clamp=conv_clamp, gain_out=np.sqrt(.5) if fix_errors else np.sqrt(1/3),
+ w_dim=self.style_net.w_dim, norm=True,
+ )
+ middle_blocks.append(block)
+ if n_middle_blocks != 0:
+ self.middle_blocks = Sequential(*middle_blocks)
+ self.decoder = torch.nn.ModuleList(decoder_layers)
+ self.to_rgb = Conv2d(cnum, im_channels, 1, activation="linear", conv_clamp=conv_clamp)
+ # Initialize "middle blocks" that do not have down/up sample
+ self.decoder = torch.nn.ModuleList(decoder_layers)
+ self.scale_grad = scale_grad
+ self.mask_output = mask_output
+
+ def forward_dec(self, x, w, unet_features, condition, mask, s, **kwargs):
+ for i, layer in enumerate(self.decoder):
+ if i != 0:
+ unet_layer = getattr(self, f"unet_block{i}")
+ x = x + unet_layer(unet_features[-i])
+ x = layer(x, w=w, s=s)
+ x = self.to_rgb(x)
+ if self.mask_output:
+ x = mask_output(True, condition, x, mask)
+ return dict(img=x)
+
+ def forward_enc(self, condition, mask, embedding, keypoints, E_mask, **kwargs):
+ if self.input_cse:
+ x = torch.cat((condition, mask, embedding, E_mask), dim=1)
+ else:
+ x = torch.cat((condition, mask), dim=1)
+ if self.input_keypoints:
+ keypoints = keypoints[:, self.input_keypoint_indices]
+ one_hot_pose = spatial_embed_keypoints(keypoints, x)
+ x = torch.cat((x, one_hot_pose), dim=1)
+ x = self.from_rgb(x)
+
+ unet_features = []
+ for i, layer in enumerate(self.encoder):
+ x = layer(x)
+ if i != len(self.encoder)-1:
+ unet_features.append(x)
+ if hasattr(self, "middle_blocks"):
+ for layer in self.middle_blocks:
+ x = layer(x)
+ return x, unet_features
+
+ def forward(
+ self, condition, mask,
+ z=None, embedding=None, w=None, update_emas=False, x=None,
+ s=None,
+ keypoints=None,
+ unet_features=None,
+ E_mask=None,
+ **kwargs):
+ # Used to skip sampling from encoder in inference. E.g. for w projection.
+ if x is not None and unet_features is not None:
+ assert not self.training
+ else:
+ x, unet_features = self.forward_enc(condition, mask, embedding, keypoints, E_mask, **kwargs)
+ if w is None:
+ if z is None:
+ z = self.get_z(condition)
+ w = self.get_w(z, update_emas=update_emas)
+ return self.forward_dec(x, w, unet_features, condition, mask, s, **kwargs)
+
+
+class ComodStyleUNet(StyleGANUnet):
+
+ def __init__(self, min_comod_res=4, lr_multiplier_comod=1, **kwargs) -> None:
+ super().__init__(**kwargs)
+ min_fmap = min(self._encoder_out_shape[1:])
+ enc_out_ch = self._encoder_out_shape[0]
+ n_down = int(np.ceil(np.log2(min_fmap) - np.log2(min_comod_res)))
+ comod_layers = []
+ in_ch = enc_out_ch
+ for i in range(n_down):
+ comod_layers.append(Conv2d(enc_out_ch, 256, kernel_size=3, down=2, lr_multiplier=lr_multiplier_comod))
+ in_ch = 256
+ if n_down == 0:
+ comod_layers = [Conv2d(in_ch, 256, kernel_size=3)]
+ comod_layers.append(torch.nn.Flatten())
+ out_res = [x//2**n_down for x in self._encoder_out_shape[1:]]
+ in_ch_fc = np.prod(out_res) * 256
+ comod_layers.append(FullyConnectedLayer(in_ch_fc, 512, lr_multiplier=lr_multiplier_comod))
+ self.comod_block = Sequential(*comod_layers)
+ self.comod_fc = FullyConnectedLayer(
+ 512+self.style_net.w_dim, self.style_net.w_dim, lr_multiplier=lr_multiplier_comod)
+
+ def forward_dec(self, x, w, unet_features, condition, mask, **kwargs):
+ y = self.comod_block(x)
+ y = torch.cat((y, w), dim=1)
+ y = self.comod_fc(y)
+ for i, layer in enumerate(self.decoder):
+ if i != 0:
+ unet_layer = getattr(self, f"unet_block{i}")
+ x = x + unet_layer(unet_features[-i], gain=np.sqrt(.5))
+ x = layer(x, w=y)
+ x = self.to_rgb(x)
+ if self.mask_output:
+ x = mask_output(True, condition, x, mask)
+ return dict(img=x)
+
+ def get_comod_y(self, batch, w):
+ x, unet_features = self.forward_enc(**batch)
+ y = self.comod_block(x)
+ y = torch.cat((y, w), dim=1)
+ y = self.comod_fc(y)
+ return y
diff --git a/project/models/deprecated_deep_privacy2/dp2/generator/triagan.py b/project/models/deprecated_deep_privacy2/dp2/generator/triagan.py
new file mode 100644
index 0000000..0cce5a6
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/generator/triagan.py
@@ -0,0 +1,563 @@
+from functools import partial
+from typing import Iterable, List, Tuple
+import numpy as np
+import torch
+import torch.nn as nn
+from .base import BaseStyleGAN
+from sg3_torch_utils.ops import bias_act
+from dp2.layers import Sequential
+import torch.nn.functional as F
+from sg3_torch_utils.ops import fma, upfirdn2d
+from resize_right import resize as resize_r
+from .utils import spatial_embed_keypoints
+
+
+class Upfirdn2d(torch.nn.Module):
+ def __init__(self, down=1, up=1):
+ super().__init__()
+ self.register_buffer("resample_filter", upfirdn2d.setup_filter([1, 3, 3, 1]))
+ fw, fh = upfirdn2d._get_filter_size(self.resample_filter)
+ px0, px1, py0, py1 = upfirdn2d._parse_padding(0)
+ self.down = down
+ self.up = up
+ if up > 1:
+ px0 += (fw + up - 1) // 2
+ px1 += (fw - up) // 2
+ py0 += (fh + up - 1) // 2
+ py1 += (fh - up) // 2
+ if down > 1:
+ px0 += (fw - down + 1) // 2
+ px1 += (fw - down) // 2
+ py0 += (fh - down + 1) // 2
+ py1 += (fh - down) // 2
+ self.padding = [px0, px1, py0, py1]
+ self.gain = up**2
+ assert up <= 2
+
+ def forward(self, x, *args):
+ if isinstance(x, dict):
+ x = {k: v for k, v in x.items()}
+ x["x"] = upfirdn2d.upfirdn2d(
+ x["x"],
+ self.resample_filter,
+ down=self.down,
+ padding=self.padding,
+ up=self.up,
+ gain=self.gain,
+ )
+ return x
+ x = upfirdn2d.upfirdn2d(
+ x,
+ self.resample_filter,
+ down=self.down,
+ padding=self.padding,
+ up=self.up,
+ gain=self.gain,
+ )
+ if len(args) == 0:
+ return x
+ return (x, *args)
+
+
+class Identity(nn.Module):
+ def __init__(self) -> None:
+ super().__init__()
+
+ def forward(self, x, *args, **kwargs):
+ return x
+
+
+class FullyConnectedLayer(torch.nn.Module):
+ def __init__(
+ self,
+ in_features, # Number of input features.
+ out_features, # Number of output features.
+ bias=True, # Apply additive bias before the activation function?
+ activation="linear", # Activation function: 'relu', 'lrelu', etc.
+ lr_multiplier=1, # Learning rate multiplier.
+ bias_init=0, # Initial value for the additive bias.
+ ):
+ super().__init__()
+ self.repr = dict(
+ in_features=in_features,
+ out_features=out_features,
+ bias=bias,
+ activation=activation,
+ lr_multiplier=lr_multiplier,
+ bias_init=bias_init,
+ )
+ self.activation = activation
+ self.weight = torch.nn.Parameter(
+ torch.randn([out_features, in_features]) / lr_multiplier
+ )
+ self.bias = (
+ torch.nn.Parameter(torch.full([out_features], np.float32(bias_init)))
+ if bias
+ else None
+ )
+ self.weight_gain = lr_multiplier / np.sqrt(in_features)
+ self.bias_gain = lr_multiplier
+ self.in_features = in_features
+ self.out_features = out_features
+
+ def forward(self, x):
+ w = self.weight * self.weight_gain
+ b = self.bias
+ if b is not None:
+ if self.bias_gain != 1:
+ b = b * self.bias_gain
+ x = F.linear(x, w)
+ x = bias_act.bias_act(x, b, act=self.activation)
+ return x
+
+ def extra_repr(self) -> str:
+ return ", ".join([f"{key}={item}" for key, item in self.repr.items()])
+
+
+class Conv2d(torch.nn.Module):
+ def __init__(
+ self,
+ in_channels,
+ out_channels,
+ kernel_size=3,
+ activation="lrelu",
+ bias=True,
+ norm=None,
+ lr_multiplier=1,
+ bias_init=0,
+ w_dim=None,
+ gain=1,
+ padding=None,
+ resolution=None,
+ use_noise=False,
+ ):
+ super().__init__()
+ if norm == torch.nn.InstanceNorm2d:
+ self.norm = torch.nn.InstanceNorm2d(None)
+ elif isinstance(norm, torch.nn.Module):
+ self.norm = norm
+ elif norm == "gnorm":
+ self.norm = nn.GroupNorm(32, in_channels)
+ elif norm:
+ self.norm = torch.nn.InstanceNorm2d(None)
+ elif norm == False:
+ pass
+ elif norm is not None:
+ raise ValueError(f"norm not supported: {norm}")
+ self.activation = activation
+ self.out_channels = out_channels
+ self.in_channels = in_channels
+ self.padding = kernel_size // 2 if padding is None else padding
+ self.repr = dict(
+ in_channels=in_channels,
+ out_channels=out_channels,
+ kernel_size=kernel_size,
+ activation=activation,
+ bias=bias,
+ )
+ self.gain = gain
+ self.register_buffer(
+ "act_gain",
+ torch.tensor(bias_act.activation_funcs[activation].def_gain).float(),
+ persistent=False,
+ )
+ self.weight_gain = lr_multiplier / np.sqrt(in_channels * (kernel_size**2))
+ self.weight = torch.nn.Parameter(
+ torch.randn([out_channels, in_channels, kernel_size, kernel_size])
+ )
+ self.bias = (
+ torch.nn.Parameter(torch.zeros([out_channels]) + bias_init)
+ if bias
+ else None
+ )
+ self.bias_gain = lr_multiplier
+ if w_dim is not None:
+ self.affine = FullyConnectedLayer(w_dim, in_channels, bias_init=1)
+ self.affine_beta = FullyConnectedLayer(w_dim, in_channels, bias_init=0)
+
+ if use_noise:
+ self.resolution = resolution
+ self.register_buffer("noise_const", torch.randn(list(resolution)))
+ self.noise_strength = torch.nn.Parameter(torch.zeros([]))
+ self.use_noise = use_noise
+
+ def forward(self, x, w=None, s=None):
+ # Implements normalization -> mod -> conv -> activatio
+ if hasattr(self, "norm"):
+ x = self.norm(x)
+ if hasattr(self, "affine") and s is None:
+ gamma = self.affine(w).view(-1, self.in_channels, 1, 1)
+ beta = self.affine_beta(w).view(-1, self.in_channels, 1, 1)
+ x = fma.fma(x, gamma, beta)
+ elif hasattr(self, "affine"):
+ s = next(s)
+ s = s[: self.in_channels * 2]
+ gamma, beta = s.view(
+ 1,
+ -1,
+ 1,
+ 1,
+ ).chunk(2, dim=1)
+ x = fma.fma(x, gamma, beta)
+ act_gain = self.act_gain
+ x = bias_act.bias_act(x, None, act=self.activation, gain=act_gain)
+ b = self.bias * self.bias_gain * self.gain if self.bias is not None else None
+ w = self.weight * self.weight_gain * self.gain
+ x = F.conv2d(input=x, weight=w, padding=self.padding, bias=b)
+
+ if self.training and self.use_noise:
+ noise = (
+ torch.randn([x.shape[0], 1, *self.resolution], device=x.device)
+ * self.noise_strength
+ )
+ elif self.use_noise:
+ noise = self.noise_const * self.noise_strength
+ if self.use_noise:
+ x = x + noise
+ return x
+
+ def extra_repr(self) -> str:
+ return ", ".join([f"{key}={item}" for key, item in self.repr.items()])
+
+
+class SG2ResidualBlock(torch.nn.Module):
+ def __init__(
+ self,
+ in_channels, # Number of input channels, 0 = first block.
+ out_channels: List[int], # Number of output channels.
+ skip_gain=np.sqrt(0.5),
+ layer_scale=False,
+ **layer_kwargs, # Arguments for conv layer.
+ ):
+ super().__init__()
+ self.in_channels = in_channels
+ self.out_channels = out_channels
+
+ self.conv0 = Conv2d(in_channels, out_channels[0], **layer_kwargs)
+ self.conv1 = Conv2d(
+ out_channels[0], out_channels[1], **layer_kwargs, gain=skip_gain
+ )
+ self.skip = Conv2d(
+ in_channels,
+ out_channels[1],
+ kernel_size=1,
+ bias=False,
+ gain=skip_gain,
+ activation="linear",
+ )
+ if layer_scale:
+ self.layer_scale = nn.Parameter(
+ torch.zeros((1, out_channels[1], 1, 1), dtype=torch.float32) + 1e-5
+ )
+
+ def forward(self, x, w=None, **layer_kwargs):
+ y = x
+ if hasattr(self, "skip"):
+ y = self.skip(x)
+ x = self.conv0(x, w, **layer_kwargs)
+ x = self.conv1(x, w, **layer_kwargs)
+ if hasattr(self, "layer_scale"):
+ x = x * self.layer_scale
+ return y + x
+
+
+def cast_tuple(val, length=None):
+ if isinstance(val, Iterable) and not isinstance(val, str):
+ val = tuple(val)
+ if not isinstance(val, tuple):
+ val = (val,) * length
+ assert len(val) == length, (val, length)
+ return val
+
+
+class Encoder(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ dim_mults: Tuple[int],
+ num_resnet_blocks, # Number of resnet blocks per resolution
+ w_dim: int,
+ norm_enc: bool,
+ imsize: Tuple[int],
+ use_noise: bool,
+ layer_scale: bool,
+ ) -> None:
+ super().__init__()
+ self.n_layers = len(dim_mults)
+ n_layers = len(dim_mults)
+ dims = [dim * m for m in dim_mults]
+ enc_blk = partial(
+ SG2ResidualBlock,
+ norm=norm_enc,
+ w_dim=w_dim,
+ use_noise=use_noise,
+ layer_scale=layer_scale,
+ )
+ layers = []
+ # Currently up/down sampling is done by bilinear upsampling.
+ # This can be simplified by replacing it with a strided upsampling layer...
+
+ for lidx in range(n_layers):
+ resolution = [r // (2**lidx) for r in imsize]
+
+ dim_in = dims[lidx]
+ dim_out = dims[min(lidx + 1, n_layers - 1)]
+ res_blocks = nn.ModuleList()
+ for i in range(num_resnet_blocks[lidx]):
+ cur_dim = dim_out if i == num_resnet_blocks[lidx] - 1 else dim_in
+ gain = np.sqrt(1 / 2)
+ block = enc_blk(
+ dim_in,
+ [dim_in, cur_dim],
+ skip_gain=gain,
+ resolution=resolution,
+ )
+ res_blocks.append(block)
+ layers.append(res_blocks)
+ layers.reverse()
+ self.layers = nn.ModuleList(layers)
+
+ self.downsample = Upfirdn2d(down=2)
+
+ def forward(self, x, w, s):
+ unet_features = []
+ for lidx, res_blocks in enumerate(self.layers[::-1]):
+ is_last = lidx == len(self.layers) - 1
+ for block in res_blocks:
+ x = block(x, w=w, s=s)
+ unet_features.append(x)
+ if not is_last:
+ x = self.downsample(x)
+ return x, unet_features
+
+
+class Decoder(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ dim_mults: tuple,
+ num_resnet_blocks, # Number of resnet blocks per resolution
+ n_middle_blocks: int,
+ w_dim: int,
+ norm_dec: str,
+ im_channels: int,
+ imsize: Tuple[int],
+ use_noise: bool,
+ layer_scale: bool,
+ ) -> None:
+ super().__init__()
+ dims = [dim * m for m in dim_mults]
+ n_layers = len(dims)
+ # initialize decoder
+ self.layers = nn.ModuleList()
+ dec_blk = partial(
+ SG2ResidualBlock,
+ norm=norm_dec,
+ w_dim=w_dim,
+ use_noise=use_noise,
+ layer_scale=layer_scale,
+ )
+ self.unet_layers = torch.nn.ModuleList()
+ for lidx in range(n_layers): # Iterate from lowest resolution
+ dim_in = dims[min(-lidx, -1)]
+ dim_out = dims[-1 - lidx]
+ res_blocks = nn.ModuleList()
+ unet_skips = nn.ModuleList()
+ for i in range(num_resnet_blocks[-lidx - 1]):
+ resolution = [r//(2**(n_layers-1-lidx)) for r in imsize]
+ is_first = i == 0
+ has_unet = is_first and lidx != 0
+ cur_dim = dim_in if is_first else dim_out
+ n = 2
+ n += int(has_unet)
+ gain = np.sqrt(1 / n)
+ block = dec_blk(
+ cur_dim, [cur_dim, dim_out], skip_gain=gain, resolution=resolution
+ )
+ res_blocks.append(block)
+ if has_unet:
+ unet_block = Conv2d(
+ cur_dim,
+ cur_dim,
+ kernel_size=1,
+ norm=True,
+ gain=gain,
+ bias=False,
+ )
+ unet_skips.append(unet_block)
+ else:
+ unet_skips.append(torch.nn.Identity())
+ self.layers.append(res_blocks)
+ self.unet_layers.append(unet_skips)
+ self.upsample = Upfirdn2d(up=2)
+
+ middle_blocks = []
+ for i in range(n_middle_blocks):
+ block = dec_blk(
+ dims[-1],
+ [dims[-1], dims[-1]],
+ skip_gain=np.sqrt(0.5),
+ resolution=[r // (2 ** (n_layers - 1)) for r in imsize],
+ )
+ middle_blocks.append(block)
+ if n_middle_blocks != 0:
+ self.middle_blocks = Sequential(*middle_blocks)
+ self.to_rgb = Conv2d(dim_out, im_channels, 1, activation="linear")
+ self.im_channels = im_channels
+
+ def forward(self, x, w, unet_features, s):
+ if hasattr(self, "middle_blocks"):
+ x = self.middle_blocks(x, w=w, s=s)
+ features = []
+ unet_features = iter(reversed(unet_features))
+ for i, (unet_skip, res_blocks) in enumerate(zip(self.unet_layers, self.layers)):
+ is_last = i == len(self.layers) - 1
+ for (
+ skip,
+ block,
+ ) in zip(unet_skip, res_blocks):
+ skip_x = next(unet_features)
+ if not isinstance(skip, torch.nn.Identity):
+ skip_x = skip(skip_x)
+ x = x + skip_x
+ x = block(x, w=w, s=s)
+ features.append(x)
+ if not is_last:
+ x = self.upsample(x)
+ x = self.to_rgb(x)
+ return x, features
+
+
+class TriaGAN(BaseStyleGAN):
+ def __init__(
+ self,
+ imsize: Tuple[int],
+ im_channels: int,
+ dim: int,
+ dim_mults: tuple,
+ num_resnet_blocks, # Number of resnet blocks per resolution
+ n_middle_blocks: int,
+ z_channels: int,
+ w_dim: int,
+ norm_enc: bool,
+ norm_dec: str,
+ use_maskrcnn_mask: bool,
+ input_keypoints: bool,
+ n_keypoints: int,
+ input_keypoint_indices: Tuple[int],
+ style_net: nn.Module,
+ input_joint=False,
+ latent_space=None,
+ use_noise=True,
+ layer_scale=False,
+ **kwargs,
+ ) -> None:
+ super().__init__(z_channels, w_dim, **kwargs)
+ self.style_net = style_net
+ self.n_keypoints = n_keypoints
+ self.input_keypoint_indices = list(input_keypoint_indices)
+ self.input_keypoints = input_keypoints
+ self.imsize = tuple(imsize)
+ self.input_joint = input_joint
+ self.dim = dim
+ self.dim_mults = dim_mults
+ if latent_space is not None:
+ self.latent_space = latent_space
+ assert self.latent_space in ["W", "W_kp", "Z"]
+ n_layers = len(dim_mults)
+ num_resnet_blocks = cast_tuple(num_resnet_blocks, n_layers)
+ self.from_rgb = Conv2d(
+ im_channels
+ + 2
+ + 2 * int(use_maskrcnn_mask)
+ + self.input_keypoints * len(input_keypoint_indices)
+ + input_joint * 6,
+ dim,
+ 7,
+ activation="linear",
+ )
+ self.from_rgb.weight_gain = 1 / np.sqrt(
+ (3 + 1 + use_maskrcnn_mask + self.input_keypoints + input_joint) * (7**2)
+ )
+
+ self.use_maskrcnn_mask = use_maskrcnn_mask
+ self.encoder = Encoder(
+ dim,
+ dim_mults,
+ num_resnet_blocks,
+ w_dim,
+ norm_enc,
+ imsize=imsize,
+ layer_scale=layer_scale,
+ use_noise=False
+ )
+ self.decoder = Decoder(
+ dim,
+ dim_mults,
+ num_resnet_blocks,
+ n_middle_blocks,
+ w_dim,
+ norm_dec,
+ im_channels=im_channels,
+ use_noise=use_noise,
+ imsize=imsize,
+ layer_scale=layer_scale,
+ )
+
+ def get_input(
+ self, condition, mask, maskrcnn_mask, keypoints, joint_map, **kwargs
+ ) -> torch.Tensor:
+ if self.use_maskrcnn_mask:
+ x = torch.cat(
+ (condition, mask, 1 - mask, maskrcnn_mask, 1 - maskrcnn_mask), dim=1
+ )
+ else:
+ x = torch.cat((condition, mask, 1 - mask), dim=1)
+
+ if self.input_keypoints:
+ keypoints = keypoints[:, self.input_keypoint_indices]
+ one_hot_pose = spatial_embed_keypoints(keypoints, x).to(x.device)
+ x = torch.cat((x, one_hot_pose), dim=1)
+ if self.input_joint:
+ joint_map_oh = torch.zeros(
+ (joint_map.shape[0], 6 + 1, *joint_map.shape[-2:]),
+ device=joint_map.device,
+ dtype=torch.float32,
+ )
+ joint_map_oh.scatter_(1, joint_map.long(), 1)
+ x = torch.cat((x, joint_map_oh[:, 1:]), dim=1) # Zero is BG
+ return x
+
+ def forward(
+ self,
+ condition,
+ mask,
+ maskrcnn_mask=None,
+ img=None,
+ z=None,
+ w=None,
+ update_emas=False,
+ keypoints=None,
+ s=None,
+ joint_map=None,
+ **kwargs,
+ ):
+ if z is None:
+ z = self.get_z(condition)
+
+ if w is None and s is None:
+ w = self.style_net(z, keypoints=keypoints, update_emas=update_emas)
+ x = self.get_input(
+ condition, mask, maskrcnn_mask, keypoints, joint_map, **kwargs
+ )
+ x = self.from_rgb(x)
+ x, unet_features = self.encoder(x, w, s=s)
+
+ x, _ = self.decoder(x, w, unet_features, s=s)
+ unmasked = x
+ x = mask * img + (1 - mask) * x
+ out = dict(img=x, unmasked=unmasked)
+ return out
+
+ def get_w(self, z, update_emas, keypoints=None):
+ return self.style_net(z, update_emas=update_emas, keypoints=keypoints)
diff --git a/project/models/deprecated_deep_privacy2/dp2/generator/utils.py b/project/models/deprecated_deep_privacy2/dp2/generator/utils.py
new file mode 100644
index 0000000..ec5a983
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/generator/utils.py
@@ -0,0 +1,49 @@
+import torch
+import tops
+import torch
+from torch.cuda.amp import custom_bwd, custom_fwd
+
+
+@torch.no_grad()
+def spatial_embed_keypoints(keypoints: torch.Tensor, x):
+ tops.assert_shape(keypoints, (None, None, 3))
+ B, N_K, _ = keypoints.shape
+ H, W = x.shape[-2:]
+ keypoint_spatial = torch.zeros(keypoints.shape[0], N_K, H, W, device=keypoints.device, dtype=torch.float32)
+ x, y, visible = keypoints.chunk(3, dim=2)
+ x = (x * W).round().long().clamp(0, W-1)
+ y = (y * H).round().long().clamp(0, H-1)
+ kp_idx = torch.arange(0, N_K, 1, device=keypoints.device, dtype=torch.long).view(1, -1, 1).repeat(B, 1, 1)
+ pos = (kp_idx*(H*W) + y*W + x + 1)
+ # Offset all by 1 to index invisible keypoints as 0
+ pos = (pos * visible.round().long()).squeeze(dim=-1)
+ keypoint_spatial = torch.zeros(keypoints.shape[0], N_K*H*W+1, device=keypoints.device, dtype=torch.float32)
+ keypoint_spatial.scatter_(1, pos, 1)
+ keypoint_spatial = keypoint_spatial[:, 1:].view(-1, N_K, H, W)
+ return keypoint_spatial
+
+
+class MaskOutput(torch.autograd.Function):
+
+ @staticmethod
+ @custom_fwd
+ def forward(ctx, x_real, x_fake, mask):
+ ctx.save_for_backward(mask)
+ out = x_real * mask + (1-mask) * x_fake
+ return out
+
+ @staticmethod
+ @custom_bwd
+ def backward(ctx, grad_output):
+ fake_grad = grad_output
+ mask, = ctx.saved_tensors
+ fake_grad = fake_grad * (1 - mask)
+ known_percentage = mask.view(mask.shape[0], -1).mean(dim=1)
+ fake_grad = fake_grad / (1-known_percentage).view(-1, 1, 1, 1)
+ return None, fake_grad, None
+
+
+def mask_output(scale_grad, x_real, x_fake, mask):
+ if scale_grad:
+ return MaskOutput.apply(x_real, x_fake, mask)
+ return x_real * mask + (1-mask) * x_fake
diff --git a/project/models/deprecated_deep_privacy2/dp2/infer.py b/project/models/deprecated_deep_privacy2/dp2/infer.py
new file mode 100644
index 0000000..11d4979
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/infer.py
@@ -0,0 +1,81 @@
+import tops
+import torch
+from tops import checkpointer
+from tops.config import instantiate
+from tops.logger import warn
+from dp2.generator.deep_privacy1 import MSGGenerator
+
+
+def load_generator_state(ckpt, G: torch.nn.Module, ckpt_mapper=None):
+ state = ckpt["EMA_generator"] if "EMA_generator" in ckpt else ckpt["running_average_generator"]
+ if ckpt_mapper is not None:
+ state = ckpt_mapper(state)
+ if isinstance(G, MSGGenerator):
+ G.load_state_dict(state)
+ else:
+ load_state_dict(G, state)
+ tops.logger.log(f"Generator loaded, num parameters: {tops.num_parameters(G)/1e6}M")
+ if "w_centers" in ckpt:
+ G.style_net.register_buffer("w_centers", ckpt["w_centers"])
+ tops.logger.log(f"W cluster centers loaded. Number of centers: {len(G.style_net.w_centers)}")
+ if "style_net.w_centers" in state:
+ G.style_net.register_buffer("w_centers", state["style_net.w_centers"])
+ tops.logger.log(f"W cluster centers loaded. Number of centers: {len(G.style_net.w_centers)}")
+
+
+def build_trained_generator(cfg, map_location=None):
+ map_location = map_location if map_location is not None else tops.get_device()
+ G = instantiate(cfg.generator)
+ G.eval()
+ G.imsize = tuple(cfg.data.imsize) if hasattr(cfg, "data") else None
+ if hasattr(cfg, "ckpt_mapper"):
+ ckpt_mapper = instantiate(cfg.ckpt_mapper)
+ else:
+ ckpt_mapper = None
+ if "model_url" in cfg.common:
+ ckpt = tops.load_file_or_url(cfg.common.model_url, md5sum=cfg.common.model_md5sum)
+ load_generator_state(ckpt, G, ckpt_mapper)
+ return G.to(map_location)
+ try:
+ ckpt = checkpointer.load_checkpoint(cfg.checkpoint_dir, map_location="cpu")
+ load_generator_state(ckpt, G, ckpt_mapper)
+ except FileNotFoundError as e:
+ tops.logger.warn(f"Did not find generator checkpoint in: {cfg.checkpoint_dir}")
+ return G.to(map_location)
+
+
+def build_trained_discriminator(cfg, map_location=None):
+ map_location = map_location if map_location is not None else tops.get_device()
+ D = instantiate(cfg.discriminator).to(map_location)
+ D.eval()
+ try:
+ ckpt = checkpointer.load_checkpoint(cfg.checkpoint_dir, map_location="cpu")
+ if hasattr(cfg, "ckpt_mapper_D"):
+ ckpt["discriminator"] = instantiate(cfg.ckpt_mapper_D)(ckpt["discriminator"])
+ D.load_state_dict(ckpt["discriminator"])
+ except FileNotFoundError as e:
+ tops.logger.warn(f"Did not find discriminator checkpoint in: {cfg.checkpoint_dir}")
+ return D
+
+
+def load_state_dict(module: torch.nn.Module, state_dict: dict):
+ ignore_key = "style_net.w_centers" # Loaded by buyild_trained_generator
+ module_sd = module.state_dict()
+ to_remove = []
+ for key, item in state_dict.items():
+ if key not in module_sd:
+ continue
+ if item.shape != module_sd[key].shape:
+ to_remove.append(key)
+ warn(f"Incorrect shape. Current model: {module_sd[key].shape}, in state dict: {item.shape} for key: {key}")
+ for key in to_remove:
+ state_dict.pop(key)
+ for key, item in state_dict.items():
+ if key == ignore_key:
+ continue
+ if key not in module_sd:
+ warn(f"Did not find key in model state dict: {key}")
+ for key, item in module_sd.items():
+ if key not in state_dict:
+ warn(f"Did not find key in state dict: {key}")
+ module.load_state_dict(state_dict, strict=False)
diff --git a/project/models/deprecated_deep_privacy2/dp2/layers/__init__.py b/project/models/deprecated_deep_privacy2/dp2/layers/__init__.py
new file mode 100644
index 0000000..680be56
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/layers/__init__.py
@@ -0,0 +1,22 @@
+from typing import Dict
+import torch
+import tops
+import torch.nn as nn
+
+
+class Sequential(nn.Sequential):
+
+ def forward(self, x: Dict[str, torch.Tensor], **kwargs) -> Dict[str, torch.Tensor]:
+ for module in self:
+ x = module(x, **kwargs)
+ return x
+
+
+class Module(nn.Module):
+
+ def __init__(self, *args, **kwargs):
+ super().__init__()
+
+ def extra_repr(self):
+ num_params = tops.num_parameters(self) / 10**6
+ return f"Num params: {num_params:.3f}M"
diff --git a/project/models/deprecated_deep_privacy2/dp2/layers/sg2_layers.py b/project/models/deprecated_deep_privacy2/dp2/layers/sg2_layers.py
new file mode 100644
index 0000000..ce111ff
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/layers/sg2_layers.py
@@ -0,0 +1,229 @@
+from typing import List
+import numpy as np
+import torch
+import tops
+import torch.nn.functional as F
+from sg3_torch_utils.ops import conv2d_resample
+from sg3_torch_utils.ops import upfirdn2d
+from sg3_torch_utils.ops import bias_act
+from sg3_torch_utils.ops.fma import fma
+
+
+class FullyConnectedLayer(torch.nn.Module):
+ def __init__(self,
+ in_features, # Number of input features.
+ out_features, # Number of output features.
+ bias=True, # Apply additive bias before the activation function?
+ activation='linear', # Activation function: 'relu', 'lrelu', etc.
+ lr_multiplier=1, # Learning rate multiplier.
+ bias_init=0, # Initial value for the additive bias.
+ ):
+ super().__init__()
+ self.repr = dict(
+ in_features=in_features, out_features=out_features, bias=bias,
+ activation=activation, lr_multiplier=lr_multiplier, bias_init=bias_init)
+ self.activation = activation
+ self.weight = torch.nn.Parameter(torch.randn([out_features, in_features]) / lr_multiplier)
+ self.bias = torch.nn.Parameter(torch.full([out_features], np.float32(bias_init))) if bias else None
+ self.weight_gain = lr_multiplier / np.sqrt(in_features)
+ self.bias_gain = lr_multiplier
+ self.in_features = in_features
+ self.out_features = out_features
+
+ def forward(self, x):
+ w = self.weight * self.weight_gain
+ b = self.bias
+ if b is not None and self.bias_gain != 1:
+ b = b * self.bias_gain
+ x = F.linear(x, w)
+ x = bias_act.bias_act(x, b, act=self.activation)
+ return x
+
+ def extra_repr(self) -> str:
+ return ", ".join([f"{key}={item}" for key, item in self.repr.items()])
+
+
+class Conv2d(torch.nn.Module):
+ def __init__(self,
+ in_channels, # Number of input channels.
+ out_channels, # Number of output channels.
+ kernel_size=3, # Convolution kernel size.
+ up=1, # Integer upsampling factor.
+ down=1, # Integer downsampling factor
+ activation='lrelu', # Activation function: 'relu', 'lrelu', etc.
+ resample_filter=[1, 3, 3, 1], # Low-pass filter to apply when resampling activations.
+ conv_clamp=None, # Clamp the output of convolution layers to +-X, None = disable clamping.
+ bias=True,
+ norm=False,
+ lr_multiplier=1,
+ bias_init=0,
+ w_dim=None,
+ gain=1,
+ ):
+ super().__init__()
+ if norm:
+ self.norm = torch.nn.InstanceNorm2d(None)
+ assert norm in [True, False]
+ self.up = up
+ self.down = down
+ self.activation = activation
+ self.conv_clamp = conv_clamp if conv_clamp is None else conv_clamp * gain
+ self.out_channels = out_channels
+ self.in_channels = in_channels
+ self.padding = kernel_size // 2
+
+ self.repr = dict(
+ in_channels=in_channels, out_channels=out_channels,
+ kernel_size=kernel_size, up=up, down=down,
+ activation=activation, resample_filter=resample_filter, conv_clamp=conv_clamp, bias=bias,
+ )
+
+ if self.up == 1 and self.down == 1:
+ self.resample_filter = None
+ else:
+ self.register_buffer('resample_filter', upfirdn2d.setup_filter(resample_filter))
+
+ self.act_gain = bias_act.activation_funcs[activation].def_gain * gain
+ self.weight_gain = lr_multiplier / np.sqrt(in_channels * (kernel_size ** 2))
+ self.weight = torch.nn.Parameter(torch.randn([out_channels, in_channels, kernel_size, kernel_size]))
+ self.bias = torch.nn.Parameter(torch.zeros([out_channels]) + bias_init) if bias else None
+ self.bias_gain = lr_multiplier
+ if w_dim is not None:
+ self.affine = FullyConnectedLayer(w_dim, in_channels, bias_init=1)
+ self.affine_beta = FullyConnectedLayer(w_dim, in_channels, bias_init=0)
+
+ def forward(self, x, w=None, s=None):
+ tops.assert_shape(x, [None, self.weight.shape[1], None, None])
+ if s is not None:
+ s = s[..., :self.in_channels * 2]
+ gamma, beta = s.view(-1, self.in_channels * 2, 1, 1).chunk(2, dim=1)
+ x = fma(x, gamma, beta)
+ elif hasattr(self, "affine"):
+ gamma = self.affine(w).view(-1, self.in_channels, 1, 1)
+ beta = self.affine_beta(w).view(-1, self.in_channels, 1, 1)
+ x = fma(x, gamma, beta)
+ w = self.weight * self.weight_gain
+ # Removing flip weight is not safe.
+ x = conv2d_resample.conv2d_resample(x, w, self.resample_filter, self.up,
+ self.down, self.padding, flip_weight=self.up == 1)
+ if hasattr(self, "norm"):
+ x = self.norm(x)
+ b = self.bias * self.bias_gain if self.bias is not None else None
+ x = bias_act.bias_act(x, b, act=self.activation, gain=self.act_gain, clamp=self.conv_clamp)
+ return x
+
+ def extra_repr(self) -> str:
+ return ", ".join([f"{key}={item}" for key, item in self.repr.items()])
+
+
+class Block(torch.nn.Module):
+ def __init__(self,
+ in_channels, # Number of input channels, 0 = first block.
+ out_channels, # Number of output channels.
+ conv_clamp=None, # Clamp the output of convolution layers to +-X, None = disable clamping.
+ up=1,
+ down=1,
+ **layer_kwargs, # Arguments for SynthesisLayer.
+ ):
+ super().__init__()
+ self.in_channels = in_channels
+ self.down = down
+ self.conv0 = Conv2d(in_channels, out_channels, down=down, conv_clamp=conv_clamp, **layer_kwargs)
+ self.conv1 = Conv2d(out_channels, out_channels, up=up, conv_clamp=conv_clamp, **layer_kwargs)
+
+ def forward(self, x, **layer_kwargs):
+ x = self.conv0(x, **layer_kwargs)
+ x = self.conv1(x, **layer_kwargs)
+ return x
+
+
+class ResidualBlock(torch.nn.Module):
+ def __init__(self,
+ in_channels, # Number of input channels, 0 = first block.
+ out_channels, # Number of output channels.
+ conv_clamp=None, # Clamp the output of convolution layers to +-X, None = disable clamping.
+ up=1,
+ down=1,
+ gain_out=np.sqrt(0.5),
+ fix_residual: bool = False,
+ **layer_kwargs, # Arguments for conv layer.
+ ):
+ super().__init__()
+ self.in_channels = in_channels
+ self.out_channels = out_channels
+ self.down = down
+ self.conv0 = Conv2d(in_channels, out_channels, down=down, conv_clamp=conv_clamp, **layer_kwargs)
+
+ self.conv1 = Conv2d(out_channels, out_channels, up=up, conv_clamp=conv_clamp, gain=gain_out, **layer_kwargs)
+
+ self.skip = Conv2d(
+ in_channels, out_channels, kernel_size=1, bias=False, up=up, down=down,
+ activation="linear" if fix_residual else "lrelu",
+ gain=gain_out
+ )
+ self.gain_out = gain_out
+
+ def forward(self, x, w=None, s=None, **layer_kwargs):
+ y = self.skip(x)
+ s_ = next(s) if s is not None else None
+ x = self.conv0(x, w, s=s_, **layer_kwargs)
+ s_ = next(s) if s is not None else None
+ x = self.conv1(x, w, s=s_, **layer_kwargs)
+ x = y + x
+ return x
+
+
+class MinibatchStdLayer(torch.nn.Module):
+ def __init__(self, group_size, num_channels=1):
+ super().__init__()
+ self.group_size = group_size
+ self.num_channels = num_channels
+
+ def forward(self, x):
+ N, C, H, W = x.shape
+ with tops.suppress_tracer_warnings(): # as_tensor results are registered as constants
+ G = torch.min(torch.as_tensor(self.group_size), torch.as_tensor(N)) if self.group_size is not None else N
+ F = self.num_channels
+ c = C // F
+
+ # [GnFcHW] Split minibatch N into n groups of size G, and channels C into F groups of size c.
+ y = x.reshape(G, -1, F, c, H, W)
+ y = y - y.mean(dim=0) # [GnFcHW] Subtract mean over group.
+ y = y.square().mean(dim=0) # [nFcHW] Calc variance over group.
+ y = (y + 1e-8).sqrt() # [nFcHW] Calc stddev over group.
+ y = y.mean(dim=[2, 3, 4]) # [nF] Take average over channels and pixels.
+ y = y.reshape(-1, F, 1, 1) # [nF11] Add missing dimensions.
+ y = y.repeat(G, 1, H, W) # [NFHW] Replicate over group and pixels.
+ x = torch.cat([x, y], dim=1) # [NCHW] Append to input as new channels.
+ return x
+
+
+class DiscriminatorEpilogue(torch.nn.Module):
+ def __init__(self,
+ in_channels, # Number of input channels.
+ resolution: List[int], # Resolution of this block.
+ mbstd_group_size=4, # Group size for the minibatch standard deviation layer, None = entire minibatch.
+ mbstd_num_channels=1, # Number of features for the minibatch standard deviation layer, 0 = disable.
+ activation='lrelu', # Activation function: 'relu', 'lrelu', etc.
+ conv_clamp=None, # Clamp the output of convolution layers to +-X, None = disable clamping.
+ ):
+ super().__init__()
+ self.in_channels = in_channels
+ self.resolution = resolution
+ self.mbstd = MinibatchStdLayer(group_size=mbstd_group_size,
+ num_channels=mbstd_num_channels) if mbstd_num_channels > 0 else None
+ self.conv = Conv2d(
+ in_channels + mbstd_num_channels, in_channels,
+ kernel_size=3, activation=activation, conv_clamp=conv_clamp)
+ self.fc = FullyConnectedLayer(in_channels * resolution[0] * resolution[1], in_channels, activation=activation)
+ self.out = FullyConnectedLayer(in_channels, 1)
+
+ def forward(self, x):
+ tops.assert_shape(x, [None, self.in_channels, *self.resolution]) # [NCHW]
+ # Main layers.
+ if self.mbstd is not None:
+ x = self.mbstd(x)
+ x = self.conv(x)
+ x = self.fc(x.flatten(1))
+ x = self.out(x)
+ return x
diff --git a/project/models/deprecated_deep_privacy2/dp2/loss/__init__.py b/project/models/deprecated_deep_privacy2/dp2/loss/__init__.py
new file mode 100644
index 0000000..16cbdd0
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/loss/__init__.py
@@ -0,0 +1 @@
+from .sg2_loss import StyleGAN2Loss
diff --git a/project/models/deprecated_deep_privacy2/dp2/loss/pl_regularization.py b/project/models/deprecated_deep_privacy2/dp2/loss/pl_regularization.py
new file mode 100644
index 0000000..cf47b9b
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/loss/pl_regularization.py
@@ -0,0 +1,49 @@
+import torch
+import tops
+import numpy as np
+from sg3_torch_utils.ops import conv2d_gradfix
+
+pl_mean_total = torch.zeros([])
+
+
+class PLRegularization:
+
+ def __init__(self, weight: float, batch_shrink: int, pl_decay: float, scale_by_mask: bool, **kwargs):
+ self.pl_mean = torch.zeros([], device=tops.get_device())
+ self.pl_weight = weight
+ self.batch_shrink = batch_shrink
+ self.pl_decay = pl_decay
+ self.scale_by_mask = scale_by_mask
+
+ def __call__(self, G, batch, grad_scaler):
+ batch_size = batch["img"].shape[0] // self.batch_shrink
+ batch = {k: v[:batch_size] for k, v in batch.items() if k != "embed_map"}
+ if "embed_map" in batch:
+ batch["embed_map"] = batch["embed_map"]
+ z = G.get_z(batch["img"])
+
+ with torch.cuda.amp.autocast(tops.AMP()):
+ gen_ws = G.style_net(z)
+ gen_img = G(**batch, w=gen_ws)["img"].float()
+ pl_noise = torch.randn_like(gen_img) / np.sqrt(gen_img.shape[2] * gen_img.shape[3])
+ with conv2d_gradfix.no_weight_gradients():
+ # Sums over HWC
+ pl_grads = torch.autograd.grad(
+ outputs=[grad_scaler.scale(gen_img * pl_noise)],
+ inputs=[gen_ws],
+ create_graph=True,
+ grad_outputs=torch.ones_like(gen_img),
+ only_inputs=True)[0]
+
+ pl_grads = pl_grads.float() / grad_scaler.get_scale()
+ if self.scale_by_mask:
+ # Percentage of pixels known
+ scaling = batch["mask"].flatten(start_dim=1).mean(dim=1).view(-1, 1)
+ pl_grads = pl_grads / scaling
+ pl_lengths = pl_grads.square().sum(1).sqrt()
+ pl_mean = self.pl_mean.lerp(pl_lengths.mean(), self.pl_decay)
+ if not torch.isnan(pl_mean).any():
+ self.pl_mean.copy_(pl_mean.detach())
+ pl_penalty = (pl_lengths - pl_mean).square()
+ to_log = dict(pl_penalty=pl_penalty.mean().detach())
+ return pl_penalty.view(-1) * self.pl_weight, to_log
diff --git a/project/models/deprecated_deep_privacy2/dp2/loss/projected_gan_loss.py b/project/models/deprecated_deep_privacy2/dp2/loss/projected_gan_loss.py
new file mode 100644
index 0000000..5e59727
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/loss/projected_gan_loss.py
@@ -0,0 +1,123 @@
+import numpy as np
+import tops
+import torch
+from sg3_torch_utils.ops import upfirdn2d
+from tops import logger
+
+
+def blur(im, init_sigma, t, batch, **kwargs):
+ batch = {k: v for k, v in batch.items()}
+ sigma = max(t, 0) * init_sigma
+ blur_size = int(np.round(sigma*3))
+ if blur_size == 0:
+ return im
+ blur_f = torch.arange(-blur_size, blur_size + 1, device=im.device).div(sigma).square().neg().exp2()
+ blur_f = blur_f / blur_f.sum()
+ im = upfirdn2d.filter2d(im, blur_f)
+ return im
+
+
+class ProjectedGANLoss:
+
+ def __init__(
+ self,
+ D,
+ G,
+ aug_fade_kimg,
+ blur_init_sigma,
+ loss_type="hinge",
+ ) -> None:
+ self.D = D
+ self.G = G
+ self.aug_fade_kimg = aug_fade_kimg
+ self.do_PL_Reg = False
+ self.aug_t = lambda: (1 - logger.global_step() / self.aug_fade_kimg)
+ self.loss_type = loss_type
+ assert self.loss_type in ["hinge", "masked-hinge"]
+ self.blur_init_sigma = blur_init_sigma
+
+ def forward_D(self, img, batch, fnet_grad: bool):
+ if logger.global_step() < self.aug_fade_kimg:
+ img = blur(im=img, batch=batch, t=self.aug_t(), init_sigma=self.blur_init_sigma)
+ batch = {k: v for k, v in batch.items() if k != "img"}
+ return self.D(**batch, img=img, fnet_grad=fnet_grad)
+
+ def D_loss(self, batch: dict, **kwargs):
+ to_log = {}
+ # Forward through G and D
+ with torch.cuda.amp.autocast(enabled=tops.AMP()):
+ real_logits = self.forward_D(batch["img"], batch, False)["logits"]
+
+ with torch.no_grad():
+ fake_out = self.G(**batch, update_emas=True)
+ fake_img = fake_out["img"]
+ fake_logits = self.forward_D(fake_img, batch, False)["logits"]
+
+ if self.loss_type == "hinge":
+ fake_logits = [torch.cat([l.flatten(start_dim=1) for l in logits], dim=1) for logits in fake_logits]
+ fake_loss = sum([(torch.ones_like(l) + l).relu().mean() for l in fake_logits])
+ real_logits = [torch.cat([l.flatten(start_dim=1) for l in logits], dim=1) for logits in real_logits]
+ real_loss = sum([(torch.ones_like(l) - l).relu().mean() for l in real_logits])
+
+ if self.loss_type == "masked-hinge":
+ real_loss, fake_loss, to_log_hinge = masked_hinge_D_loss(fake_logits, real_logits, batch["mask"])
+ # Reshape for logging
+ fake_logits = [torch.cat([l.flatten(start_dim=1) for l in logits], dim=1) for logits in fake_logits]
+ real_logits = [torch.cat([l.flatten(start_dim=1) for l in logits], dim=1) for logits in real_logits]
+
+ real_logits = torch.cat([r.view(-1) for r in real_logits])
+ fake_logits = torch.cat([r.view(-1) for r in fake_logits])
+
+ total_loss = fake_loss + real_loss
+ to_log = dict(
+ real_scores=real_logits.mean(),
+ fake_scores=fake_logits.mean(),
+ real_loss=real_loss.mean(),
+ fake_loss=fake_loss.mean(),
+ fake_logits_sign=fake_logits.sign().mean(),
+ real_logits_sign=real_logits.sign().mean()
+ )
+ if self.loss_type == "masked-hinge":
+ to_log.update(to_log_hinge)
+ to_log = {key: item.mean().detach() for key, item in to_log.items()}
+ return total_loss.mean(), to_log
+
+ def G_loss(self, batch: dict, **kwargs):
+ with torch.cuda.amp.autocast(enabled=tops.AMP()):
+ to_log = {}
+ # Forward through G and D
+ G_fake = self.G(**batch)
+ fake_logits = self.forward_D(G_fake["img"], batch, True)["logits"]
+ fake_logits = [torch.cat([l.flatten(start_dim=1) for l in logits], dim=1) for logits in fake_logits]
+ fake_loss = sum([(-l).mean() for l in fake_logits])
+
+ to_log = {key: item.mean().detach() for key, item in to_log.items()}
+ return fake_loss.mean(), to_log
+
+
+def masked_hinge_D_loss(fake_logits, real_logits, mask):
+ fake_loss = 0
+ real_loss = 0
+ fake_logits_real_sign = 0
+ fake_logits_fake_sign = 0
+ for r_logits, f_logits in zip(real_logits, fake_logits):
+ resized_fake_pixels = [
+ torch.nn.functional.adaptive_max_pool2d(1 - mask, output_size=l.shape[-2:])
+ for l in f_logits
+ ]
+ N_fake_pixels = sum([l.sum() for l in resized_fake_pixels])
+ N_real_pixels = sum([np.prod(l.shape) for l in f_logits]) - N_fake_pixels
+
+ for rl, fl, fake_pixels in zip(r_logits, f_logits, resized_fake_pixels):
+ real_pixels = 1 - fake_pixels
+ fake_loss = fake_loss + ((torch.ones_like(fl) + fl)*fake_pixels).relu().sum() / N_fake_pixels
+
+ real_loss = real_loss + ((torch.ones_like(fl) - fl)*real_pixels).relu().sum() / N_real_pixels / 2
+ real_loss = real_loss + ((torch.ones_like(fl) - rl)*real_pixels).relu().sum() / N_real_pixels / 2
+ real_loss = real_loss + ((torch.ones_like(fl) - rl)*fake_pixels).relu().sum() / N_real_pixels
+ fake_logits_real_sign += ((real_pixels * fl).sign().sum() / real_pixels.sum()).detach() / len(r_logits) / len(fake_logits)
+ fake_logits_fake_sign += ((fake_pixels * fl).sign().sum() / fake_pixels.sum()).detach() / len(r_logits) / len(fake_logits)
+ return real_loss, fake_loss, dict(
+ fake_logits_real_sign=fake_logits_real_sign,
+ fake_logits_fake_sign=fake_logits_fake_sign
+ )
diff --git a/project/models/deprecated_deep_privacy2/dp2/loss/r1_regularization.py b/project/models/deprecated_deep_privacy2/dp2/loss/r1_regularization.py
new file mode 100644
index 0000000..f974c55
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/loss/r1_regularization.py
@@ -0,0 +1,32 @@
+import torch
+import tops
+
+
+def r1_regularization(
+ real_img, real_score, mask, lambd: float, lazy_reg_interval: int,
+ lazy_regularization: bool,
+ scaler: torch.cuda.amp.GradScaler, mask_out: bool,
+ mask_out_scale: bool,
+ **kwargs
+):
+ grad = torch.autograd.grad(
+ outputs=scaler.scale(real_score),
+ inputs=real_img,
+ grad_outputs=torch.ones_like(real_score),
+ create_graph=True,
+ only_inputs=True,
+ )[0]
+ inv_scale = 1.0 / scaler.get_scale()
+ grad = grad * inv_scale
+ with torch.cuda.amp.autocast(tops.AMP()):
+ if mask_out:
+ grad = grad * (1 - mask)
+ grad = grad.square().sum(dim=[1, 2, 3])
+ if mask_out and mask_out_scale:
+ total_pixels = real_img.shape[1] * real_img.shape[2] * real_img.shape[3]
+ n_fake = (1-mask).sum(dim=[1, 2, 3])
+ scaling = total_pixels / n_fake
+ grad = grad * scaling
+ if lazy_regularization:
+ lambd_ = lambd * lazy_reg_interval / 2 # From stylegan2, lazy regularization
+ return grad * lambd_, grad.detach()
diff --git a/project/models/deprecated_deep_privacy2/dp2/loss/sg2_loss.py b/project/models/deprecated_deep_privacy2/dp2/loss/sg2_loss.py
new file mode 100644
index 0000000..763263e
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/loss/sg2_loss.py
@@ -0,0 +1,96 @@
+import functools
+import torch
+import tops
+from tops import logger
+from dp2.utils import forward_D_fake
+from .utils import nsgan_d_loss, nsgan_g_loss
+from .r1_regularization import r1_regularization
+from .pl_regularization import PLRegularization
+
+
+class StyleGAN2Loss:
+
+ def __init__(
+ self,
+ D,
+ G,
+ r1_opts: dict,
+ EP_lambd: float,
+ lazy_reg_interval: int,
+ lazy_regularization: bool,
+ pl_reg_opts: dict,
+ ) -> None:
+ self.gradient_step_D = 0
+ self._lazy_reg_interval = lazy_reg_interval
+ self.D = D
+ self.G = G
+ self.EP_lambd = EP_lambd
+ self.lazy_regularization = lazy_regularization
+ self.r1_reg = functools.partial(
+ r1_regularization, **r1_opts, lazy_reg_interval=lazy_reg_interval,
+ lazy_regularization=lazy_regularization)
+ self.do_PL_Reg = False
+ if pl_reg_opts.weight > 0:
+ self.pl_reg = PLRegularization(**pl_reg_opts)
+ self.do_PL_Reg = True
+ self.pl_start_nimg = pl_reg_opts.start_nimg
+
+ def D_loss(self, batch: dict, grad_scaler):
+ to_log = {}
+ # Forward through G and D
+ do_GP = self.lazy_regularization and self.gradient_step_D % self._lazy_reg_interval == 0
+ if do_GP:
+ batch["img"] = batch["img"].detach().requires_grad_(True)
+ with torch.cuda.amp.autocast(enabled=tops.AMP()):
+ with torch.no_grad():
+ G_fake = self.G(**batch, update_emas=True)
+ D_out_real = self.D(**batch)
+
+ D_out_fake = forward_D_fake(batch, G_fake["img"], self.D)
+
+ # Non saturating loss
+ nsgan_loss = nsgan_d_loss(D_out_real["score"], D_out_fake["score"])
+ tops.assert_shape(nsgan_loss, (batch["img"].shape[0], ))
+ to_log["d_loss"] = nsgan_loss.mean()
+ total_loss = nsgan_loss
+ epsilon_penalty = D_out_real["score"].pow(2).view(-1)
+ to_log["epsilon_penalty"] = epsilon_penalty.mean()
+ tops.assert_shape(epsilon_penalty, total_loss.shape)
+ total_loss = total_loss + epsilon_penalty * self.EP_lambd
+
+ # Improved gradient penalty with lazy regularization
+ # Gradient penalty applies specialized autocast.
+ if do_GP:
+ gradient_pen, grad_unscaled = self.r1_reg(
+ batch["img"], D_out_real["score"], batch["mask"], scaler=grad_scaler)
+ to_log["r1_gradient_penalty"] = grad_unscaled.mean()
+ tops.assert_shape(gradient_pen, total_loss.shape)
+ total_loss = total_loss + gradient_pen
+
+ batch["img"] = batch["img"].detach().requires_grad_(False)
+ if "score" in D_out_real:
+ to_log["real_scores"] = D_out_real["score"]
+ to_log["real_logits_sign"] = D_out_real["score"].sign()
+ to_log["fake_logits_sign"] = D_out_fake["score"].sign()
+ to_log["fake_scores"] = D_out_fake["score"]
+ to_log = {key: item.mean().detach() for key, item in to_log.items()}
+ self.gradient_step_D += 1
+ return total_loss.mean(), to_log
+
+ def G_loss(self, batch: dict, grad_scaler):
+ with torch.cuda.amp.autocast(enabled=tops.AMP()):
+ to_log = {}
+ # Forward through G and D
+ G_fake = self.G(**batch)
+ D_out_fake = forward_D_fake(batch, G_fake["img"], self.D)
+ # Adversarial Loss
+ total_loss = nsgan_g_loss(D_out_fake["score"]).view(-1)
+ to_log["g_loss"] = total_loss.mean()
+ tops.assert_shape(total_loss, (batch["img"].shape[0], ))
+
+ if self.do_PL_Reg and logger.global_step() >= self.pl_start_nimg:
+ pl_reg, to_log_ = self.pl_reg(self.G, batch, grad_scaler=grad_scaler)
+ total_loss = total_loss + pl_reg.mean()
+ to_log.update(to_log_)
+ to_log = {key: item.mean().detach() for key, item in to_log.items()}
+ return total_loss.mean(), to_log
diff --git a/project/models/deprecated_deep_privacy2/dp2/loss/utils.py b/project/models/deprecated_deep_privacy2/dp2/loss/utils.py
new file mode 100644
index 0000000..8d6e19c
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/loss/utils.py
@@ -0,0 +1,26 @@
+import torch
+import torch.nn.functional as F
+
+
+def nsgan_g_loss(fake_score):
+ """
+ Non-saturating criterion from Goodfellow et al. 2014
+ """
+ return torch.nn.functional.softplus(-fake_score)
+
+
+def nsgan_d_loss(real_score, fake_score):
+ """
+ Non-saturating criterion from Goodfellow et al. 2014
+ """
+ d_loss = F.softplus(-real_score) + F.softplus(fake_score)
+ return d_loss.view(-1)
+
+
+def smooth_masked_l1_loss(x, target, mask):
+ """
+ Pixel-wise l1 loss for the area indicated by mask
+ """
+ # Beta=.1 <-> square loss if pixel difference <= 12.8
+ l1 = F.smooth_l1_loss(x*mask, target*mask, beta=.1, reduction="none").sum(dim=[1, 2, 3]) / mask.sum(dim=[1, 2, 3])
+ return l1
diff --git a/project/models/deprecated_deep_privacy2/dp2/metrics/__init__.py b/project/models/deprecated_deep_privacy2/dp2/metrics/__init__.py
new file mode 100644
index 0000000..9d8bbb1
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/metrics/__init__.py
@@ -0,0 +1,3 @@
+from .torch_metrics import compute_metrics_iteratively
+from .fid import compute_fid
+from .ppl import calculate_ppl
diff --git a/project/models/deprecated_deep_privacy2/dp2/metrics/fid.py b/project/models/deprecated_deep_privacy2/dp2/metrics/fid.py
new file mode 100644
index 0000000..3c8e0e6
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/metrics/fid.py
@@ -0,0 +1,52 @@
+import tops
+from dp2 import utils
+from pathlib import Path
+from torch_fidelity.generative_model_modulewrapper import GenerativeModelModuleWrapper
+import torch
+import torch_fidelity
+
+
+class GeneratorIteratorWrapper(GenerativeModelModuleWrapper):
+
+ def __init__(self, generator, dataloader, zero_z: bool, n_diverse: int):
+ if isinstance(generator, utils.EMA):
+ generator = generator.generator
+ z_size = generator.z_channels
+ super().__init__(generator, z_size, "normal", 0)
+ self.zero_z = zero_z
+ self.dataloader = iter(dataloader)
+ self.n_diverse = n_diverse
+ self.cur_div_idx = 0
+
+ @torch.no_grad()
+ def forward(self, z, **kwargs):
+ if self.cur_div_idx == 0:
+ self.batch = next(self.dataloader)
+ if self.zero_z:
+ z = z.zero_()
+ self.cur_div_idx += 1
+ self.cur_div_idx = 0 if self.cur_div_idx == self.n_diverse else self.cur_div_idx
+ with torch.cuda.amp.autocast(enabled=tops.AMP()):
+ img = self.module(**self.batch)["img"]
+ img = (utils.denormalize_img(img)*255).byte()
+ return img
+
+
+def compute_fid(generator, dataloader, real_directory, n_source, zero_z, n_diverse):
+ generator = GeneratorIteratorWrapper(generator, dataloader, zero_z, n_diverse)
+ batch_size = dataloader.batch_size
+ num_samples = (n_source * n_diverse) // batch_size * batch_size
+ assert n_diverse >= 1
+ assert (not zero_z) or n_diverse == 1
+ assert num_samples % batch_size == 0
+ assert n_source <= batch_size * len(dataloader), (batch_size*len(dataloader), n_source, n_diverse)
+ metrics = torch_fidelity.calculate_metrics(
+ input1=generator,
+ input2=real_directory,
+ cuda=torch.cuda.is_available(),
+ fid=True,
+ input2_cache_name="_".join(Path(real_directory).parts) + "_cached",
+ input1_model_num_samples=int(num_samples),
+ batch_size=dataloader.batch_size
+ )
+ return metrics["frechet_inception_distance"]
diff --git a/project/models/deprecated_deep_privacy2/dp2/metrics/fid_clip.py b/project/models/deprecated_deep_privacy2/dp2/metrics/fid_clip.py
new file mode 100644
index 0000000..b307f75
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/metrics/fid_clip.py
@@ -0,0 +1,89 @@
+import pickle
+import torch
+import torchvision
+from pathlib import Path
+from dp2 import utils
+import tops
+try:
+ import clip
+except ImportError:
+ print("Could not import clip.")
+from torch_fidelity.metric_fid import fid_features_to_statistics, fid_statistics_to_metric
+clip_model = None
+clip_preprocess = None
+
+
+@torch.no_grad()
+def compute_fid_clip(
+ dataloader, generator,
+ cache_directory,
+ data_len=None,
+ truncation_value=None,
+ multi_modal_truncate=False,
+ **kwargs
+ ) -> dict:
+ """
+ FID CLIP following the description in The Role of ImageNet Classes in Frechet Inception Distance, Thomas Kynkaamniemi et al.
+ Args:
+ n_samples (int): Creates N samples from same image to calculate stats
+ """
+ global clip_model, clip_preprocess
+ if clip_model is None:
+ clip_model, preprocess = clip.load("ViT-B/32", device="cpu")
+ normalize_fn = preprocess.transforms[-1]
+ img_mean = normalize_fn.mean
+ img_std = normalize_fn.std
+ clip_model = tops.to_cuda(clip_model.visual)
+ clip_preprocess = tops.to_cuda(torch.nn.Sequential(
+ torchvision.transforms.Resize((224, 224), interpolation=torchvision.transforms.InterpolationMode.BICUBIC),
+ torchvision.transforms.Normalize(img_mean, img_std)
+ ))
+ cache_directory = Path(cache_directory)
+ if data_len is None:
+ data_len = len(dataloader)*dataloader.batch_size
+ fid_cache_path = cache_directory.joinpath("fid_stats_clip.pkl")
+ has_fid_cache = fid_cache_path.is_file()
+ if not has_fid_cache:
+ fid_features_real = torch.zeros(data_len, 512, dtype=torch.float32, device=tops.get_device())
+ fid_features_fake = torch.zeros(data_len, 512, dtype=torch.float32, device=tops.get_device())
+ eidx = 0
+ n_samples_seen = 0
+ for batch in utils.tqdm_(iter(dataloader), desc="Computing FID CLIP."):
+ sidx = eidx
+ eidx = sidx + batch["img"].shape[0]
+ n_samples_seen += batch["img"].shape[0]
+ with torch.cuda.amp.autocast(tops.AMP()):
+ if multi_modal_truncate:
+ fakes = generator.multi_modal_truncate(n=batch["condition"].shape[0], truncation_value=0)["img"]
+ else:
+ fakes = generator.sample(n=batch["condition"].shape[0], truncation_value=truncation_value)["img"]
+ real_data = batch["img"]
+ fakes = utils.denormalize_img(fakes)
+ real_data = utils.denormalize_img(real_data)
+ if not has_fid_cache:
+ real_data = clip_preprocess(real_data)
+ fid_features_real[sidx:eidx] = clip_model(real_data)
+ fakes = clip_preprocess(fakes)
+ fid_features_fake[sidx:eidx] = clip_model(fakes)
+ fid_features_fake = fid_features_fake[:n_samples_seen]
+ fid_features_fake = tops.all_gather_uneven(fid_features_fake).cpu()
+ if has_fid_cache:
+ if tops.rank() == 0:
+ with open(fid_cache_path, "rb") as fp:
+ fid_stat_real = pickle.load(fp)
+ else:
+ fid_features_real = fid_features_real[:n_samples_seen]
+ fid_features_real = tops.all_gather_uneven(fid_features_real).cpu()
+ assert fid_features_real.shape == fid_features_fake.shape
+ if tops.rank() == 0:
+ fid_stat_real = fid_features_to_statistics(fid_features_real)
+ cache_directory.mkdir(exist_ok=True, parents=True)
+ with open(fid_cache_path, "wb") as fp:
+ pickle.dump(fid_stat_real, fp)
+
+ if tops.rank() == 0:
+ print("Starting calculation of fid from features of shape:", fid_features_fake.shape)
+ fid_stat_fake = fid_features_to_statistics(fid_features_fake)
+ fid_ = fid_statistics_to_metric(fid_stat_real, fid_stat_fake, verbose=False)["frechet_inception_distance"]
+ return dict(fid_clip=fid_)
+ return dict(fid_clip=-1)
diff --git a/project/models/deprecated_deep_privacy2/dp2/metrics/lpips.py b/project/models/deprecated_deep_privacy2/dp2/metrics/lpips.py
new file mode 100644
index 0000000..397d1b1
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/metrics/lpips.py
@@ -0,0 +1,77 @@
+import torch
+import tops
+import sys
+from contextlib import redirect_stdout
+from torch_fidelity.sample_similarity_lpips import NetLinLayer, URL_VGG16_LPIPS, VGG16features, normalize_tensor, spatial_average
+
+
+class SampleSimilarityLPIPS(torch.nn.Module):
+ SUPPORTED_DTYPES = {
+ 'uint8': torch.uint8,
+ 'float32': torch.float32,
+ }
+
+ def __init__(self):
+
+ super().__init__()
+ self.chns = [64, 128, 256, 512, 512]
+ self.L = len(self.chns)
+ self.lin0 = NetLinLayer(self.chns[0], use_dropout=True)
+ self.lin1 = NetLinLayer(self.chns[1], use_dropout=True)
+ self.lin2 = NetLinLayer(self.chns[2], use_dropout=True)
+ self.lin3 = NetLinLayer(self.chns[3], use_dropout=True)
+ self.lin4 = NetLinLayer(self.chns[4], use_dropout=True)
+ self.lins = [self.lin0, self.lin1, self.lin2, self.lin3, self.lin4]
+ with redirect_stdout(sys.stderr):
+ fp = tops.download_file(URL_VGG16_LPIPS)
+ state_dict = torch.load(fp, map_location="cpu")
+ self.load_state_dict(state_dict)
+ self.net = VGG16features()
+ self.eval()
+ for param in self.parameters():
+ param.requires_grad = False
+ mean_rescaled = (1 + torch.tensor([-.030, -.088, -.188]).view(1, 3, 1, 1)) * 255 / 2
+ inv_std_rescaled = 2 / (torch.tensor([.458, .448, .450]).view(1, 3, 1, 1) * 255)
+ self.register_buffer("mean", mean_rescaled)
+ self.register_buffer("std", inv_std_rescaled)
+
+ def normalize(self, x):
+ # torchvision values in range [0,1] mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225]
+ x = (x.float() - self.mean) * self.std
+ return x
+
+ @staticmethod
+ def resize(x, size):
+ if x.shape[-1] > size and x.shape[-2] > size:
+ x = torch.nn.functional.interpolate(x, (size, size), mode='area')
+ else:
+ x = torch.nn.functional.interpolate(x, (size, size), mode='bilinear', align_corners=False)
+ return x
+
+ def lpips_from_feats(self, feats0, feats1):
+ diffs = {}
+ for kk in range(self.L):
+ diffs[kk] = (feats0[kk] - feats1[kk]) ** 2
+
+ res = [spatial_average(self.lins[kk].model(diffs[kk])) for kk in range(self.L)]
+ val = sum(res)
+ return val
+
+ def get_feats(self, x):
+ assert x.dim() == 4 and x.shape[1] == 3, 'Input 0 is not Bx3xHxW'
+ if x.shape[-2] < 16 or x.shape[-1] < 16: # Resize images < 16x16
+ f = 2
+ size = tuple([int(f*_) for _ in x.shape[-2:]])
+ x = torch.nn.functional.interpolate(x, size=size, mode="bilinear", align_corners=False)
+ in0_input = self.normalize(x)
+ outs0 = self.net.forward(in0_input)
+
+ feats = {}
+ for kk in range(self.L):
+ feats[kk] = normalize_tensor(outs0[kk])
+ return feats
+
+ def forward(self, in0, in1):
+ feats0 = self.get_feats(in0)
+ feats1 = self.get_feats(in1)
+ return self.lpips_from_feats(feats0, feats1), feats0, feats1
diff --git a/project/models/deprecated_deep_privacy2/dp2/metrics/ppl.py b/project/models/deprecated_deep_privacy2/dp2/metrics/ppl.py
new file mode 100644
index 0000000..421aeaf
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/metrics/ppl.py
@@ -0,0 +1,116 @@
+import numpy as np
+import torch
+import tops
+from dp2 import utils
+from torch_fidelity.helpers import get_kwarg, vassert
+from torch_fidelity.defaults import DEFAULTS as PPL_DEFAULTS
+from torch_fidelity.utils import sample_random, batch_interp, create_sample_similarity
+from torchvision.transforms.functional import resize
+
+
+def slerp(a, b, t):
+ a = a / a.norm(dim=-1, keepdim=True)
+ b = b / b.norm(dim=-1, keepdim=True)
+ d = (a * b).sum(dim=-1, keepdim=True)
+ p = t * torch.acos(d)
+ c = b - d * a
+ c = c / c.norm(dim=-1, keepdim=True)
+ d = a * torch.cos(p) + c * torch.sin(p)
+ d = d / d.norm(dim=-1, keepdim=True)
+ return d
+
+
+@torch.no_grad()
+def calculate_ppl(
+ dataloader,
+ generator,
+ latent_space=None,
+ data_len=None,
+ upsample_size=None,
+ **kwargs) -> dict:
+ """
+ Inspired by https://github.com/NVlabs/stylegan/blob/master/metrics/perceptual_path_length.py
+ """
+ if latent_space is None:
+ latent_space = generator.latent_space
+ assert latent_space in ["Z", "W"], f"Not supported latent space: {latent_space}"
+ assert len(upsample_size) == 2
+ epsilon = PPL_DEFAULTS["ppl_epsilon"]
+ interp = PPL_DEFAULTS['ppl_z_interp_mode']
+ similarity_name = PPL_DEFAULTS['ppl_sample_similarity']
+ sample_similarity_resize = PPL_DEFAULTS['ppl_sample_similarity_resize']
+ sample_similarity_dtype = PPL_DEFAULTS['ppl_sample_similarity_dtype']
+ discard_percentile_lower = PPL_DEFAULTS['ppl_discard_percentile_lower']
+ discard_percentile_higher = PPL_DEFAULTS['ppl_discard_percentile_higher']
+
+ vassert(type(epsilon) is float and epsilon > 0, 'Epsilon must be a small positive floating point number')
+ vassert(discard_percentile_lower is None or 0 < discard_percentile_lower < 100, 'Invalid percentile')
+ vassert(discard_percentile_higher is None or 0 < discard_percentile_higher < 100, 'Invalid percentile')
+ if discard_percentile_lower is not None and discard_percentile_higher is not None:
+ vassert(0 < discard_percentile_lower < discard_percentile_higher < 100, 'Invalid percentiles')
+
+ sample_similarity = create_sample_similarity(
+ similarity_name,
+ sample_similarity_resize=sample_similarity_resize,
+ sample_similarity_dtype=sample_similarity_dtype,
+ cuda=False,
+ **kwargs
+ )
+ sample_similarity = tops.to_cuda(sample_similarity)
+ rng = np.random.RandomState(get_kwarg('rng_seed', kwargs))
+ distances = []
+ if data_len is None:
+ data_len = len(dataloader) * dataloader.batch_size
+ z0 = sample_random(rng, (data_len, generator.z_channels), "normal")
+ z1 = sample_random(rng, (data_len, generator.z_channels), "normal")
+ if latent_space == "Z":
+ z1 = batch_interp(z0, z1, epsilon, interp)
+ print("Computing PPL IN", latent_space)
+ distances = torch.zeros(data_len, dtype=torch.float32, device=tops.get_device())
+ print(distances.shape)
+ end = 0
+ n_samples = 0
+ for it, batch in enumerate(utils.tqdm_(dataloader, desc="Perceptual Path Length")):
+ start = end
+ end = start + batch["img"].shape[0]
+ n_samples += batch["img"].shape[0]
+ batch_lat_e0 = tops.to_cuda(z0[start:end])
+ batch_lat_e1 = tops.to_cuda(z1[start:end])
+ if latent_space == "W":
+ w0 = generator.get_w(batch_lat_e0, update_emas=False)
+ w1 = generator.get_w(batch_lat_e1, update_emas=False)
+ w1 = w0.lerp(w1, epsilon) # PPL end
+ rgb1 = generator(**batch, w=w0)["img"]
+ rgb2 = generator(**batch, w=w1)["img"]
+ else:
+ rgb1 = generator(**batch, z=batch_lat_e0)["img"]
+ rgb2 = generator(**batch, z=batch_lat_e1)["img"]
+ if rgb1.shape[-2] < upsample_size[0] or rgb1.shape[-1] < upsample_size[1]:
+ rgb1 = resize(rgb1, upsample_size, antialias=True)
+ rgb2 = resize(rgb2, upsample_size, antialias=True)
+ rgb1 = utils.denormalize_img(rgb1).mul(255).byte()
+ rgb2 = utils.denormalize_img(rgb2).mul(255).byte()
+
+ sim = sample_similarity(rgb1, rgb2)
+ dist_lat_e01 = sim / (epsilon ** 2)
+ distances[start:end] = dist_lat_e01.view(-1)
+ distances = distances[:n_samples]
+ distances = tops.all_gather_uneven(distances).cpu().numpy()
+ if tops.rank() != 0:
+ return {"ppl/mean": -1, "ppl/std": -1}
+ if tops.rank() == 0:
+ cond, lo, hi = None, None, None
+ if discard_percentile_lower is not None:
+ lo = np.percentile(distances, discard_percentile_lower, interpolation='lower')
+ cond = lo <= distances
+ if discard_percentile_higher is not None:
+ hi = np.percentile(distances, discard_percentile_higher, interpolation='higher')
+ cond = np.logical_and(cond, distances <= hi)
+ if cond is not None:
+ distances = np.extract(cond, distances)
+ return {
+ "ppl/mean": float(np.mean(distances)),
+ "ppl/std": float(np.std(distances)),
+ }
+ else:
+ return {"ppl/mean"}
diff --git a/project/models/deprecated_deep_privacy2/dp2/metrics/torch_metrics.py b/project/models/deprecated_deep_privacy2/dp2/metrics/torch_metrics.py
new file mode 100644
index 0000000..56d9147
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/metrics/torch_metrics.py
@@ -0,0 +1,182 @@
+import pickle
+import numpy as np
+import torch
+import time
+from pathlib import Path
+from dp2 import utils
+import tops
+from .lpips import SampleSimilarityLPIPS
+from torch_fidelity.defaults import DEFAULTS as trf_defaults
+from torch_fidelity.metric_fid import fid_features_to_statistics, fid_statistics_to_metric
+from torch_fidelity.utils import create_feature_extractor
+lpips_model = None
+fid_model = None
+
+
+@torch.no_grad()
+def mse(images1: torch.Tensor, images2: torch.Tensor) -> torch.Tensor:
+ se = (images1 - images2) ** 2
+ se = se.view(images1.shape[0], -1).mean(dim=1)
+ return se
+
+
+@torch.no_grad()
+def psnr(images1: torch.Tensor, images2: torch.Tensor) -> torch.Tensor:
+ mse_ = mse(images1, images2)
+ psnr = 10 * torch.log10(1 / mse_)
+ return psnr
+
+
+@torch.no_grad()
+def lpips(images1: torch.Tensor, images2: torch.Tensor) -> torch.Tensor:
+ return _lpips_w_grad(images1, images2)
+
+
+def _lpips_w_grad(images1: torch.Tensor, images2: torch.Tensor) -> torch.Tensor:
+ global lpips_model
+ if lpips_model is None:
+ lpips_model = tops.to_cuda(SampleSimilarityLPIPS())
+
+ images1 = images1.mul(255)
+ images2 = images2.mul(255)
+ with torch.cuda.amp.autocast(tops.AMP()):
+ dists = lpips_model(images1, images2)[0].view(-1)
+ return dists
+
+
+@torch.no_grad()
+def compute_metrics_iteratively(
+ dataloader, generator,
+ cache_directory,
+ data_len=None,
+ truncation_value: float = None,
+ multi_modal_truncate=False,
+) -> dict:
+ """
+ Args:
+ n_samples (int): Creates N samples from same image to calculate stats
+ dataset_percentage (float): The percentage of the dataset to compute metrics on.
+ """
+
+ global lpips_model, fid_model
+ if lpips_model is None:
+ lpips_model = tops.to_cuda(SampleSimilarityLPIPS())
+ if fid_model is None:
+ fid_model = create_feature_extractor(
+ trf_defaults["feature_extractor"], [trf_defaults["feature_layer_fid"]], cuda=False)
+ fid_model = tops.to_cuda(fid_model)
+ cache_directory = Path(cache_directory)
+ start_time = time.time()
+ lpips_total = torch.tensor(0, dtype=torch.float32, device=tops.get_device())
+ diversity_total = torch.zeros_like(lpips_total)
+ fid_cache_path = cache_directory.joinpath("fid_stats.pkl")
+ has_fid_cache = fid_cache_path.is_file()
+ if data_len is None:
+ data_len = len(dataloader)*dataloader.batch_size
+ if not has_fid_cache:
+ fid_features_real = torch.zeros(data_len, 2048, dtype=torch.float32, device=tops.get_device())
+ fid_features_fake = torch.zeros(data_len, 2048, dtype=torch.float32, device=tops.get_device())
+ n_samples_seen = torch.tensor([0], dtype=torch.int32, device=tops.get_device())
+ eidx = 0
+ for batch in utils.tqdm_(iter(dataloader), desc="Computing FID, LPIPS and LPIPS Diversity"):
+ sidx = eidx
+ eidx = sidx + batch["img"].shape[0]
+ n_samples_seen += batch["img"].shape[0]
+ with torch.cuda.amp.autocast(tops.AMP()):
+ if multi_modal_truncate:
+ fakes1 = generator.multi_modal_truncate(n=batch["condition"].shape[0], truncation_value=0)["img"]
+ fakes2 = generator.multi_modal_truncate(n=batch["condition"].shape[0], truncation_value=0)["img"]
+ else:
+ fakes1 = generator.sample(**batch, truncation_value=truncation_value)["img"]
+ fakes2 = generator.sample(**batch, truncation_value=truncation_value)["img"]
+ fakes1 = utils.denormalize_img(fakes1).mul(255)
+ fakes2 = utils.denormalize_img(fakes2).mul(255)
+ real_data = utils.denormalize_img(batch["img"]).mul(255)
+ lpips_1, real_lpips_feats, fake1_lpips_feats = lpips_model(real_data, fakes1)
+ fake2_lpips_feats = lpips_model.get_feats(fakes2)
+ lpips_2 = lpips_model.lpips_from_feats(real_lpips_feats, fake2_lpips_feats)
+
+ lpips_total += lpips_1.sum().add(lpips_2.sum()).div(2)
+ diversity_total += lpips_model.lpips_from_feats(fake1_lpips_feats, fake2_lpips_feats).sum()
+ if not has_fid_cache:
+ fid_features_real[sidx:eidx] = fid_model(real_data.byte())[0]
+ fid_features_fake[sidx:eidx] = fid_model(fakes1.byte())[0]
+ fid_features_fake = fid_features_fake[:n_samples_seen]
+ if has_fid_cache:
+ if tops.rank() == 0:
+ with open(fid_cache_path, "rb") as fp:
+ fid_stat_real = pickle.load(fp)
+ else:
+ fid_features_real = fid_features_real[:n_samples_seen]
+ fid_features_real = tops.all_gather_uneven(fid_features_real).cpu()
+ if tops.rank() == 0:
+ fid_stat_real = fid_features_to_statistics(fid_features_real)
+ cache_directory.mkdir(exist_ok=True, parents=True)
+ with open(fid_cache_path, "wb") as fp:
+ pickle.dump(fid_stat_real, fp)
+ fid_features_fake = tops.all_gather_uneven(fid_features_fake).cpu()
+ if tops.rank() == 0:
+ print("Starting calculation of fid from features of shape:", fid_features_fake.shape)
+ fid_stat_fake = fid_features_to_statistics(fid_features_fake)
+ fid_ = fid_statistics_to_metric(fid_stat_real, fid_stat_fake, verbose=False)["frechet_inception_distance"]
+ tops.all_reduce(n_samples_seen, torch.distributed.ReduceOp.SUM)
+ tops.all_reduce(lpips_total, torch.distributed.ReduceOp.SUM)
+ tops.all_reduce(diversity_total, torch.distributed.ReduceOp.SUM)
+ lpips_total = lpips_total / n_samples_seen
+ diversity_total = diversity_total / n_samples_seen
+ to_return = dict(lpips=lpips_total, lpips_diversity=diversity_total)
+ if tops.rank() == 0:
+ to_return["fid"] = fid_
+ else:
+ to_return["fid"] = -1
+ to_return["validation_time_s"] = time.time() - start_time
+ return to_return
+
+
+@torch.no_grad()
+def compute_lpips(
+ dataloader, generator,
+ truncation_value: float = None,
+ data_len=None,
+ ) -> dict:
+ """
+ Args:
+ n_samples (int): Creates N samples from same image to calculate stats
+ dataset_percentage (float): The percentage of the dataset to compute metrics on.
+ """
+ global lpips_model, fid_model
+ if lpips_model is None:
+ lpips_model = tops.to_cuda(SampleSimilarityLPIPS())
+ start_time = time.time()
+ lpips_total = torch.tensor(0, dtype=torch.float32, device=tops.get_device())
+ diversity_total = torch.zeros_like(lpips_total)
+ if data_len is None:
+ data_len = len(dataloader) * dataloader.batch_size
+ eidx = 0
+ n_samples_seen = torch.tensor([0], dtype=torch.int32, device=tops.get_device())
+ for batch in utils.tqdm_(dataloader, desc="Validating on dataset."):
+ sidx = eidx
+ eidx = sidx + batch["img"].shape[0]
+ n_samples_seen += batch["img"].shape[0]
+ with torch.cuda.amp.autocast(tops.AMP()):
+ fakes1 = generator.sample(**batch, truncation_value=truncation_value)["img"]
+ fakes2 = generator.sample(**batch, truncation_value=truncation_value)["img"]
+ real_data = batch["img"]
+ fakes1 = utils.denormalize_img(fakes1).mul(255)
+ fakes2 = utils.denormalize_img(fakes2).mul(255)
+ real_data = utils.denormalize_img(real_data).mul(255)
+ lpips_1, real_lpips_feats, fake1_lpips_feats = lpips_model(real_data, fakes1)
+ fake2_lpips_feats = lpips_model.get_feats(fakes2)
+ lpips_2 = lpips_model.lpips_from_feats(real_lpips_feats, fake2_lpips_feats)
+
+ lpips_total += lpips_1.sum().add(lpips_2.sum()).div(2)
+ diversity_total += lpips_model.lpips_from_feats(fake1_lpips_feats, fake2_lpips_feats).sum()
+ tops.all_reduce(n_samples_seen, torch.distributed.ReduceOp.SUM)
+ tops.all_reduce(lpips_total, torch.distributed.ReduceOp.SUM)
+ tops.all_reduce(diversity_total, torch.distributed.ReduceOp.SUM)
+ lpips_total = lpips_total / n_samples_seen
+ diversity_total = diversity_total / n_samples_seen
+ to_return = dict(lpips=lpips_total, lpips_diversity=diversity_total)
+ to_return = {k: v.cpu().item() for k, v in to_return.items()}
+ to_return["validation_time_s"] = time.time() - start_time
+ return to_return
diff --git a/project/models/deprecated_deep_privacy2/dp2/utils/__init__.py b/project/models/deprecated_deep_privacy2/dp2/utils/__init__.py
new file mode 100644
index 0000000..d4edbac
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/utils/__init__.py
@@ -0,0 +1,24 @@
+import pathlib
+from tops.config import LazyConfig
+from .torch_utils import (
+ im2torch, im2numpy, denormalize_img, set_requires_grad, forward_D_fake,
+ binary_dilation, crop_box, remove_pad,
+ torch_wasserstein_loss
+)
+from .ema import EMA
+from .utils import init_tops, tqdm_, print_config, config_to_str, trange_
+from .cse import from_E_to_vertex
+
+
+def load_config(config_path):
+ config_path = pathlib.Path(config_path)
+ assert config_path.is_file(), config_path
+ cfg = LazyConfig.load(str(config_path))
+ cfg.output_dir = pathlib.Path(str(config_path).replace("configs", str(cfg.common.output_dir)).replace(".py", ""))
+ if cfg.common.experiment_name is None:
+ cfg.experiment_name = str(config_path)
+ else:
+ cfg.experiment_name = cfg.common.experiment_name
+ cfg.checkpoint_dir = cfg.output_dir.joinpath("checkpoints")
+ print("Saving outputs to:", cfg.output_dir)
+ return cfg
diff --git a/project/models/deprecated_deep_privacy2/dp2/utils/bufferless_video_capture.py b/project/models/deprecated_deep_privacy2/dp2/utils/bufferless_video_capture.py
new file mode 100644
index 0000000..dd5e100
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/utils/bufferless_video_capture.py
@@ -0,0 +1,32 @@
+import queue
+import threading
+import cv2
+
+
+class BufferlessVideoCapture:
+
+ def __init__(self, name, width=None, height=None):
+ self.cap = cv2.VideoCapture(name)
+ if width is not None and height is not None:
+ self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
+ self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
+ self.q = queue.Queue()
+ t = threading.Thread(target=self._reader)
+ t.daemon = True
+ t.start()
+
+ # read frames as soon as they are available, keeping only most recent one
+ def _reader(self):
+ while True:
+ ret, frame = self.cap.read()
+ if not ret:
+ break
+ if not self.q.empty():
+ try:
+ self.q.get_nowait() # discard previous (unprocessed) frame
+ except queue.Empty:
+ pass
+ self.q.put((ret, frame))
+
+ def read(self):
+ return self.q.get()
diff --git a/project/models/deprecated_deep_privacy2/dp2/utils/cse.py b/project/models/deprecated_deep_privacy2/dp2/utils/cse.py
new file mode 100644
index 0000000..cd3e01d
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/utils/cse.py
@@ -0,0 +1,21 @@
+import warnings
+import torch
+from densepose.modeling.cse.utils import get_closest_vertices_mask_from_ES
+
+
+def from_E_to_vertex(E, M, embed_map):
+ """
+ M is 1 for unkown regions
+ """
+ assert len(E.shape) == 4
+ assert len(E.shape) == len(M.shape), (E.shape, M.shape)
+ assert E.shape[0] == 1
+ M = M.float()
+ M = torch.cat([M, 1-M], dim=1)
+ with warnings.catch_warnings(): # Ignore userError for pytorch interpolate from detectron2
+ warnings.filterwarnings("ignore")
+ vertices, _ = get_closest_vertices_mask_from_ES(
+ E, M, E.shape[2], E.shape[3],
+ embed_map, device=E.device)
+
+ return vertices.long()
diff --git a/project/models/deprecated_deep_privacy2/dp2/utils/ema.py b/project/models/deprecated_deep_privacy2/dp2/utils/ema.py
new file mode 100644
index 0000000..475e6b5
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/utils/ema.py
@@ -0,0 +1,80 @@
+import torch
+import copy
+import tops
+from tops import logger
+from .torch_utils import set_requires_grad
+
+
+class EMA:
+ """
+ Expoenential moving average.
+ See:
+ Yazici, Y. et al.The unusual effectiveness of averaging in GAN training. ICLR 2019
+
+ """
+
+ def __init__(
+ self,
+ generator: torch.nn.Module,
+ batch_size: int,
+ rampup: float,
+ ):
+ self.rampup = rampup
+ self._nimg_half_time = batch_size * 10 / 32 * 1000
+ self._batch_size = batch_size
+ with torch.no_grad():
+ self.generator = copy.deepcopy(generator.cpu()).eval()
+ self.generator = tops.to_cuda(self.generator)
+ self.old_ra_beta = 0
+ set_requires_grad(self.generator, False)
+
+ def update_beta(self):
+ y = self._nimg_half_time
+ global_step = logger.global_step()
+ if self.rampup != None:
+ y = min(y, global_step*self.rampup)
+ self.ra_beta = 0.5 ** (self._batch_size/max(y, 1e-8))
+ if self.ra_beta != self.old_ra_beta:
+ logger.add_scalar("stats/EMA_beta", self.ra_beta)
+ self.old_ra_beta = self.ra_beta
+
+ @torch.no_grad()
+ def update(self, normal_G):
+ with torch.autograd.profiler.record_function("EMA_update"):
+ for ema_p, p in zip(self.generator.parameters(),
+ normal_G.parameters()):
+ ema_p.copy_(p.lerp(ema_p, self.ra_beta))
+ for ema_buf, buff in zip(self.generator.buffers(),
+ normal_G.buffers()):
+ ema_buf.copy_(buff)
+
+ def __call__(self, *args, **kwargs):
+ return self.generator(*args, **kwargs)
+
+ def __getattr__(self, name: str):
+ if hasattr(self.generator, name):
+ return getattr(self.generator, name)
+ raise AttributeError(f"Generator object has no attribute {name}")
+
+ def cuda(self, *args, **kwargs):
+ self.generator = self.generator.cuda()
+ return self
+
+ def state_dict(self, *args, **kwargs):
+ return self.generator.state_dict(*args, **kwargs)
+
+ def load_state_dict(self, *args, **kwargs):
+ return self.generator.load_state_dict(*args, **kwargs)
+
+ def eval(self):
+ self.generator.eval()
+
+ def train(self):
+ self.generator.train()
+
+ @property
+ def module(self):
+ return self.generator.module
+
+ def sample(self, *args, **kwargs):
+ return self.generator.sample(*args, **kwargs)
diff --git a/project/models/deprecated_deep_privacy2/dp2/utils/torch_utils.py b/project/models/deprecated_deep_privacy2/dp2/utils/torch_utils.py
new file mode 100644
index 0000000..80ab53e
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/utils/torch_utils.py
@@ -0,0 +1,140 @@
+import torch
+import tops
+
+
+def denormalize_img(image, mean=0.5, std=0.5):
+ image = image * std + mean
+ image = torch.clamp(image.float(), 0, 1)
+ image = (image * 255)
+ image = torch.round(image)
+ return image / 255
+
+
+@torch.no_grad()
+def im2numpy(images, to_uint8=False, denormalize=False):
+ if denormalize:
+ images = denormalize_img(images)
+ if images.dtype != torch.uint8:
+ images = images.clamp(0, 1)
+ return tops.im2numpy(images, to_uint8=to_uint8)
+
+
+@torch.no_grad()
+def im2torch(im, cuda=False, normalize=True, to_float=True):
+ im = tops.im2torch(im, cuda=cuda, to_float=to_float)
+ if normalize:
+ assert im.min() >= 0.0 and im.max() <= 1.0
+ if normalize:
+ im = im * 2 - 1
+ return im
+
+
+@torch.no_grad()
+def binary_dilation(im: torch.Tensor, kernel: torch.Tensor):
+ assert len(im.shape) == 4
+ assert len(kernel.shape) == 2
+ kernel = kernel.unsqueeze(0).unsqueeze(0)
+ padding = kernel.shape[-1]//2
+ assert kernel.shape[-1] % 2 != 0
+ if isinstance(im, torch.cuda.FloatTensor):
+ im, kernel = im.half(), kernel.half()
+ else:
+ im, kernel = im.float(), kernel.float()
+ im = torch.nn.functional.conv2d(
+ im, kernel, groups=im.shape[1], padding=padding)
+ im = im > 0.5
+ return im
+
+
+@torch.no_grad()
+def binary_erosion(im: torch.Tensor, kernel: torch.Tensor):
+ assert len(im.shape) == 4
+ assert len(kernel.shape) == 2
+ kernel = kernel.unsqueeze(0).unsqueeze(0)
+ padding = kernel.shape[-1]//2
+ assert kernel.shape[-1] % 2 != 0
+ if isinstance(im, torch.cuda.FloatTensor):
+ im, kernel = im.half(), kernel.half()
+ else:
+ im, kernel = im.float(), kernel.float()
+ ksum = kernel.sum()
+ padding = (padding, padding, padding, padding)
+ im = torch.nn.functional.pad(im, padding, mode="reflect")
+ im = torch.nn.functional.conv2d(
+ im, kernel, groups=im.shape[1])
+ return im.round() == ksum
+
+
+def set_requires_grad(value: torch.nn.Module, requires_grad: bool):
+ if isinstance(value, (list, tuple)):
+ for param in value:
+ param.requires_grad = requires_grad
+ return
+ for p in value.parameters():
+ p.requires_grad = requires_grad
+
+
+def forward_D_fake(batch, fake_img, discriminator, **kwargs):
+ fake_batch = {k: v for k, v in batch.items() if k != "img"}
+ fake_batch["img"] = fake_img
+ return discriminator(**fake_batch, **kwargs)
+
+
+def remove_pad(x: torch.Tensor, bbox_XYXY, imshape):
+ """
+ Remove padding that is shown as negative
+ """
+ H, W = imshape
+ x0, y0, x1, y1 = bbox_XYXY
+ padding = [
+ max(0, -x0),
+ max(0, -y0),
+ max(x1 - W, 0),
+ max(y1 - H, 0)
+ ]
+ x0, y0 = padding[:2]
+ x1 = x.shape[2] - padding[2]
+ y1 = x.shape[1] - padding[3]
+ return x[:, y0:y1, x0:x1]
+
+
+def crop_box(x: torch.Tensor, bbox_XYXY) -> torch.Tensor:
+ """
+ Crops x by bbox_XYXY.
+ """
+ x0, y0, x1, y1 = bbox_XYXY
+ x0 = max(x0, 0)
+ y0 = max(y0, 0)
+ x1 = min(x1, x.shape[-1])
+ y1 = min(y1, x.shape[-2])
+ return x[..., y0:y1, x0:x1]
+
+
+def torch_wasserstein_loss(tensor_a, tensor_b):
+ # Compute the first Wasserstein distance between two 1D distributions.
+ return (torch_cdf_loss(tensor_a, tensor_b, p=1))
+
+
+def torch_cdf_loss(tensor_a, tensor_b, p=1):
+ # last-dimension is weight distribution
+ # p is the norm of the distance, p=1 --> First Wasserstein Distance
+ # to get a positive weight with our normalized distribution
+ # we recommend combining this loss with other difference-based losses like L1
+
+ # normalize distribution, add 1e-14 to divisor to avoid 0/0
+ tensor_a = tensor_a / (torch.sum(tensor_a, dim=-1, keepdim=True) + 1e-14)
+ tensor_b = tensor_b / (torch.sum(tensor_b, dim=-1, keepdim=True) + 1e-14)
+ # make cdf with cumsum
+ cdf_tensor_a = torch.cumsum(tensor_a, dim=-1)
+ cdf_tensor_b = torch.cumsum(tensor_b, dim=-1)
+
+ # choose different formulas for different norm situations
+ if p == 1:
+ cdf_distance = torch.sum(torch.abs((cdf_tensor_a-cdf_tensor_b)), dim=-1)
+ elif p == 2:
+ cdf_distance = torch.sqrt(torch.sum(torch.pow((cdf_tensor_a-cdf_tensor_b), 2), dim=-1))
+ else:
+ cdf_distance = torch.pow(torch.sum(torch.pow(torch.abs(cdf_tensor_a-cdf_tensor_b), p), dim=-1), 1/p)
+
+ cdf_loss = cdf_distance.mean()
+ return cdf_loss
diff --git a/project/models/deprecated_deep_privacy2/dp2/utils/utils.py b/project/models/deprecated_deep_privacy2/dp2/utils/utils.py
new file mode 100644
index 0000000..f3dda0e
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/utils/utils.py
@@ -0,0 +1,30 @@
+import tops
+import tqdm
+from tops import logger, highlight_py_str
+from tops.config import LazyConfig
+
+
+def print_config(cfg):
+ logger.log("\n" + highlight_py_str(LazyConfig.to_py(cfg, prefix="")))
+
+
+def config_to_str(cfg):
+ return LazyConfig.to_py(cfg, prefix=".")
+
+
+def init_tops(cfg, reinit=False):
+ tops.init(
+ cfg.output_dir, cfg.common.logger_backend, cfg.experiment_name,
+ cfg.common.wandb_project, dict(cfg), reinit)
+
+
+def tqdm_(iterator, *args, **kwargs):
+ if tops.rank() == 0:
+ return tqdm.tqdm(iterator, *args, **kwargs)
+ return iterator
+
+
+def trange_(*args, **kwargs):
+ if tops.rank() == 0:
+ return tqdm.trange(*args, **kwargs)
+ return range(*args)
diff --git a/project/models/deprecated_deep_privacy2/dp2/utils/vis_utils.py b/project/models/deprecated_deep_privacy2/dp2/utils/vis_utils.py
new file mode 100644
index 0000000..ac09c66
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/dp2/utils/vis_utils.py
@@ -0,0 +1,440 @@
+import torch
+import tops
+import cv2
+import torchvision.transforms.functional as F
+from typing import Optional, List, Union, Tuple
+from .cse import from_E_to_vertex
+import numpy as np
+from tops import download_file
+from .torch_utils import (
+ denormalize_img, binary_dilation, binary_erosion,
+ remove_pad, crop_box)
+from torchvision.utils import _generate_color_palette
+from PIL import Image, ImageColor, ImageDraw
+
+
+def get_coco_keypoints():
+ # From: https://github.com/facebookresearch/Detectron/blob/main/detectron/utils/keypoints.py
+ keypoints = [
+ 'nose',
+ 'left_eye',
+ 'right_eye',
+ 'left_ear',
+ 'right_ear',
+ 'left_shoulder',
+ 'right_shoulder',
+ 'left_elbow',
+ 'right_elbow',
+ 'left_wrist',
+ 'right_wrist',
+ 'left_hip',
+ 'right_hip',
+ 'left_knee',
+ 'right_knee',
+ 'left_ankle',
+ 'right_ankle'
+ ]
+ keypoint_flip_map = {
+ 'left_eye': 'right_eye',
+ 'left_ear': 'right_ear',
+ 'left_shoulder': 'right_shoulder',
+ 'left_elbow': 'right_elbow',
+ 'left_wrist': 'right_wrist',
+ 'left_hip': 'right_hip',
+ 'left_knee': 'right_knee',
+ 'left_ankle': 'right_ankle'
+ }
+ connectivity = {
+ "nose": "left_eye",
+ "left_eye": "right_eye",
+ "right_eye": "nose",
+ "left_ear": "left_eye",
+ "right_ear": "right_eye",
+ "left_shoulder": "nose",
+ "right_shoulder": "nose",
+ "left_elbow": "left_shoulder",
+ "right_elbow": "right_shoulder",
+ "left_wrist": "left_elbow",
+ "right_wrist": "right_elbow",
+ "left_hip": "left_shoulder",
+ "right_hip": "right_shoulder",
+ "left_knee": "left_hip",
+ "right_knee": "right_hip",
+ "left_ankle": "left_knee",
+ "right_ankle": "right_knee"
+ }
+ connectivity_indices = [
+ (sidx, keypoints.index(connectivity[kp]))
+ for sidx, kp in enumerate(keypoints)
+ ]
+ return keypoints, keypoint_flip_map, connectivity_indices
+
+
+def get_coco_colors():
+ return [
+ *["red"]*5,
+ "blue",
+ "green",
+ "blue",
+ "green",
+ "blue",
+ "green",
+ "purple",
+ "orange",
+ "purple",
+ "orange",
+ "purple",
+ "orange",
+ ]
+
+
+@torch.no_grad()
+def draw_keypoints(
+ image: torch.Tensor,
+ keypoints: torch.Tensor,
+ connectivity: Optional[List[Tuple[int, int]]] = None,
+ visible: Optional[List[List[bool]]] = None,
+ colors: Optional[Union[str, Tuple[int, int, int]]] = None,
+ radius: int = None,
+ width: int = None,
+) -> torch.Tensor:
+ """
+ Function taken from torchvision source code. Added in torchvision 0.12
+
+ Draws Keypoints on given RGB image.
+ The values of the input image should be uint8 between 0 and 255.
+
+ Args:
+ image (Tensor): Tensor of shape (3, H, W) and dtype uint8.
+ keypoints (Tensor): Tensor of shape (num_instances, K, 2) the K keypoints location for each of the N instances,
+ in the format [x, y].
+ connectivity (List[Tuple[int, int]]]): A List of tuple where,
+ each tuple contains pair of keypoints to be connected.
+ colors (str, Tuple): The color can be represented as
+ PIL strings e.g. "red" or "#FF00FF", or as RGB tuples e.g. ``(240, 10, 157)``.
+ radius (int): Integer denoting radius of keypoint.
+ width (int): Integer denoting width of line connecting keypoints.
+
+ Returns:
+ img (Tensor[C, H, W]): Image Tensor of dtype uint8 with keypoints drawn.
+ """
+
+ if not isinstance(image, torch.Tensor):
+ raise TypeError(f"The image must be a tensor, got {type(image)}")
+ elif image.dtype != torch.uint8:
+ raise ValueError(f"The image dtype must be uint8, got {image.dtype}")
+ elif image.dim() != 3:
+ raise ValueError("Pass individual images, not batches")
+ elif image.size()[0] != 3:
+ raise ValueError("Pass an RGB image. Other Image formats are not supported")
+
+ if keypoints.ndim != 3:
+ raise ValueError("keypoints must be of shape (num_instances, K, 2)")
+ if width is None:
+ width = int(max(max(image.shape[-2:]) * 0.01, 1))
+ if radius is None:
+ radius = int(max(max(image.shape[-2:]) * 0.01, 1))
+
+ ndarr = image.permute(1, 2, 0).cpu().numpy()
+ img_to_draw = Image.fromarray(ndarr)
+ draw = ImageDraw.Draw(img_to_draw)
+ if isinstance(keypoints, torch.Tensor):
+ img_kpts = keypoints.to(torch.int64).tolist()
+ else:
+ assert isinstance(keypoints, np.ndarray)
+ img_kpts = keypoints.astype(int).tolist()
+ colors = get_coco_colors()
+ for inst_id, kpt_inst in enumerate(img_kpts):
+
+ for kpt_id, kpt in enumerate(kpt_inst):
+ if visible is not None and int(visible[inst_id][kpt_id]) == 0:
+ continue
+ x1 = kpt[0] - radius
+ x2 = kpt[0] + radius
+ y1 = kpt[1] - radius
+ y2 = kpt[1] + radius
+
+ draw.ellipse([x1, y1, x2, y2], fill=colors[kpt_id], outline=None, width=0)
+
+ if connectivity is not None:
+ for connection in connectivity:
+ if connection[1] >= len(kpt_inst) or connection[0] >= len(kpt_inst):
+ continue
+ if visible is not None and (int(visible[inst_id][connection[1]]) == 0 or int(visible[inst_id][connection[0]]) == 0):
+ continue
+
+ start_pt_x = kpt_inst[connection[0]][0]
+ start_pt_y = kpt_inst[connection[0]][1]
+
+ end_pt_x = kpt_inst[connection[1]][0]
+ end_pt_y = kpt_inst[connection[1]][1]
+
+ draw.line(
+ ((start_pt_x, start_pt_y), (end_pt_x, end_pt_y)),
+ width=width, fill=colors[connection[1]]
+ )
+
+ return torch.from_numpy(np.array(img_to_draw)).permute(2, 0, 1).to(dtype=torch.uint8)
+
+
+def visualize_keypoints(img, keypoints):
+ img = img.clone()
+ keypoints = keypoints.clone()
+ keypoints[:, :, 0] *= img.shape[-1]
+ keypoints[:, :, 1] *= img.shape[-2]
+ _, _, connectivity = get_coco_keypoints()
+ connectivity = np.array(connectivity)
+ visible = None
+ if keypoints.shape[-1] == 3:
+ visible = keypoints[:, :, 2] > 0
+ for idx in range(img.shape[0]):
+ img[idx] = draw_keypoints(
+ img[idx], keypoints[idx:idx+1].long(), colors="red",
+ connectivity=connectivity, visible=visible[idx:idx+1])
+ return img
+
+
+def visualize_batch(
+ img: torch.Tensor, mask: torch.Tensor,
+ vertices: torch.Tensor = None,
+ E_mask: torch.Tensor = None,
+ embed_map: torch.Tensor = None,
+ semantic_mask: torch.Tensor = None,
+ embedding: torch.Tensor = None,
+ keypoints: torch.Tensor = None,
+ maskrcnn_mask: torch.Tensor = None,
+ **kwargs) -> torch.ByteTensor:
+ img = denormalize_img(img).mul(255).round().clamp(0, 255).byte()
+ img = draw_mask(img, mask)
+ if maskrcnn_mask is not None and maskrcnn_mask.shape == mask.shape:
+ img = draw_mask(img, maskrcnn_mask)
+ if vertices is not None or embedding is not None:
+ assert E_mask is not None
+ assert embed_map is not None
+ img, E_mask, embedding, embed_map, vertices = tops.to_cpu([
+ img, E_mask, embedding, embed_map, vertices
+ ])
+ img = draw_cse(img, E_mask, embedding, embed_map, vertices)
+ elif semantic_mask is not None:
+ img = draw_segmentation_masks(img, semantic_mask)
+ if keypoints is not None:
+ img = visualize_keypoints(img, keypoints)
+ return img
+
+
+@torch.no_grad()
+def draw_cse(
+ img: torch.Tensor, E_seg: torch.Tensor,
+ embedding: torch.Tensor = None,
+ embed_map: torch.Tensor = None,
+ vertices: torch.Tensor = None, t=0.7
+):
+ """
+ E_seg: 1 for areas with embedding
+ """
+ assert img.dtype == torch.uint8
+ img = img.view(-1, *img.shape[-3:])
+ E_seg = E_seg.view(-1, 1, *E_seg.shape[-2:])
+ if vertices is None:
+ assert embedding is not None
+ assert embed_map is not None
+ embedding = embedding.view(-1, *embedding.shape[-3:])
+ vertices = torch.stack(
+ [from_E_to_vertex(e[None], e_seg[None].logical_not().float(), embed_map)
+ for e, e_seg in zip(embedding, E_seg)])
+
+ i = np.arange(0, 256, dtype=np.uint8).reshape(1, -1)
+ colormap_JET = torch.from_numpy(cv2.applyColorMap(i, cv2.COLORMAP_JET)[0])
+ color_embed_map, _ = np.load(download_file(
+ "https://dl.fbaipublicfiles.com/densepose/data/cse/mds_d=256.npy"), allow_pickle=True)
+ color_embed_map = torch.from_numpy(color_embed_map).float()[:, 0]
+ color_embed_map -= color_embed_map.min()
+ color_embed_map /= color_embed_map.max()
+ vertx2idx = (color_embed_map*255).long()
+ vertx2colormap = colormap_JET[vertx2idx]
+
+ vertices = vertices.view(-1, *vertices.shape[-2:])
+ E_seg = E_seg.view(-1, 1, *E_seg.shape[-2:])
+ # This operation might be good to do on cpu...
+
+ E_color = vertx2colormap[vertices.long()]
+ E_color = E_color.to(E_seg.device)
+ E_color = E_color.permute(0, 3, 1, 2)
+ E_color = E_color*E_seg.byte()
+
+ m = E_seg.bool().repeat(1, 3, 1, 1)
+ img[m] = (img[m] * (1-t) + t * E_color[m]).byte()
+ return img
+
+
+def draw_cse_all(
+ embedding: List[torch.Tensor], E_mask: List[torch.Tensor],
+ im: torch.Tensor, boxes_XYXY: list, embed_map: torch.Tensor, t=0.7):
+ """
+ E_seg: 1 for areas with embedding
+ """
+ assert len(im.shape) == 3, im.shape
+ assert im.dtype == torch.uint8
+
+ N = len(E_mask)
+ im = im.clone()
+ for i in range(N):
+ assert len(E_mask[i].shape) == 2
+ assert len(embedding[i].shape) == 3
+ assert embed_map.shape[1] == embedding[i].shape[0]
+ assert len(boxes_XYXY[i]) == 4
+ E = embedding[i]
+ x0, y0, x1, y1 = boxes_XYXY[i]
+ E = F.resize(E, (y1-y0, x1-x0), antialias=True)
+ s = E_mask[i].float()
+ s = (F.resize(s.squeeze()[None], (y1-y0, x1-x0), antialias=True) > 0).float()
+ box = boxes_XYXY[i]
+
+ im_ = crop_box(im, box)
+ s = remove_pad(s, box, im.shape[1:])
+ E = remove_pad(E, box, im.shape[1:])
+ E_color = draw_cse(img=im_, E_seg=s[None], embedding=E[None], embed_map=embed_map)[0]
+ E_color = E_color.to(im.device)
+ s = s.bool().repeat(3, 1, 1)
+ crop_box(im, box)[s] = (im_[s] * (1-t) + t * E_color[s]).byte()
+ return im
+
+
+@torch.no_grad()
+def draw_segmentation_masks(
+ image: torch.Tensor,
+ masks: torch.Tensor,
+ alpha: float = 0.8,
+ colors: Optional[List[Union[str, Tuple[int, int, int]]]] = None,
+) -> torch.Tensor:
+ """
+ Draws segmentation masks on given RGB image.
+ The values of the input image should be uint8 between 0 and 255.
+
+ Args:
+ image (Tensor): Tensor of shape (3, H, W) and dtype uint8.
+ masks (Tensor): Tensor of shape (num_masks, H, W) or (H, W) and dtype bool.
+ alpha (float): Float number between 0 and 1 denoting the transparency of the masks.
+ 0 means full transparency, 1 means no transparency.
+ colors (list or None): List containing the colors of the masks. The colors can
+ be represented as PIL strings e.g. "red" or "#FF00FF", or as RGB tuples e.g. ``(240, 10, 157)``.
+ When ``masks`` has a single entry of shape (H, W), you can pass a single color instead of a list
+ with one element. By default, random colors are generated for each mask.
+
+ Returns:
+ img (Tensor[C, H, W]): Image Tensor, with segmentation masks drawn on top.
+ """
+
+ if not isinstance(image, torch.Tensor):
+ raise TypeError(f"The image must be a tensor, got {type(image)}")
+ elif image.dtype != torch.uint8:
+ raise ValueError(f"The image dtype must be uint8, got {image.dtype}")
+ elif image.dim() != 3:
+ raise ValueError("Pass individual images, not batches")
+ elif image.size()[0] != 3:
+ raise ValueError("Pass an RGB image. Other Image formats are not supported")
+ if masks.ndim == 2:
+ masks = masks[None, :, :]
+ if masks.ndim != 3:
+ raise ValueError("masks must be of shape (H, W) or (batch_size, H, W)")
+ if masks.dtype != torch.bool:
+ raise ValueError(f"The masks must be of dtype bool. Got {masks.dtype}")
+ if masks.shape[-2:] != image.shape[-2:]:
+ raise ValueError("The image and the masks must have the same height and width")
+ num_masks = masks.size()[0]
+ if num_masks == 0:
+ return image
+ if colors is None:
+ colors = _generate_color_palette(num_masks)
+ if not isinstance(colors[0], (Tuple, List)):
+ colors = [colors for i in range(num_masks)]
+ if colors is not None and num_masks > len(colors):
+ raise ValueError(f"There are more masks ({num_masks}) than colors ({len(colors)})")
+
+ if not isinstance(colors, list):
+ colors = [colors]
+ if not isinstance(colors[0], (tuple, str)):
+ raise ValueError("colors must be a tuple or a string, or a list thereof")
+ if isinstance(colors[0], tuple) and len(colors[0]) != 3:
+ raise ValueError("It seems that you passed a tuple of colors instead of a list of colors")
+
+ out_dtype = torch.uint8
+
+ colors_ = []
+ for color in colors:
+ if isinstance(color, str):
+ color = ImageColor.getrgb(color)
+ color = torch.tensor(color, dtype=out_dtype, device=masks.device)
+ colors_.append(color)
+ img_to_draw = image.detach().clone()
+ # TODO: There might be a way to vectorize this
+ for mask, color in zip(masks, colors_):
+ img_to_draw[:, mask] = color[:, None]
+
+ out = image * (1 - alpha) + img_to_draw * alpha
+ return out.to(out_dtype)
+
+
+def draw_mask(im: torch.Tensor, mask: torch.Tensor, t=0.2, color=(255, 255, 255), visualize_instances=True):
+ """
+ Visualize mask where mask = 0.
+ Supports multiple instances.
+ mask shape: [N, C, H, W], where C is different instances in same image.
+ """
+ orig_imshape = im.shape
+ if mask.numel() == 0:
+ return im
+ assert len(mask.shape) in (3, 4), mask.shape
+ mask = mask.view(-1, *mask.shape[-3:])
+ im = im.view(-1, *im.shape[-3:])
+ assert im.dtype == torch.uint8, im.dtype
+ assert 0 <= t <= 1
+ if not visualize_instances:
+ mask = mask.any(dim=1, keepdim=True)
+ mask = mask.bool()
+ kernel = torch.ones((3, 3), dtype=mask.dtype, device=mask.device)
+ outer_border = binary_dilation(mask, kernel).logical_xor(mask)
+ outer_border = outer_border.any(dim=1, keepdim=True).repeat(1, 3, 1, 1) > 0
+ inner_border = binary_erosion(mask, kernel).logical_xor(mask)
+ inner_border = inner_border.any(dim=1, keepdim=True).repeat(1, 3, 1, 1) > 0
+ mask = (mask == 0).any(dim=1, keepdim=True).repeat(1, 3, 1, 1)
+ color = torch.tensor(color).to(im.device).byte().view(1, 3, 1, 1) # .repeat(1, *im.shape[1:])
+ color = color.repeat(im.shape[0], 1, *im.shape[-2:])
+ im[mask] = (im[mask] * (1-t) + t * color[mask]).byte()
+ im[outer_border] = 255
+ im[inner_border] = 0
+ return im.view(*orig_imshape)
+
+
+def draw_cropped_masks(im: torch.Tensor, mask: torch.Tensor, boxes: torch.Tensor, **kwargs):
+ for i, box in enumerate(boxes):
+ x0, y0, x1, y1 = boxes[i]
+ orig_shape = (y1-y0, x1-x0)
+ m = F.resize(mask[i], orig_shape, F.InterpolationMode.NEAREST).squeeze()[None]
+ m = remove_pad(m, boxes[i], im.shape[-2:])
+ crop_box(im, boxes[i]).set_(draw_mask(crop_box(im, boxes[i]), m))
+ return im
+
+
+def draw_cropped_keypoints(im: torch.Tensor, all_keypoints: torch.Tensor, boxes: torch.Tensor, **kwargs):
+ n_boxes = boxes.shape[0]
+ tops.assert_shape(all_keypoints, (n_boxes, 17, 3))
+ im = im.clone()
+ for i, box in enumerate(boxes):
+
+ x0, y0, x1, y1 = boxes[i]
+ orig_shape = (y1-y0, x1-x0)
+ keypoints = all_keypoints[i].clone()
+ keypoints[:, 0] *= orig_shape[1]
+ keypoints[:, 1] *= orig_shape[0]
+ keypoints = keypoints.long()
+ _, _, connectivity = get_coco_keypoints()
+ connectivity = np.array(connectivity)
+ visible = (keypoints[:, 2] > .5)
+ # Remove padding from keypoints before visualization
+ keypoints[:, 0] += min(x0, 0)
+ keypoints[:, 1] += min(y0, 0)
+ im_with_kp = draw_keypoints(
+ crop_box(im, box), keypoints[None], colors="red", connectivity=connectivity, visible=visible[None])
+ crop_box(im, box).copy_(im_with_kp)
+ return im
diff --git a/project/models/deprecated_deep_privacy2/face_obfuscator.py b/project/models/deprecated_deep_privacy2/face_obfuscator.py
new file mode 100644
index 0000000..8073925
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/face_obfuscator.py
@@ -0,0 +1,65 @@
+import cv2
+import torch
+import tops
+import tqdm
+import click
+import hashlib
+import numpy as np
+from dp2 import utils
+from PIL import Image
+from tops import logger
+from pathlib import Path
+from typing import Optional
+import moviepy.editor as mp
+from tops.config import instantiate
+from detectron2.data.detection_utils import _apply_exif_orientation
+from dp2.utils.bufferless_video_capture import BufferlessVideoCapture
+import os
+
+class DEEP_PRIVACY2():
+ def __init__(self):
+ pass
+
+ def obfuscate(self, face_img):
+ pass
+
+
+app = FastAPI()
+if torch.cuda.is_available():
+ print("torch version: ", torch.__version__, "cuda: ", torch.version.cuda)
+deep_privacy2 = None
+image_processing_path = "C:/Users/bijan/Desktop/obfuscation_platform/project/models/deep_privacy2/image_cache/"
+
+@app.get("/init")
+def init():
+ try:
+ print("initiating face_anon_simple")
+ global deep_privacy2
+ deep_privacy2 = DEEP_PRIVACY2()
+
+
+@app.get("/obfuscate")
+def obfuscate_api():
+ #TODO usw
+ global deep_privacy2
+ obfuscated_img = deep_privacy2.obfuscate(img)
+ #obfuscated_img.save(os.path.join(image_processing_path, "obfuscated_face.jpg"))
+
+@app.get("/health")
+def health(): return {"ok": True}
+
+
+
+def main():
+ print("TEST RUN")
+ obfuscator = FACE_ANON_SIMPLE()
+ print("INIT DONE")
+ original_image = load_image("my_dataset/test/face.jpg")
+ print("Image LOADING DONE")
+ obfuscated = obfuscator.obfuscate(original_image)
+ print("OBFUSCATION DONE")
+ obfuscated.save("anon.png")
+ print("SAVING DONE")
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/gradio_demos/body_cse.py b/project/models/deprecated_deep_privacy2/gradio_demos/body_cse.py
new file mode 100644
index 0000000..2ddf185
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/gradio_demos/body_cse.py
@@ -0,0 +1,23 @@
+import gradio
+from dp2 import utils
+from tops.config import instantiate
+import gradio.inputs
+from gradio_demos.modules import ExampleDemo, WebcamDemo
+
+
+cfg_body = utils.load_config("configs/anonymizers/FB_cse.py")
+anonymizer_body = instantiate(cfg_body.anonymizer, load_cache=False)
+anonymizer_body.initialize_tracker(fps=1)
+
+
+with gradio.Blocks() as demo:
+ gradio.Markdown("#
")
+ gradio.Markdown("---")
+ gradio.Image(value="media/gan_architecture.png")
+
+
+def pil2torch(img: Image.Image):
+ img = img.convert("RGB")
+ img = np.array(img)
+ img = np.rollaxis(img, 2)
+ return torch.from_numpy(img), None
diff --git a/project/models/deprecated_deep_privacy2/media/erling.jpg b/project/models/deprecated_deep_privacy2/media/erling.jpg
new file mode 100644
index 0000000..03fdccd
Binary files /dev/null and b/project/models/deprecated_deep_privacy2/media/erling.jpg differ
diff --git a/project/models/deprecated_deep_privacy2/media/g7_leaders.jpg b/project/models/deprecated_deep_privacy2/media/g7_leaders.jpg
new file mode 100644
index 0000000..c1a1038
Binary files /dev/null and b/project/models/deprecated_deep_privacy2/media/g7_leaders.jpg differ
diff --git a/project/models/deprecated_deep_privacy2/media/regjeringen.jpg b/project/models/deprecated_deep_privacy2/media/regjeringen.jpg
new file mode 100644
index 0000000..00c7242
Binary files /dev/null and b/project/models/deprecated_deep_privacy2/media/regjeringen.jpg differ
diff --git a/project/models/deprecated_deep_privacy2/media/stylemc_example.jpg b/project/models/deprecated_deep_privacy2/media/stylemc_example.jpg
new file mode 100644
index 0000000..afc55f9
Binary files /dev/null and b/project/models/deprecated_deep_privacy2/media/stylemc_example.jpg differ
diff --git a/project/models/deprecated_deep_privacy2/readme.md b/project/models/deprecated_deep_privacy2/readme.md
new file mode 100644
index 0000000..be299fb
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/readme.md
@@ -0,0 +1,118 @@
+
+
+# DeepPrivacy2 - A Toolbox for Realistic Image Anonymization
+[[Paper]](https://openaccess.thecvf.com/content/WACV2023/papers/Hukkelas_DeepPrivacy2_Towards_Realistic_Full-Body_Anonymization_WACV_2023_paper.pdf) [[Appendix]](https://openaccess.thecvf.com/content/WACV2023/supplemental/Hukkelas_DeepPrivacy2_Towards_Realistic_WACV_2023_supplemental.pdf)
+[[Video Demo]](https://youtu.be/Kt3au719hhk)
+[[Documentation]](http://hukkelas.no/deep_privacy2/)
+[](https://huggingface.co/spaces/haakohu/deep_privacy2)
+
+
+
+DeepPrivacy2 is a toolbox for realistic anonymization of humans, including a face and a full-body anonymizer.
+
+
+
+
+
+
+
+
+
+
+DeepPrivacy first detects, then recursively anonymization all individuals in an image with a Generative Adversarial Network (GAN) that synthesizes one individual at a time.
+
+
+
+## Published Papers
+This repository provide source code for the following papers
+
+- [[PDF]](https://openaccess.thecvf.com/content/WACV2023/papers/Hukkelas_DeepPrivacy2_Towards_Realistic_Full-Body_Anonymization_WACV_2023_paper.pdf) [[Appendix]](https://openaccess.thecvf.com/content/WACV2023/supplemental/Hukkelas_DeepPrivacy2_Towards_Realistic_WACV_2023_supplemental.pdf) [[Conference Presentation]](https://youtu.be/wwKRkkzxKuM) DeepPrivacy2: Towards Realistic Full-Body Anonymization. Published at WACV 2023.
+- [[PDF]](https://openaccess.thecvf.com/content/CVPR2023W/WAD/papers/Hukkelas_Does_Image_Anonymization_Impact_Computer_Vision_Training_CVPRW_2023_paper.pdf) [[Appendix]](https://openaccess.thecvf.com/content/CVPR2023W/WAD/supplemental/Hukkelas_Does_Image_Anonymization_CVPRW_2023_supplemental.pdf) Does Image Anonymization Impact Computer Vision Training? Published at CVPR Workshop on Autonomous Driving 2023.
+- [[PDF]](https://arxiv.org/pdf/2304.03164) [[Appendix]](https://api.loke.aws.unit.no/dlr-gui-backend-resources-content/v2/contents/links/09a4db16-7c09-4de5-890d-60ad608813b9ed8ba261-2b76-499d-ad50-f5351a5518e54be5b525-0280-4d04-97bd-8a701e3e5f42) Synthesizing Anyone, Anywhere, in Any Pose.
+
+
+## DeepPrivacy2 vs [DeepPrivacy1](https://github.com/hukkelas/DeepPrivacy)
+
+This repository improves over the original [DeepPrivacy](https://github.com/hukkelas/DeepPrivacy) repository with the following new features:
+- **Full-body anonymization:** Anonymize the entire human body with a single generator
+- **Improved Face Anonymization:** Improved quality and higher resolution (256x256 vs. 128x128) face anonymization without relying on facial landmark detection.
+- **Attribute Guided Anonymiation:** Anonymize faces guided on text prompts using [StyleMC](https://github.com/catlab-team/stylemc) - [[Video Demo]](https://www.youtube.com/watch?v=faoNyaaORts).
+- **Code cleanup and general improvements:** Extensive refactoring, bugfixes, and improvements yielding improved results and faster training.
+
+## Useful Links
+
+- [Installation instructions](https://www.hukkelas.no/deep_privacy2/#/README).
+- [Anonymization Instructions](https://www.hukkelas.no/deep_privacy2/#/anonymization).
+- [Training Instructions](https://www.hukkelas.no/deep_privacy2/#/training_and_development).
+
+## Quick Start
+
+### Installation
+We recommend to setup and install pytorch with [anaconda](https://www.anaconda.com/) following the [pytorch installation instructions](https://pytorch.org/get-started/locally/).
+
+1. Clone repository: `git clone https://github.com/hukkelas/deep_privacy2/`.
+2. Install using `setup.py`:
+```
+pip install -e .
+```
+or:
+```
+pip install git+https://github.com/hukkelas/deep_privacy2/
+```
+
+See the [documentation](https://www.hukkelas.no/deep_privacy2/#/) for more installation instructions.
+
+### Anonymization
+[anonymize.py](anonymize.py) is the main script for anonymization.
+
+**Full-Body Anonymization**
+```
+python3 anonymize.py configs/anonymizers/FB_cse.py -i media/regjeringen.jpg --output_path output.png --visualize
+```
+**Face Anonymization**
+```
+python3 anonymize.py configs/anonymizers/face.py -i media/regjeringen.jpg --output_path output.png --visualize
+```
+**Webcam anonymization**
+```
+python3 anonymize.py configs/anonymizers/FB_cse.py --webcam
+```
+
+
+See the [documentation](https://www.hukkelas.no/deep_privacy2/#/anonymization) for more detailed instructions for anonymization.
+
+### Gradio Demos
+The repository includes gradio demos to show of the capabilities of DeepPrivacy2.
+
+**Face anonymization**. Test it on [Hugging Face](https://huggingface.co/spaces/haakohu/deep_privacy2_face).
+```
+python3 -m gradio_demos.face
+```
+
+**Full-body anonymization**. Test it on [Hugging Face](https://huggingface.co/spaces/haakohu/deep_privacy2).
+```
+python3 -m gradio_demos.body_cse
+```
+
+
+## License
+This repsitory is released under [Apache 2.0 License](License), except for the following:.
+
+- Code under `sg3_torch_utils/`. This code is modified from [github.com/NVlabs/stylegan2-ada-pytorch](https://github.com/NVlabs/stylegan2-ada-pytorch). Separate license is attached in the directory.
+- Detection network: See [Detectron2 License](https://github.com/facebookresearch/detectron2/blob/main/LICENSE).
+- All checkpoints follow the license of the datasets. See the respective datasets for more information.
+- Code under `dp2/detection/models/vit_pose`. This code is modified from [https://github.com/gpastal24/ViTPose-Pytorch](https://github.com/gpastal24/ViTPose-Pytorch), where code is adapted from OpenMMLab. Original license is [Apache 2-0](https://github.com/open-mmlab/mmpose/blob/master/LICENSE).
+
+## Citation
+If you find this repository useful, please cite:
+```
+@inproceedings{hukkelas23DP2,
+ author={Hukkelås, Håkon and Lindseth, Frank},
+ booktitle={2023 IEEE/CVF Winter Conference on Applications of Computer Vision (WACV)},
+ title={DeepPrivacy2: Towards Realistic Full-Body Anonymization},
+ year={2023},
+ volume={},
+ number={},
+ pages={1329-1338},
+ doi={10.1109/WACV56688.2023.00138}}
+```
diff --git a/project/models/deprecated_deep_privacy2/setup.py b/project/models/deprecated_deep_privacy2/setup.py
new file mode 100644
index 0000000..3cc1ae0
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/setup.py
@@ -0,0 +1,46 @@
+import torch
+import torchvision
+from setuptools import setup, find_packages
+
+torch_ver = [int(x) for x in torch.__version__.split(".")[:2]]
+assert torch_ver >= [1, 9], "Requires PyTorch >= 1.9"
+torchvision_ver = [int(x) for x in torchvision.__version__.split(".")[:2]]
+assert torchvision_ver >= [0, 11], "Requires torchvision >= 0.11"
+
+setup(
+ name="dp2",
+ version="0.1.0",
+ packages=find_packages(),
+ install_requires=[
+ "numpy>=1.20",
+ "cython",
+ "matplotlib",
+ "tqdm",
+ "tensorboard",
+ "opencv-python",
+ "detectron2-densepose@git+https://github.com/facebookresearch/detectron2@96c752ce821a3340e27edd51c28a00665dd32a30#subdirectory=projects/DensePose",
+ "torch_fidelity==0.3.0",
+ "ninja==1.10.2",
+ "moviepy",
+ "pyspng",
+ "face_detection@git+https://github.com/hukkelas/DSFD-Pytorch-Inference",
+ "wandb",
+ "termcolor",
+ "tops@git+https://github.com/hukkelas/torch_ops.git",
+ "motpy@git+https://github.com/wmuron/motpy@c77f85d27e371c0a298e9a88ca99292d9b9cbe6b",
+ "fast_pytorch_kmeans",
+ "einops",
+ "einops_exts",
+ "regex",
+ "setuptools==59.5.0",
+ "resize_right==0.0.2",
+ "pillow==8.3.1",
+ "scipy==1.7.1",
+ "webdataset==0.2.26",
+ "scikit-image",
+ "imageio==2.4.1",
+ "timm==0.6.7",
+ "clip@git+https://github.com/openai/CLIP.git@b46f5ac7587d2e1862f8b7b1573179d80dcdd620",
+
+ ],
+)
diff --git a/project/models/deprecated_deep_privacy2/sg3_torch_utils/LICENSE.txt b/project/models/deprecated_deep_privacy2/sg3_torch_utils/LICENSE.txt
new file mode 100644
index 0000000..6b5ee9b
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/sg3_torch_utils/LICENSE.txt
@@ -0,0 +1,97 @@
+Copyright (c) 2021, NVIDIA Corporation & affiliates. All rights reserved.
+
+
+NVIDIA Source Code License for StyleGAN3
+
+
+=======================================================================
+
+1. Definitions
+
+"Licensor" means any person or entity that distributes its Work.
+
+"Software" means the original work of authorship made available under
+this License.
+
+"Work" means the Software and any additions to or derivative works of
+the Software that are made available under this License.
+
+The terms "reproduce," "reproduction," "derivative works," and
+"distribution" have the meaning as provided under U.S. copyright law;
+provided, however, that for the purposes of this License, derivative
+works shall not include works that remain separable from, or merely
+link (or bind by name) to the interfaces of, the Work.
+
+Works, including the Software, are "made available" under this License
+by including in or with the Work either (a) a copyright notice
+referencing the applicability of this License to the Work, or (b) a
+copy of this License.
+
+2. License Grants
+
+ 2.1 Copyright Grant. Subject to the terms and conditions of this
+ License, each Licensor grants to you a perpetual, worldwide,
+ non-exclusive, royalty-free, copyright license to reproduce,
+ prepare derivative works of, publicly display, publicly perform,
+ sublicense and distribute its Work and any resulting derivative
+ works in any form.
+
+3. Limitations
+
+ 3.1 Redistribution. You may reproduce or distribute the Work only
+ if (a) you do so under this License, (b) you include a complete
+ copy of this License with your distribution, and (c) you retain
+ without modification any copyright, patent, trademark, or
+ attribution notices that are present in the Work.
+
+ 3.2 Derivative Works. You may specify that additional or different
+ terms apply to the use, reproduction, and distribution of your
+ derivative works of the Work ("Your Terms") only if (a) Your Terms
+ provide that the use limitation in Section 3.3 applies to your
+ derivative works, and (b) you identify the specific derivative
+ works that are subject to Your Terms. Notwithstanding Your Terms,
+ this License (including the redistribution requirements in Section
+ 3.1) will continue to apply to the Work itself.
+
+ 3.3 Use Limitation. The Work and any derivative works thereof only
+ may be used or intended for use non-commercially. Notwithstanding
+ the foregoing, NVIDIA and its affiliates may use the Work and any
+ derivative works commercially. As used herein, "non-commercially"
+ means for research or evaluation purposes only.
+
+ 3.4 Patent Claims. If you bring or threaten to bring a patent claim
+ against any Licensor (including any claim, cross-claim or
+ counterclaim in a lawsuit) to enforce any patents that you allege
+ are infringed by any Work, then your rights under this License from
+ such Licensor (including the grant in Section 2.1) will terminate
+ immediately.
+
+ 3.5 Trademarks. This License does not grant any rights to use any
+ Licensor’s or its affiliates’ names, logos, or trademarks, except
+ as necessary to reproduce the notices described in this License.
+
+ 3.6 Termination. If you violate any term of this License, then your
+ rights under this License (including the grant in Section 2.1) will
+ terminate immediately.
+
+4. Disclaimer of Warranty.
+
+THE WORK IS PROVIDED "AS IS" WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WARRANTIES OR CONDITIONS OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE OR
+NON-INFRINGEMENT. YOU BEAR THE RISK OF UNDERTAKING ANY ACTIVITIES UNDER
+THIS LICENSE.
+
+5. Limitation of Liability.
+
+EXCEPT AS PROHIBITED BY APPLICABLE LAW, IN NO EVENT AND UNDER NO LEGAL
+THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE
+SHALL ANY LICENSOR BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY DIRECT,
+INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF
+OR RELATED TO THIS LICENSE, THE USE OR INABILITY TO USE THE WORK
+(INCLUDING BUT NOT LIMITED TO LOSS OF GOODWILL, BUSINESS INTERRUPTION,
+LOST PROFITS OR DATA, COMPUTER FAILURE OR MALFUNCTION, OR ANY OTHER
+COMMERCIAL DAMAGES OR LOSSES), EVEN IF THE LICENSOR HAS BEEN ADVISED OF
+THE POSSIBILITY OF SUCH DAMAGES.
+
+=======================================================================
diff --git a/project/models/deprecated_deep_privacy2/sg3_torch_utils/__init__.py b/project/models/deprecated_deep_privacy2/sg3_torch_utils/__init__.py
new file mode 100644
index 0000000..ece0ea0
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/sg3_torch_utils/__init__.py
@@ -0,0 +1,9 @@
+# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+#
+# NVIDIA CORPORATION and its licensors retain all intellectual property
+# and proprietary rights in and to this software, related documentation
+# and any modifications thereto. Any use, reproduction, disclosure or
+# distribution of this software and related documentation without an express
+# license agreement from NVIDIA CORPORATION is strictly prohibited.
+
+# empty
diff --git a/project/models/deprecated_deep_privacy2/sg3_torch_utils/custom_ops.py b/project/models/deprecated_deep_privacy2/sg3_torch_utils/custom_ops.py
new file mode 100644
index 0000000..4cc4e43
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/sg3_torch_utils/custom_ops.py
@@ -0,0 +1,126 @@
+# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+#
+# NVIDIA CORPORATION and its licensors retain all intellectual property
+# and proprietary rights in and to this software, related documentation
+# and any modifications thereto. Any use, reproduction, disclosure or
+# distribution of this software and related documentation without an express
+# license agreement from NVIDIA CORPORATION is strictly prohibited.
+
+import os
+import glob
+import torch
+import torch.utils.cpp_extension
+import importlib
+import hashlib
+import shutil
+from pathlib import Path
+
+from torch.utils.file_baton import FileBaton
+
+#----------------------------------------------------------------------------
+# Global options.
+
+verbosity = 'brief' # Verbosity level: 'none', 'brief', 'full'
+
+#----------------------------------------------------------------------------
+# Internal helper funcs.
+
+def _find_compiler_bindir():
+ patterns = [
+ 'C:/Program Files (x86)/Microsoft Visual Studio/*/Professional/VC/Tools/MSVC/*/bin/Hostx64/x64',
+ 'C:/Program Files (x86)/Microsoft Visual Studio/*/BuildTools/VC/Tools/MSVC/*/bin/Hostx64/x64',
+ 'C:/Program Files (x86)/Microsoft Visual Studio/*/Community/VC/Tools/MSVC/*/bin/Hostx64/x64',
+ 'C:/Program Files (x86)/Microsoft Visual Studio */vc/bin',
+ ]
+ for pattern in patterns:
+ matches = sorted(glob.glob(pattern))
+ if len(matches):
+ return matches[-1]
+ return None
+
+#----------------------------------------------------------------------------
+# Main entry point for compiling and loading C++/CUDA plugins.
+
+_cached_plugins = dict()
+
+def get_plugin(module_name, sources, **build_kwargs):
+ assert verbosity in ['none', 'brief', 'full']
+
+ # Already cached?
+ if module_name in _cached_plugins:
+ return _cached_plugins[module_name]
+
+ # Print status.
+ if verbosity == 'full':
+ print(f'Setting up PyTorch plugin "{module_name}"...')
+ elif verbosity == 'brief':
+ print(f'Setting up PyTorch plugin "{module_name}"... ', end='', flush=True)
+
+ try: # pylint: disable=too-many-nested-blocks
+ # Make sure we can find the necessary compiler binaries.
+ if os.name == 'nt' and os.system("where cl.exe >nul 2>nul") != 0:
+ compiler_bindir = _find_compiler_bindir()
+ if compiler_bindir is None:
+ raise RuntimeError(f'Could not find MSVC/GCC/CLANG installation on this computer. Check _find_compiler_bindir() in "{__file__}".')
+ os.environ['PATH'] += ';' + compiler_bindir
+
+ # Compile and load.
+ verbose_build = (verbosity == 'full')
+
+ # Incremental build md5sum trickery. Copies all the input source files
+ # into a cached build directory under a combined md5 digest of the input
+ # source files. Copying is done only if the combined digest has changed.
+ # This keeps input file timestamps and filenames the same as in previous
+ # extension builds, allowing for fast incremental rebuilds.
+ #
+ # This optimization is done only in case all the source files reside in
+ # a single directory (just for simplicity) and if the TORCH_EXTENSIONS_DIR
+ # environment variable is set (we take this as a signal that the user
+ # actually cares about this.)
+ source_dirs_set = set(os.path.dirname(source) for source in sources)
+ if len(source_dirs_set) == 1 and ('TORCH_EXTENSIONS_DIR' in os.environ):
+ all_source_files = sorted(list(x for x in Path(list(source_dirs_set)[0]).iterdir() if x.is_file()))
+
+ # Compute a combined hash digest for all source files in the same
+ # custom op directory (usually .cu, .cpp, .py and .h files).
+ hash_md5 = hashlib.md5()
+ for src in all_source_files:
+ with open(src, 'rb') as f:
+ hash_md5.update(f.read())
+ build_dir = torch.utils.cpp_extension._get_build_directory(module_name, verbose=verbose_build) # pylint: disable=protected-access
+ digest_build_dir = os.path.join(build_dir, hash_md5.hexdigest())
+
+ if not os.path.isdir(digest_build_dir):
+ os.makedirs(digest_build_dir, exist_ok=True)
+ baton = FileBaton(os.path.join(digest_build_dir, 'lock'))
+ if baton.try_acquire():
+ try:
+ for src in all_source_files:
+ shutil.copyfile(src, os.path.join(digest_build_dir, os.path.basename(src)))
+ finally:
+ baton.release()
+ else:
+ # Someone else is copying source files under the digest dir,
+ # wait until done and continue.
+ baton.wait()
+ digest_sources = [os.path.join(digest_build_dir, os.path.basename(x)) for x in sources]
+ torch.utils.cpp_extension.load(name=module_name, build_directory=build_dir,
+ verbose=verbose_build, sources=digest_sources, **build_kwargs)
+ else:
+ torch.utils.cpp_extension.load(name=module_name, verbose=verbose_build, sources=sources, **build_kwargs)
+ module = importlib.import_module(module_name)
+
+ except:
+ if verbosity == 'brief':
+ print('Failed!')
+ raise
+
+ # Print status and add to cache.
+ if verbosity == 'full':
+ print(f'Done setting up PyTorch plugin "{module_name}".')
+ elif verbosity == 'brief':
+ print('Done.')
+ _cached_plugins[module_name] = module
+ return module
+
+#----------------------------------------------------------------------------
diff --git a/project/models/deprecated_deep_privacy2/sg3_torch_utils/misc.py b/project/models/deprecated_deep_privacy2/sg3_torch_utils/misc.py
new file mode 100644
index 0000000..10d8e31
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/sg3_torch_utils/misc.py
@@ -0,0 +1,172 @@
+# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+#
+# NVIDIA CORPORATION and its licensors retain all intellectual property
+# and proprietary rights in and to this software, related documentation
+# and any modifications thereto. Any use, reproduction, disclosure or
+# distribution of this software and related documentation without an express
+# license agreement from NVIDIA CORPORATION is strictly prohibited.
+
+import re
+import contextlib
+import numpy as np
+import torch
+import warnings
+
+#----------------------------------------------------------------------------
+# Cached construction of constant tensors. Avoids CPU=>GPU copy when the
+# same constant is used multiple times.
+
+_constant_cache = dict()
+
+def constant(value, shape=None, dtype=None, device=None, memory_format=None):
+ value = np.asarray(value)
+ if shape is not None:
+ shape = tuple(shape)
+ if dtype is None:
+ dtype = torch.get_default_dtype()
+ if device is None:
+ device = torch.device('cpu')
+ if memory_format is None:
+ memory_format = torch.contiguous_format
+
+ key = (value.shape, value.dtype, value.tobytes(), shape, dtype, device, memory_format)
+ tensor = _constant_cache.get(key, None)
+ if tensor is None:
+ tensor = torch.as_tensor(value.copy(), dtype=dtype, device=device)
+ if shape is not None:
+ tensor, _ = torch.broadcast_tensors(tensor, torch.empty(shape))
+ tensor = tensor.contiguous(memory_format=memory_format)
+ _constant_cache[key] = tensor
+ return tensor
+
+#----------------------------------------------------------------------------
+# Replace NaN/Inf with specified numerical values.
+
+try:
+ nan_to_num = torch.nan_to_num # 1.8.0a0
+except AttributeError:
+ def nan_to_num(input, nan=0.0, posinf=None, neginf=None, *, out=None): # pylint: disable=redefined-builtin
+ assert isinstance(input, torch.Tensor)
+ if posinf is None:
+ posinf = torch.finfo(input.dtype).max
+ if neginf is None:
+ neginf = torch.finfo(input.dtype).min
+ assert nan == 0
+ return torch.clamp(input.unsqueeze(0).nansum(0), min=neginf, max=posinf, out=out)
+
+#----------------------------------------------------------------------------
+# Symbolic assert.
+
+try:
+ symbolic_assert = torch._assert # 1.8.0a0 # pylint: disable=protected-access
+except AttributeError:
+ symbolic_assert = torch.Assert # 1.7.0
+
+#----------------------------------------------------------------------------
+# Context manager to suppress known warnings in torch.jit.trace().
+
+class suppress_tracer_warnings(warnings.catch_warnings):
+ def __enter__(self):
+ super().__enter__()
+ warnings.simplefilter('ignore', category=torch.jit.TracerWarning)
+ return self
+
+#----------------------------------------------------------------------------
+# Assert that the shape of a tensor matches the given list of integers.
+# None indicates that the size of a dimension is allowed to vary.
+# Performs symbolic assertion when used in torch.jit.trace().
+
+def assert_shape(tensor, ref_shape):
+ if tensor.ndim != len(ref_shape):
+ raise AssertionError(f'Wrong number of dimensions: got {tensor.ndim}, expected {len(ref_shape)}')
+ for idx, (size, ref_size) in enumerate(zip(tensor.shape, ref_shape)):
+ if ref_size is None:
+ pass
+ elif isinstance(ref_size, torch.Tensor):
+ with suppress_tracer_warnings(): # as_tensor results are registered as constants
+ symbolic_assert(torch.equal(torch.as_tensor(size), ref_size), f'Wrong size for dimension {idx}')
+ elif isinstance(size, torch.Tensor):
+ with suppress_tracer_warnings(): # as_tensor results are registered as constants
+ symbolic_assert(torch.equal(size, torch.as_tensor(ref_size)), f'Wrong size for dimension {idx}: expected {ref_size}')
+ elif size != ref_size:
+ raise AssertionError(f'Wrong size for dimension {idx}: got {size}, expected {ref_size}')
+
+#----------------------------------------------------------------------------
+# Function decorator that calls torch.autograd.profiler.record_function().
+
+def profiled_function(fn):
+ def decorator(*args, **kwargs):
+ with torch.autograd.profiler.record_function(fn.__name__):
+ return fn(*args, **kwargs)
+ decorator.__name__ = fn.__name__
+ return decorator
+
+#----------------------------------------------------------------------------
+# Sampler for torch.utils.data.DataLoader that loops over the dataset
+# indefinitely, shuffling items as it goes.
+
+class InfiniteSampler(torch.utils.data.Sampler):
+ def __init__(self, dataset, rank=0, num_replicas=1, shuffle=True, seed=0, window_size=0.5):
+ assert len(dataset) > 0
+ assert num_replicas > 0
+ assert 0 <= rank < num_replicas
+ assert 0 <= window_size <= 1
+ super().__init__(dataset)
+ self.dataset = dataset
+ self.rank = rank
+ self.num_replicas = num_replicas
+ self.shuffle = shuffle
+ self.seed = seed
+ self.window_size = window_size
+
+ def __iter__(self):
+ order = np.arange(len(self.dataset))
+ rnd = None
+ window = 0
+ if self.shuffle:
+ rnd = np.random.RandomState(self.seed)
+ rnd.shuffle(order)
+ window = int(np.rint(order.size * self.window_size))
+
+ idx = 0
+ while True:
+ i = idx % order.size
+ if idx % self.num_replicas == self.rank:
+ yield order[i]
+ if window >= 2:
+ j = (i - rnd.randint(window)) % order.size
+ order[i], order[j] = order[j], order[i]
+ idx += 1
+
+#----------------------------------------------------------------------------
+# Utilities for operating with torch.nn.Module parameters and buffers.
+
+def params_and_buffers(module):
+ assert isinstance(module, torch.nn.Module)
+ return list(module.parameters()) + list(module.buffers())
+
+def named_params_and_buffers(module):
+ assert isinstance(module, torch.nn.Module)
+ return list(module.named_parameters()) + list(module.named_buffers())
+
+def copy_params_and_buffers(src_module, dst_module, require_all=False):
+ assert isinstance(src_module, torch.nn.Module)
+ assert isinstance(dst_module, torch.nn.Module)
+ src_tensors = {name: tensor for name, tensor in named_params_and_buffers(src_module)}
+ for name, tensor in named_params_and_buffers(dst_module):
+ assert (name in src_tensors) or (not require_all)
+ if name in src_tensors:
+ tensor.copy_(src_tensors[name].detach()).requires_grad_(tensor.requires_grad)
+
+#----------------------------------------------------------------------------
+# Context manager for easily enabling/disabling DistributedDataParallel
+# synchronization.
+
+@contextlib.contextmanager
+def ddp_sync(module, sync):
+ assert isinstance(module, torch.nn.Module)
+ if sync or not isinstance(module, torch.nn.parallel.DistributedDataParallel):
+ yield
+ else:
+ with module.no_sync():
+ yield
diff --git a/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/__init__.py b/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/__init__.py
new file mode 100644
index 0000000..ece0ea0
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/__init__.py
@@ -0,0 +1,9 @@
+# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+#
+# NVIDIA CORPORATION and its licensors retain all intellectual property
+# and proprietary rights in and to this software, related documentation
+# and any modifications thereto. Any use, reproduction, disclosure or
+# distribution of this software and related documentation without an express
+# license agreement from NVIDIA CORPORATION is strictly prohibited.
+
+# empty
diff --git a/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/bias_act.cpp b/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/bias_act.cpp
new file mode 100644
index 0000000..5d2425d
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/bias_act.cpp
@@ -0,0 +1,99 @@
+// Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+//
+// NVIDIA CORPORATION and its licensors retain all intellectual property
+// and proprietary rights in and to this software, related documentation
+// and any modifications thereto. Any use, reproduction, disclosure or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA CORPORATION is strictly prohibited.
+
+#include
+#include
+#include
+#include "bias_act.h"
+
+//------------------------------------------------------------------------
+
+static bool has_same_layout(torch::Tensor x, torch::Tensor y)
+{
+ if (x.dim() != y.dim())
+ return false;
+ for (int64_t i = 0; i < x.dim(); i++)
+ {
+ if (x.size(i) != y.size(i))
+ return false;
+ if (x.size(i) >= 2 && x.stride(i) != y.stride(i))
+ return false;
+ }
+ return true;
+}
+
+//------------------------------------------------------------------------
+
+static torch::Tensor bias_act(torch::Tensor x, torch::Tensor b, torch::Tensor xref, torch::Tensor yref, torch::Tensor dy, int grad, int dim, int act, float alpha, float gain, float clamp)
+{
+ // Validate arguments.
+ TORCH_CHECK(x.is_cuda(), "x must reside on CUDA device");
+ TORCH_CHECK(b.numel() == 0 || (b.dtype() == x.dtype() && b.device() == x.device()), "b must have the same dtype and device as x");
+ TORCH_CHECK(xref.numel() == 0 || (xref.sizes() == x.sizes() && xref.dtype() == x.dtype() && xref.device() == x.device()), "xref must have the same shape, dtype, and device as x");
+ TORCH_CHECK(yref.numel() == 0 || (yref.sizes() == x.sizes() && yref.dtype() == x.dtype() && yref.device() == x.device()), "yref must have the same shape, dtype, and device as x");
+ TORCH_CHECK(dy.numel() == 0 || (dy.sizes() == x.sizes() && dy.dtype() == x.dtype() && dy.device() == x.device()), "dy must have the same dtype and device as x");
+ TORCH_CHECK(x.numel() <= INT_MAX, "x is too large");
+ TORCH_CHECK(b.dim() == 1, "b must have rank 1");
+ TORCH_CHECK(b.numel() == 0 || (dim >= 0 && dim < x.dim()), "dim is out of bounds");
+ TORCH_CHECK(b.numel() == 0 || b.numel() == x.size(dim), "b has wrong number of elements");
+ TORCH_CHECK(grad >= 0, "grad must be non-negative");
+
+ // Validate layout.
+ TORCH_CHECK(x.is_non_overlapping_and_dense(), "x must be non-overlapping and dense");
+ TORCH_CHECK(b.is_contiguous(), "b must be contiguous");
+ TORCH_CHECK(xref.numel() == 0 || has_same_layout(xref, x), "xref must have the same layout as x");
+ TORCH_CHECK(yref.numel() == 0 || has_same_layout(yref, x), "yref must have the same layout as x");
+ TORCH_CHECK(dy.numel() == 0 || has_same_layout(dy, x), "dy must have the same layout as x");
+
+ // Create output tensor.
+ const at::cuda::OptionalCUDAGuard device_guard(device_of(x));
+ torch::Tensor y = torch::empty_like(x);
+ TORCH_CHECK(has_same_layout(y, x), "y must have the same layout as x");
+
+ // Initialize CUDA kernel parameters.
+ bias_act_kernel_params p;
+ p.x = x.data_ptr();
+ p.b = (b.numel()) ? b.data_ptr() : NULL;
+ p.xref = (xref.numel()) ? xref.data_ptr() : NULL;
+ p.yref = (yref.numel()) ? yref.data_ptr() : NULL;
+ p.dy = (dy.numel()) ? dy.data_ptr() : NULL;
+ p.y = y.data_ptr();
+ p.grad = grad;
+ p.act = act;
+ p.alpha = alpha;
+ p.gain = gain;
+ p.clamp = clamp;
+ p.sizeX = (int)x.numel();
+ p.sizeB = (int)b.numel();
+ p.stepB = (b.numel()) ? (int)x.stride(dim) : 1;
+
+ // Choose CUDA kernel.
+ void* kernel;
+ AT_DISPATCH_FLOATING_TYPES_AND_HALF(x.scalar_type(), "upfirdn2d_cuda", [&]
+ {
+ kernel = choose_bias_act_kernel(p);
+ });
+ TORCH_CHECK(kernel, "no CUDA kernel found for the specified activation func");
+
+ // Launch CUDA kernel.
+ p.loopX = 4;
+ int blockSize = 4 * 32;
+ int gridSize = (p.sizeX - 1) / (p.loopX * blockSize) + 1;
+ void* args[] = {&p};
+ AT_CUDA_CHECK(cudaLaunchKernel(kernel, gridSize, blockSize, args, 0, at::cuda::getCurrentCUDAStream()));
+ return y;
+}
+
+//------------------------------------------------------------------------
+
+PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)
+{
+ m.def("bias_act", &bias_act);
+}
+
+//------------------------------------------------------------------------
diff --git a/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/bias_act.cu b/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/bias_act.cu
new file mode 100644
index 0000000..dd8fc47
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/bias_act.cu
@@ -0,0 +1,173 @@
+// Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+//
+// NVIDIA CORPORATION and its licensors retain all intellectual property
+// and proprietary rights in and to this software, related documentation
+// and any modifications thereto. Any use, reproduction, disclosure or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA CORPORATION is strictly prohibited.
+
+#include
+#include "bias_act.h"
+
+//------------------------------------------------------------------------
+// Helpers.
+
+template struct InternalType;
+template <> struct InternalType { typedef double scalar_t; };
+template <> struct InternalType { typedef float scalar_t; };
+template <> struct InternalType { typedef float scalar_t; };
+
+//------------------------------------------------------------------------
+// CUDA kernel.
+
+template
+__global__ void bias_act_kernel(bias_act_kernel_params p)
+{
+ typedef typename InternalType::scalar_t scalar_t;
+ int G = p.grad;
+ scalar_t alpha = (scalar_t)p.alpha;
+ scalar_t gain = (scalar_t)p.gain;
+ scalar_t clamp = (scalar_t)p.clamp;
+ scalar_t one = (scalar_t)1;
+ scalar_t two = (scalar_t)2;
+ scalar_t expRange = (scalar_t)80;
+ scalar_t halfExpRange = (scalar_t)40;
+ scalar_t seluScale = (scalar_t)1.0507009873554804934193349852946;
+ scalar_t seluAlpha = (scalar_t)1.6732632423543772848170429916717;
+
+ // Loop over elements.
+ int xi = blockIdx.x * p.loopX * blockDim.x + threadIdx.x;
+ for (int loopIdx = 0; loopIdx < p.loopX && xi < p.sizeX; loopIdx++, xi += blockDim.x)
+ {
+ // Load.
+ scalar_t x = (scalar_t)((const T*)p.x)[xi];
+ scalar_t b = (p.b) ? (scalar_t)((const T*)p.b)[(xi / p.stepB) % p.sizeB] : 0;
+ scalar_t xref = (p.xref) ? (scalar_t)((const T*)p.xref)[xi] : 0;
+ scalar_t yref = (p.yref) ? (scalar_t)((const T*)p.yref)[xi] : 0;
+ scalar_t dy = (p.dy) ? (scalar_t)((const T*)p.dy)[xi] : one;
+ scalar_t yy = (gain != 0) ? yref / gain : 0;
+ scalar_t y = 0;
+
+ // Apply bias.
+ ((G == 0) ? x : xref) += b;
+
+ // linear
+ if (A == 1)
+ {
+ if (G == 0) y = x;
+ if (G == 1) y = x;
+ }
+
+ // relu
+ if (A == 2)
+ {
+ if (G == 0) y = (x > 0) ? x : 0;
+ if (G == 1) y = (yy > 0) ? x : 0;
+ }
+
+ // lrelu
+ if (A == 3)
+ {
+ if (G == 0) y = (x > 0) ? x : x * alpha;
+ if (G == 1) y = (yy > 0) ? x : x * alpha;
+ }
+
+ // tanh
+ if (A == 4)
+ {
+ if (G == 0) { scalar_t c = exp(x); scalar_t d = one / c; y = (x < -expRange) ? -one : (x > expRange) ? one : (c - d) / (c + d); }
+ if (G == 1) y = x * (one - yy * yy);
+ if (G == 2) y = x * (one - yy * yy) * (-two * yy);
+ }
+
+ // sigmoid
+ if (A == 5)
+ {
+ if (G == 0) y = (x < -expRange) ? 0 : one / (exp(-x) + one);
+ if (G == 1) y = x * yy * (one - yy);
+ if (G == 2) y = x * yy * (one - yy) * (one - two * yy);
+ }
+
+ // elu
+ if (A == 6)
+ {
+ if (G == 0) y = (x >= 0) ? x : exp(x) - one;
+ if (G == 1) y = (yy >= 0) ? x : x * (yy + one);
+ if (G == 2) y = (yy >= 0) ? 0 : x * (yy + one);
+ }
+
+ // selu
+ if (A == 7)
+ {
+ if (G == 0) y = (x >= 0) ? seluScale * x : (seluScale * seluAlpha) * (exp(x) - one);
+ if (G == 1) y = (yy >= 0) ? x * seluScale : x * (yy + seluScale * seluAlpha);
+ if (G == 2) y = (yy >= 0) ? 0 : x * (yy + seluScale * seluAlpha);
+ }
+
+ // softplus
+ if (A == 8)
+ {
+ if (G == 0) y = (x > expRange) ? x : log(exp(x) + one);
+ if (G == 1) y = x * (one - exp(-yy));
+ if (G == 2) { scalar_t c = exp(-yy); y = x * c * (one - c); }
+ }
+
+ // swish
+ if (A == 9)
+ {
+ if (G == 0)
+ y = (x < -expRange) ? 0 : x / (exp(-x) + one);
+ else
+ {
+ scalar_t c = exp(xref);
+ scalar_t d = c + one;
+ if (G == 1)
+ y = (xref > halfExpRange) ? x : x * c * (xref + d) / (d * d);
+ else
+ y = (xref > halfExpRange) ? 0 : x * c * (xref * (two - d) + two * d) / (d * d * d);
+ yref = (xref < -expRange) ? 0 : xref / (exp(-xref) + one) * gain;
+ }
+ }
+
+ // Apply gain.
+ y *= gain * dy;
+
+ // Clamp.
+ if (clamp >= 0)
+ {
+ if (G == 0)
+ y = (y > -clamp & y < clamp) ? y : (y >= 0) ? clamp : -clamp;
+ else
+ y = (yref > -clamp & yref < clamp) ? y : 0;
+ }
+
+ // Store.
+ ((T*)p.y)[xi] = (T)y;
+ }
+}
+
+//------------------------------------------------------------------------
+// CUDA kernel selection.
+
+template void* choose_bias_act_kernel(const bias_act_kernel_params& p)
+{
+ if (p.act == 1) return (void*)bias_act_kernel;
+ if (p.act == 2) return (void*)bias_act_kernel;
+ if (p.act == 3) return (void*)bias_act_kernel;
+ if (p.act == 4) return (void*)bias_act_kernel;
+ if (p.act == 5) return (void*)bias_act_kernel;
+ if (p.act == 6) return (void*)bias_act_kernel;
+ if (p.act == 7) return (void*)bias_act_kernel;
+ if (p.act == 8) return (void*)bias_act_kernel;
+ if (p.act == 9) return (void*)bias_act_kernel;
+ return NULL;
+}
+
+//------------------------------------------------------------------------
+// Template specializations.
+
+template void* choose_bias_act_kernel (const bias_act_kernel_params& p);
+template void* choose_bias_act_kernel (const bias_act_kernel_params& p);
+template void* choose_bias_act_kernel (const bias_act_kernel_params& p);
+
+//------------------------------------------------------------------------
diff --git a/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/bias_act.h b/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/bias_act.h
new file mode 100644
index 0000000..a32187e
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/bias_act.h
@@ -0,0 +1,38 @@
+// Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+//
+// NVIDIA CORPORATION and its licensors retain all intellectual property
+// and proprietary rights in and to this software, related documentation
+// and any modifications thereto. Any use, reproduction, disclosure or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA CORPORATION is strictly prohibited.
+
+//------------------------------------------------------------------------
+// CUDA kernel parameters.
+
+struct bias_act_kernel_params
+{
+ const void* x; // [sizeX]
+ const void* b; // [sizeB] or NULL
+ const void* xref; // [sizeX] or NULL
+ const void* yref; // [sizeX] or NULL
+ const void* dy; // [sizeX] or NULL
+ void* y; // [sizeX]
+
+ int grad;
+ int act;
+ float alpha;
+ float gain;
+ float clamp;
+
+ int sizeX;
+ int sizeB;
+ int stepB;
+ int loopX;
+};
+
+//------------------------------------------------------------------------
+// CUDA kernel selection.
+
+template void* choose_bias_act_kernel(const bias_act_kernel_params& p);
+
+//------------------------------------------------------------------------
diff --git a/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/bias_act.py b/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/bias_act.py
new file mode 100644
index 0000000..7c39717
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/bias_act.py
@@ -0,0 +1,215 @@
+# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+#
+# NVIDIA CORPORATION and its licensors retain all intellectual property
+# and proprietary rights in and to this software, related documentation
+# and any modifications thereto. Any use, reproduction, disclosure or
+# distribution of this software and related documentation without an express
+# license agreement from NVIDIA CORPORATION is strictly prohibited.
+
+"""Custom PyTorch ops for efficient bias and activation."""
+
+import os
+import warnings
+import numpy as np
+import torch
+import traceback
+
+from .. import custom_ops
+from easydict import EasyDict
+from torch.cuda.amp import custom_bwd, custom_fwd
+#----------------------------------------------------------------------------
+
+activation_funcs = {
+ 'linear': EasyDict(func=lambda x, **_: x, def_alpha=0, def_gain=1, cuda_idx=1, ref='', has_2nd_grad=False),
+ 'relu': EasyDict(func=lambda x, **_: torch.nn.functional.relu(x), def_alpha=0, def_gain=np.sqrt(2), cuda_idx=2, ref='y', has_2nd_grad=False),
+ 'lrelu': EasyDict(func=lambda x, alpha, **_: torch.nn.functional.leaky_relu(x, alpha), def_alpha=0.2, def_gain=np.sqrt(2), cuda_idx=3, ref='y', has_2nd_grad=False),
+ 'tanh': EasyDict(func=lambda x, **_: torch.tanh(x), def_alpha=0, def_gain=1, cuda_idx=4, ref='y', has_2nd_grad=True),
+ 'sigmoid': EasyDict(func=lambda x, **_: torch.sigmoid(x), def_alpha=0, def_gain=1, cuda_idx=5, ref='y', has_2nd_grad=True),
+ 'elu': EasyDict(func=lambda x, **_: torch.nn.functional.elu(x), def_alpha=0, def_gain=1, cuda_idx=6, ref='y', has_2nd_grad=True),
+ 'selu': EasyDict(func=lambda x, **_: torch.nn.functional.selu(x), def_alpha=0, def_gain=1, cuda_idx=7, ref='y', has_2nd_grad=True),
+ 'softplus': EasyDict(func=lambda x, **_: torch.nn.functional.softplus(x), def_alpha=0, def_gain=1, cuda_idx=8, ref='y', has_2nd_grad=True),
+ 'swish': EasyDict(func=lambda x, **_: torch.nn.functional.silu(x), def_alpha=0, def_gain=np.sqrt(2), cuda_idx=9, ref='x', has_2nd_grad=True),
+}
+
+#----------------------------------------------------------------------------
+
+_inited = False
+_plugin = None
+enabled = False
+_null_tensor = torch.empty([0])
+
+def _init():
+ global _inited, _plugin
+ if not _inited:
+ _inited = True
+ sources = ['bias_act.cpp', 'bias_act.cu']
+ sources = [os.path.join(os.path.dirname(__file__), s) for s in sources]
+ try:
+ _plugin = custom_ops.get_plugin('bias_act_plugin', sources=sources, extra_cuda_cflags=['--use_fast_math'])
+ except:
+ warnings.warn('Failed to build CUDA kernels for bias_act. Falling back to slow reference implementation. Details:\n\n' + traceback.format_exc())
+ return _plugin is not None
+
+#----------------------------------------------------------------------------
+
+def bias_act(x, b=None, dim=1, act='linear', alpha=None, gain=None, clamp=None, impl='cuda'):
+ r"""Fused bias and activation function.
+
+ Adds bias `b` to activation tensor `x`, evaluates activation function `act`,
+ and scales the result by `gain`. Each of the steps is optional. In most cases,
+ the fused op is considerably more efficient than performing the same calculation
+ using standard PyTorch ops. It supports first and second order gradients,
+ but not third order gradients.
+
+ Args:
+ x: Input activation tensor. Can be of any shape.
+ b: Bias vector, or `None` to disable. Must be a 1D tensor of the same type
+ as `x`. The shape must be known, and it must match the dimension of `x`
+ corresponding to `dim`.
+ dim: The dimension in `x` corresponding to the elements of `b`.
+ The value of `dim` is ignored if `b` is not specified.
+ act: Name of the activation function to evaluate, or `"linear"` to disable.
+ Can be e.g. `"relu"`, `"lrelu"`, `"tanh"`, `"sigmoid"`, `"swish"`, etc.
+ See `activation_funcs` for a full list. `None` is not allowed.
+ alpha: Shape parameter for the activation function, or `None` to use the default.
+ gain: Scaling factor for the output tensor, or `None` to use default.
+ See `activation_funcs` for the default scaling of each activation function.
+ If unsure, consider specifying 1.
+ clamp: Clamp the output values to `[-clamp, +clamp]`, or `None` to disable
+ the clamping (default).
+ impl: Name of the implementation to use. Can be `"ref"` or `"cuda"` (default).
+
+ Returns:
+ Tensor of the same shape and datatype as `x`.
+ """
+ assert isinstance(x, torch.Tensor)
+ assert impl in ['ref', 'cuda']
+ if impl == 'cuda' and x.device.type == 'cuda' and enabled and _init():
+ return _bias_act_cuda(dim=dim, act=act, alpha=alpha, gain=gain, clamp=clamp).apply(x, b)
+ return _bias_act_ref(x=x, b=b, dim=dim, act=act, alpha=alpha, gain=gain, clamp=clamp)
+
+#----------------------------------------------------------------------------
+
+def _bias_act_ref(x, b=None, dim=1, act='linear', alpha=None, gain=None, clamp=None):
+ """Slow reference implementation of `bias_act()` using standard TensorFlow ops.
+ """
+ assert isinstance(x, torch.Tensor)
+ assert clamp is None or clamp >= 0
+ spec = activation_funcs[act]
+ alpha = float(alpha if alpha is not None else spec.def_alpha)
+ gain = float(gain if gain is not None else spec.def_gain)
+ clamp = float(clamp if clamp is not None else -1)
+
+ # Add bias.
+ if b is not None:
+ assert isinstance(b, torch.Tensor) and b.ndim == 1
+ assert 0 <= dim < x.ndim
+ assert b.shape[0] == x.shape[dim]
+ x = x + b.reshape([-1 if i == dim else 1 for i in range(x.ndim)])
+
+ # Evaluate activation function.
+ alpha = float(alpha)
+ x = spec.func(x, alpha=alpha)
+
+ # Scale by gain.
+ gain = float(gain)
+ if gain != 1:
+ x = x * gain
+
+ # Clamp.
+ if clamp >= 0:
+ x = x.clamp(-clamp, clamp) # pylint: disable=invalid-unary-operand-type
+ return x
+
+#----------------------------------------------------------------------------
+
+_bias_act_cuda_cache = dict()
+
+def _bias_act_cuda(dim=1, act='linear', alpha=None, gain=None, clamp=None):
+ """Fast CUDA implementation of `bias_act()` using custom ops.
+ """
+ # Parse arguments.
+ assert clamp is None or clamp >= 0
+ spec = activation_funcs[act]
+ alpha = float(alpha if alpha is not None else spec.def_alpha)
+ gain = float(gain if gain is not None else spec.def_gain)
+ clamp = float(clamp if clamp is not None else -1)
+
+ # Lookup from cache.
+ key = (dim, act, alpha, gain, clamp)
+ if key in _bias_act_cuda_cache:
+ return _bias_act_cuda_cache[key]
+
+ # Forward op.
+ class BiasActCuda(torch.autograd.Function):
+ @staticmethod
+ @custom_fwd(cast_inputs=torch.float16)
+ def forward(ctx, x, b): # pylint: disable=arguments-differ
+ ctx.memory_format = torch.channels_last if x.ndim > 2 and x.stride()[1] == 1 else torch.contiguous_format
+ x = x.contiguous(memory_format=ctx.memory_format)
+ b = b.contiguous() if b is not None else _null_tensor
+ y = x
+ if act != 'linear' or gain != 1 or clamp >= 0 or b is not _null_tensor:
+ y = _plugin.bias_act(x, b, _null_tensor, _null_tensor, _null_tensor, 0, dim, spec.cuda_idx, alpha, gain, clamp)
+ ctx.save_for_backward(
+ x if 'x' in spec.ref or spec.has_2nd_grad else _null_tensor,
+ b if 'x' in spec.ref or spec.has_2nd_grad else _null_tensor,
+ y if 'y' in spec.ref else _null_tensor)
+ return y
+
+ @staticmethod
+ @custom_bwd
+ def backward(ctx, dy): # pylint: disable=arguments-differ
+ dy = dy.contiguous(memory_format=ctx.memory_format)
+ x, b, y = ctx.saved_tensors
+ dx = None
+ db = None
+
+ if ctx.needs_input_grad[0] or ctx.needs_input_grad[1]:
+ dx = dy
+ if act != 'linear' or gain != 1 or clamp >= 0:
+ dx = BiasActCudaGrad.apply(dy, x, b, y)
+
+ if ctx.needs_input_grad[1]:
+ db = dx.sum([i for i in range(dx.ndim) if i != dim])
+
+ return dx, db
+
+ # Backward op.
+ class BiasActCudaGrad(torch.autograd.Function):
+ @staticmethod
+ @custom_fwd(cast_inputs=torch.float16)
+ def forward(ctx, dy, x, b, y): # pylint: disable=arguments-differ
+ ctx.memory_format = torch.channels_last if dy.ndim > 2 and dy.stride()[1] == 1 else torch.contiguous_format
+ dx = _plugin.bias_act(dy, b, x, y, _null_tensor, 1, dim, spec.cuda_idx, alpha, gain, clamp)
+ ctx.save_for_backward(
+ dy if spec.has_2nd_grad else _null_tensor,
+ x, b, y)
+ return dx
+
+ @staticmethod
+ @custom_bwd
+ def backward(ctx, d_dx): # pylint: disable=arguments-differ
+ d_dx = d_dx.contiguous(memory_format=ctx.memory_format)
+ dy, x, b, y = ctx.saved_tensors
+ d_dy = None
+ d_x = None
+ d_b = None
+ d_y = None
+
+ if ctx.needs_input_grad[0]:
+ d_dy = BiasActCudaGrad.apply(d_dx, x, b, y)
+
+ if spec.has_2nd_grad and (ctx.needs_input_grad[1] or ctx.needs_input_grad[2]):
+ d_x = _plugin.bias_act(d_dx, b, x, y, dy, 2, dim, spec.cuda_idx, alpha, gain, clamp)
+
+ if spec.has_2nd_grad and ctx.needs_input_grad[2]:
+ d_b = d_x.sum([i for i in range(d_x.ndim) if i != dim])
+
+ return d_dy, d_x, d_b, d_y
+
+ # Add to cache.
+ _bias_act_cuda_cache[key] = BiasActCuda
+ return BiasActCuda
+
+#----------------------------------------------------------------------------
diff --git a/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/conv2d_gradfix.py b/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/conv2d_gradfix.py
new file mode 100644
index 0000000..e66591f
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/conv2d_gradfix.py
@@ -0,0 +1,175 @@
+# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+#
+# NVIDIA CORPORATION and its licensors retain all intellectual property
+# and proprietary rights in and to this software, related documentation
+# and any modifications thereto. Any use, reproduction, disclosure or
+# distribution of this software and related documentation without an express
+# license agreement from NVIDIA CORPORATION is strictly prohibited.
+
+"""Custom replacement for `torch.nn.functional.conv2d` that supports
+arbitrarily high order gradients with zero performance penalty."""
+
+import warnings
+import contextlib
+import torch
+from torch.cuda.amp import custom_bwd, custom_fwd
+
+# pylint: disable=redefined-builtin
+# pylint: disable=arguments-differ
+# pylint: disable=protected-access
+
+#----------------------------------------------------------------------------
+
+enabled = False # Enable the custom op by setting this to true.
+weight_gradients_disabled = False # Forcefully disable computation of gradients with respect to the weights.
+
+@contextlib.contextmanager
+def no_weight_gradients():
+ global weight_gradients_disabled
+ old = weight_gradients_disabled
+ weight_gradients_disabled = True
+ yield
+ weight_gradients_disabled = old
+
+#----------------------------------------------------------------------------
+
+def conv2d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1):
+ if _should_use_custom_op(input):
+ return _conv2d_gradfix(transpose=False, weight_shape=weight.shape, stride=stride, padding=padding, output_padding=0, dilation=dilation, groups=groups).apply(input, weight, bias)
+ return torch.nn.functional.conv2d(input=input, weight=weight, bias=bias, stride=stride, padding=padding, dilation=dilation, groups=groups)
+
+def conv_transpose2d(input, weight, bias=None, stride=1, padding=0, output_padding=0, groups=1, dilation=1):
+ if _should_use_custom_op(input):
+ return _conv2d_gradfix(transpose=True, weight_shape=weight.shape, stride=stride, padding=padding, output_padding=output_padding, groups=groups, dilation=dilation).apply(input, weight, bias)
+ return torch.nn.functional.conv_transpose2d(input=input, weight=weight, bias=bias, stride=stride, padding=padding, output_padding=output_padding, groups=groups, dilation=dilation)
+
+#----------------------------------------------------------------------------
+
+def _should_use_custom_op(input):
+ assert isinstance(input, torch.Tensor)
+ if (not enabled) or (not torch.backends.cudnn.enabled):
+ return False
+ if input.device.type != 'cuda':
+ return False
+ if any(torch.__version__.startswith(x) for x in ['1.7.', '1.8.', '1.9', '1.10']):
+ return True
+ warnings.warn(f'conv2d_gradfix not supported on PyTorch {torch.__version__}. Falling back to torch.nn.functional.conv2d().')
+ return False
+
+def _tuple_of_ints(xs, ndim):
+ xs = tuple(xs) if isinstance(xs, (tuple, list)) else (xs,) * ndim
+ assert len(xs) == ndim
+ assert all(isinstance(x, int) for x in xs)
+ return xs
+
+#----------------------------------------------------------------------------
+
+_conv2d_gradfix_cache = dict()
+
+def _conv2d_gradfix(transpose, weight_shape, stride, padding, output_padding, dilation, groups):
+ # Parse arguments.
+ ndim = 2
+ weight_shape = tuple(weight_shape)
+ stride = _tuple_of_ints(stride, ndim)
+ padding = _tuple_of_ints(padding, ndim)
+ output_padding = _tuple_of_ints(output_padding, ndim)
+ dilation = _tuple_of_ints(dilation, ndim)
+
+ # Lookup from cache.
+ key = (transpose, weight_shape, stride, padding, output_padding, dilation, groups)
+ if key in _conv2d_gradfix_cache:
+ return _conv2d_gradfix_cache[key]
+
+ # Validate arguments.
+ assert groups >= 1
+ assert len(weight_shape) == ndim + 2
+ assert all(stride[i] >= 1 for i in range(ndim))
+ assert all(padding[i] >= 0 for i in range(ndim))
+ assert all(dilation[i] >= 0 for i in range(ndim))
+ if not transpose:
+ assert all(output_padding[i] == 0 for i in range(ndim))
+ else: # transpose
+ assert all(0 <= output_padding[i] < max(stride[i], dilation[i]) for i in range(ndim))
+
+ # Helpers.
+ common_kwargs = dict(stride=stride, padding=padding, dilation=dilation, groups=groups)
+ def calc_output_padding(input_shape, output_shape):
+ if transpose:
+ return [0, 0]
+ return [
+ input_shape[i + 2]
+ - (output_shape[i + 2] - 1) * stride[i]
+ - (1 - 2 * padding[i])
+ - dilation[i] * (weight_shape[i + 2] - 1)
+ for i in range(ndim)
+ ]
+
+ # Forward & backward.
+ class Conv2d(torch.autograd.Function):
+ @staticmethod
+ @custom_fwd(cast_inputs=torch.float16)
+ def forward(ctx, input, weight, bias):
+ assert weight.shape == weight_shape
+ if not transpose:
+ output = torch.nn.functional.conv2d(input=input, weight=weight, bias=bias, **common_kwargs)
+ else: # transpose
+ output = torch.nn.functional.conv_transpose2d(input=input, weight=weight, bias=bias, output_padding=output_padding, **common_kwargs)
+ ctx.save_for_backward(input, weight)
+ return output
+
+ @staticmethod
+ @custom_bwd
+ def backward(ctx, grad_output):
+ input, weight = ctx.saved_tensors
+ grad_input = None
+ grad_weight = None
+ grad_bias = None
+
+ if ctx.needs_input_grad[0]:
+ p = calc_output_padding(input_shape=input.shape, output_shape=grad_output.shape)
+ grad_input = _conv2d_gradfix(transpose=(not transpose), weight_shape=weight_shape, output_padding=p, **common_kwargs).apply(grad_output.float(), weight.float(), None)
+ assert grad_input.shape == input.shape
+
+ if ctx.needs_input_grad[1] and not weight_gradients_disabled:
+ grad_weight = Conv2dGradWeight.apply(grad_output.float(), input.float())
+ assert grad_weight.shape == weight_shape
+
+ if ctx.needs_input_grad[2]:
+ grad_bias = grad_output.float().sum([0, 2, 3])
+
+ return grad_input, grad_weight, grad_bias
+
+ # Gradient with respect to the weights.
+ class Conv2dGradWeight(torch.autograd.Function):
+ @staticmethod
+ @custom_fwd(cast_inputs=torch.float16)
+ def forward(ctx, grad_output, input):
+ op = torch._C._jit_get_operation('aten::cudnn_convolution_backward_weight' if not transpose else 'aten::cudnn_convolution_transpose_backward_weight')
+ flags = [torch.backends.cudnn.benchmark, torch.backends.cudnn.deterministic, torch.backends.cudnn.allow_tf32]
+ grad_weight = op(weight_shape, grad_output, input, padding, stride, dilation, groups, *flags)
+ assert grad_weight.shape == weight_shape
+ ctx.save_for_backward(grad_output, input)
+ return grad_weight
+
+ @staticmethod
+ @custom_bwd
+ def backward(ctx, grad2_grad_weight):
+ grad_output, input = ctx.saved_tensors
+ grad2_grad_output = None
+ grad2_input = None
+
+ if ctx.needs_input_grad[0]:
+ grad2_grad_output = Conv2d.apply(input, grad2_grad_weight, None)
+ assert grad2_grad_output.shape == grad_output.shape
+
+ if ctx.needs_input_grad[1]:
+ p = calc_output_padding(input_shape=input.shape, output_shape=grad_output.shape)
+ grad2_input = _conv2d_gradfix(transpose=(not transpose), weight_shape=weight_shape, output_padding=p, **common_kwargs).apply(grad_output, grad2_grad_weight, None)
+ assert grad2_input.shape == input.shape
+
+ return grad2_grad_output, grad2_input
+
+ _conv2d_gradfix_cache[key] = Conv2d
+ return Conv2d
+
+#----------------------------------------------------------------------------
diff --git a/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/conv2d_resample.py b/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/conv2d_resample.py
new file mode 100644
index 0000000..4a999b5
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/conv2d_resample.py
@@ -0,0 +1,142 @@
+# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+#
+# NVIDIA CORPORATION and its licensors retain all intellectual property
+# and proprietary rights in and to this software, related documentation
+# and any modifications thereto. Any use, reproduction, disclosure or
+# distribution of this software and related documentation without an express
+# license agreement from NVIDIA CORPORATION is strictly prohibited.
+
+"""2D convolution with optional up/downsampling."""
+
+import torch
+
+from .. import misc
+from . import conv2d_gradfix
+from . import upfirdn2d
+from .upfirdn2d import _parse_padding
+from .upfirdn2d import _get_filter_size
+
+#----------------------------------------------------------------------------
+
+def _get_weight_shape(w):
+ with misc.suppress_tracer_warnings(): # this value will be treated as a constant
+ shape = [int(sz) for sz in w.shape]
+ misc.assert_shape(w, shape)
+ return shape
+
+#----------------------------------------------------------------------------
+
+def _conv2d_wrapper(x, w, stride=1, padding=0, groups=1, transpose=False, flip_weight=True):
+ """Wrapper for the underlying `conv2d()` and `conv_transpose2d()` implementations.
+ """
+ out_channels, in_channels_per_group, kh, kw = _get_weight_shape(w)
+
+ # Flip weight if requested.
+ if not flip_weight: # conv2d() actually performs correlation (flip_weight=True) not convolution (flip_weight=False).
+ w = w.flip([2, 3])
+
+ # Otherwise => execute using conv2d_gradfix.
+ op = conv2d_gradfix.conv_transpose2d if transpose else conv2d_gradfix.conv2d
+ return op(x, w, stride=stride, padding=padding, groups=groups)
+
+#----------------------------------------------------------------------------
+
+@misc.profiled_function
+def conv2d_resample(x, w, f=None, up=1, down=1, padding=0, groups=1, flip_weight=True, flip_filter=False):
+ r"""2D convolution with optional up/downsampling.
+
+ Padding is performed only once at the beginning, not between the operations.
+
+ Args:
+ x: Input tensor of shape
+ `[batch_size, in_channels, in_height, in_width]`.
+ w: Weight tensor of shape
+ `[out_channels, in_channels//groups, kernel_height, kernel_width]`.
+ f: Low-pass filter for up/downsampling. Must be prepared beforehand by
+ calling upfirdn2d.setup_filter(). None = identity (default).
+ up: Integer upsampling factor (default: 1).
+ down: Integer downsampling factor (default: 1).
+ padding: Padding with respect to the upsampled image. Can be a single number
+ or a list/tuple `[x, y]` or `[x_before, x_after, y_before, y_after]`
+ (default: 0).
+ groups: Split input channels into N groups (default: 1).
+ flip_weight: False = convolution, True = correlation (default: True).
+ flip_filter: False = convolution, True = correlation (default: False).
+
+ Returns:
+ Tensor of the shape `[batch_size, num_channels, out_height, out_width]`.
+ """
+ # Validate arguments.
+ assert isinstance(x, torch.Tensor) and (x.ndim == 4)
+ assert isinstance(w, torch.Tensor) and (w.ndim == 4)
+ assert f is None or (isinstance(f, torch.Tensor) and f.ndim in [1, 2] and f.dtype == torch.float32)
+ assert isinstance(up, int) and (up >= 1)
+ assert isinstance(down, int) and (down >= 1)
+ assert isinstance(groups, int) and (groups >= 1)
+ out_channels, in_channels_per_group, kh, kw = _get_weight_shape(w)
+ fw, fh = _get_filter_size(f)
+ px0, px1, py0, py1 = _parse_padding(padding)
+
+ # Adjust padding to account for up/downsampling.
+ if up > 1:
+ px0 += (fw + up - 1) // 2
+ px1 += (fw - up) // 2
+ py0 += (fh + up - 1) // 2
+ py1 += (fh - up) // 2
+ if down > 1:
+ px0 += (fw - down + 1) // 2
+ px1 += (fw - down) // 2
+ py0 += (fh - down + 1) // 2
+ py1 += (fh - down) // 2
+
+ # Fast path: 1x1 convolution with downsampling only => downsample first, then convolve.
+ if kw == 1 and kh == 1 and (down > 1 and up == 1):
+ x = upfirdn2d.upfirdn2d(x=x, f=f, down=down, padding=[px0,px1,py0,py1], flip_filter=flip_filter)
+ x = _conv2d_wrapper(x=x, w=w, groups=groups, flip_weight=flip_weight)
+ return x
+
+ # Fast path: 1x1 convolution with upsampling only => convolve first, then upsample.
+ if kw == 1 and kh == 1 and (up > 1 and down == 1):
+ x = _conv2d_wrapper(x=x, w=w, groups=groups, flip_weight=flip_weight)
+ x = upfirdn2d.upfirdn2d(x=x, f=f, up=up, padding=[px0,px1,py0,py1], gain=up**2, flip_filter=flip_filter)
+ return x
+
+ # Fast path: downsampling only => use strided convolution.
+ if down > 1 and up == 1:
+ x = upfirdn2d.upfirdn2d(x=x, f=f, padding=[px0,px1,py0,py1], flip_filter=flip_filter)
+ x = _conv2d_wrapper(x=x, w=w, stride=down, groups=groups, flip_weight=flip_weight)
+ return x
+
+ # Fast path: upsampling with optional downsampling => use transpose strided convolution.
+ if up > 1:
+ if groups == 1:
+ w = w.transpose(0, 1)
+ else:
+ w = w.reshape(groups, out_channels // groups, in_channels_per_group, kh, kw)
+ w = w.transpose(1, 2)
+ w = w.reshape(groups * in_channels_per_group, out_channels // groups, kh, kw)
+ px0 -= kw - 1
+ px1 -= kw - up
+ py0 -= kh - 1
+ py1 -= kh - up
+ pxt = max(min(-px0, -px1), 0)
+ pyt = max(min(-py0, -py1), 0)
+ x = _conv2d_wrapper(x=x, w=w, stride=up, padding=[pyt,pxt], groups=groups, transpose=True, flip_weight=(not flip_weight))
+ x = upfirdn2d.upfirdn2d(x=x, f=f, padding=[px0+pxt,px1+pxt,py0+pyt,py1+pyt], gain=up**2, flip_filter=flip_filter)
+ if down > 1:
+ x = upfirdn2d.upfirdn2d(x=x, f=f, down=down, flip_filter=flip_filter)
+ return x
+
+ # Fast path: no up/downsampling, padding supported by the underlying implementation => use plain conv2d.
+ if up == 1 and down == 1:
+ if px0 == px1 and py0 == py1 and px0 >= 0 and py0 >= 0:
+ return _conv2d_wrapper(x=x, w=w, padding=[py0,px0], groups=groups, flip_weight=flip_weight)
+
+ # Fallback: Generic reference implementation.
+ x = upfirdn2d.upfirdn2d(x=x, f=(f if up > 1 else None), up=up, padding=[px0,px1,py0,py1], gain=up**2, flip_filter=flip_filter)
+ x = _conv2d_wrapper(x=x, w=w, groups=groups, flip_weight=flip_weight)
+ if down > 1:
+ x = upfirdn2d.upfirdn2d(x=x, f=f, down=down, flip_filter=flip_filter)
+ return x
+
+#----------------------------------------------------------------------------
diff --git a/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/fma.py b/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/fma.py
new file mode 100644
index 0000000..b4e8ef9
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/fma.py
@@ -0,0 +1,63 @@
+# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+#
+# NVIDIA CORPORATION and its licensors retain all intellectual property
+# and proprietary rights in and to this software, related documentation
+# and any modifications thereto. Any use, reproduction, disclosure or
+# distribution of this software and related documentation without an express
+# license agreement from NVIDIA CORPORATION is strictly prohibited.
+
+"""Fused multiply-add, with slightly faster gradients than `torch.addcmul()`."""
+
+import torch
+from torch.cuda.amp import custom_bwd, custom_fwd
+
+#----------------------------------------------------------------------------
+
+def fma(a, b, c): # => a * b + c
+ return _FusedMultiplyAdd.apply(a, b, c)
+
+#----------------------------------------------------------------------------
+
+class _FusedMultiplyAdd(torch.autograd.Function): # a * b + c
+ @staticmethod
+ @custom_fwd(cast_inputs=torch.float16)
+ def forward(ctx, a, b, c): # pylint: disable=arguments-differ
+ out = torch.addcmul(c, a, b)
+ ctx.save_for_backward(a, b)
+ ctx.c_shape = c.shape
+ return out
+
+ @staticmethod
+ @custom_bwd
+ def backward(ctx, dout): # pylint: disable=arguments-differ
+ a, b = ctx.saved_tensors
+ c_shape = ctx.c_shape
+ da = None
+ db = None
+ dc = None
+
+ if ctx.needs_input_grad[0]:
+ da = _unbroadcast(dout * b, a.shape)
+
+ if ctx.needs_input_grad[1]:
+ db = _unbroadcast(dout * a, b.shape)
+
+ if ctx.needs_input_grad[2]:
+ dc = _unbroadcast(dout, c_shape)
+
+ return da, db, dc
+
+#----------------------------------------------------------------------------
+
+def _unbroadcast(x, shape):
+ extra_dims = x.ndim - len(shape)
+ assert extra_dims >= 0
+ dim = [i for i in range(x.ndim) if x.shape[i] > 1 and (i < extra_dims or shape[i - extra_dims] == 1)]
+ if len(dim):
+ x = x.sum(dim=dim, keepdim=True)
+ if extra_dims:
+ x = x.reshape(-1, *x.shape[extra_dims+1:])
+ assert x.shape == shape
+ return x
+
+#----------------------------------------------------------------------------
diff --git a/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/grid_sample_gradfix.py b/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/grid_sample_gradfix.py
new file mode 100644
index 0000000..87067e1
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/grid_sample_gradfix.py
@@ -0,0 +1,88 @@
+# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+#
+# NVIDIA CORPORATION and its licensors retain all intellectual property
+# and proprietary rights in and to this software, related documentation
+# and any modifications thereto. Any use, reproduction, disclosure or
+# distribution of this software and related documentation without an express
+# license agreement from NVIDIA CORPORATION is strictly prohibited.
+
+"""Custom replacement for `torch.nn.functional.grid_sample` that
+supports arbitrarily high order gradients between the input and output.
+Only works on 2D images and assumes
+`mode='bilinear'`, `padding_mode='zeros'`, `align_corners=False`."""
+
+import torch
+from torch.cuda.amp import custom_bwd, custom_fwd
+from pkg_resources import parse_version
+# pylint: disable=redefined-builtin
+# pylint: disable=arguments-differ
+# pylint: disable=protected-access
+_use_pytorch_1_11_api = parse_version(torch.__version__) >= parse_version('1.11.0a') # Allow prerelease builds of 1.11
+
+
+#----------------------------------------------------------------------------
+
+enabled = False # Enable the custom op by setting this to true.
+
+#----------------------------------------------------------------------------
+
+def grid_sample(input, grid):
+ if _should_use_custom_op():
+ return _GridSample2dForward.apply(input, grid)
+ return torch.nn.functional.grid_sample(input=input, grid=grid, mode='bilinear', padding_mode='zeros', align_corners=False)
+
+#----------------------------------------------------------------------------
+
+def _should_use_custom_op():
+ return enabled
+
+#----------------------------------------------------------------------------
+
+class _GridSample2dForward(torch.autograd.Function):
+ @staticmethod
+ @custom_fwd(cast_inputs=torch.float16)
+ def forward(ctx, input, grid):
+ assert input.ndim == 4
+ assert grid.ndim == 4
+ output = torch.nn.functional.grid_sample(input=input, grid=grid, mode='bilinear', padding_mode='zeros', align_corners=False)
+ ctx.save_for_backward(input, grid)
+ return output
+
+ @staticmethod
+ @custom_bwd
+ def backward(ctx, grad_output):
+ input, grid = ctx.saved_tensors
+ grad_input, grad_grid = _GridSample2dBackward.apply(grad_output, input, grid)
+ return grad_input, grad_grid
+
+#----------------------------------------------------------------------------
+
+class _GridSample2dBackward(torch.autograd.Function):
+ @staticmethod
+ @custom_fwd(cast_inputs=torch.float16)
+ def forward(ctx, grad_output, input, grid):
+ op = torch._C._jit_get_operation('aten::grid_sampler_2d_backward')
+ if _use_pytorch_1_11_api:
+ output_mask = (ctx.needs_input_grad[1], ctx.needs_input_grad[2])
+ grad_input, grad_grid = op(grad_output, input, grid, 0, 0, False, output_mask)
+ else:
+ grad_input, grad_grid = op(grad_output, input, grid, 0, 0, False)
+ ctx.save_for_backward(grid)
+ return grad_input, grad_grid
+
+ @staticmethod
+ @custom_bwd
+ def backward(ctx, grad2_grad_input, grad2_grad_grid):
+ _ = grad2_grad_grid # unused
+ grid, = ctx.saved_tensors
+ grad2_grad_output = None
+ grad2_input = None
+ grad2_grid = None
+
+ if ctx.needs_input_grad[0]:
+ grad2_grad_output = _GridSample2dForward.apply(grad2_grad_input, grid)
+
+ assert not ctx.needs_input_grad[2]
+ return grad2_grad_output, grad2_input, grad2_grid
+
+#----------------------------------------------------------------------------
diff --git a/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/upfirdn2d.cpp b/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/upfirdn2d.cpp
new file mode 100644
index 0000000..2d7177f
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/upfirdn2d.cpp
@@ -0,0 +1,103 @@
+// Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+//
+// NVIDIA CORPORATION and its licensors retain all intellectual property
+// and proprietary rights in and to this software, related documentation
+// and any modifications thereto. Any use, reproduction, disclosure or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA CORPORATION is strictly prohibited.
+
+#include
+#include
+#include
+#include "upfirdn2d.h"
+
+//------------------------------------------------------------------------
+
+static torch::Tensor upfirdn2d(torch::Tensor x, torch::Tensor f, int upx, int upy, int downx, int downy, int padx0, int padx1, int pady0, int pady1, bool flip, float gain)
+{
+ // Validate arguments.
+ TORCH_CHECK(x.is_cuda(), "x must reside on CUDA device");
+ TORCH_CHECK(f.device() == x.device(), "f must reside on the same device as x");
+ TORCH_CHECK(f.dtype() == torch::kFloat, "f must be float32");
+ TORCH_CHECK(x.numel() <= INT_MAX, "x is too large");
+ TORCH_CHECK(f.numel() <= INT_MAX, "f is too large");
+ TORCH_CHECK(x.dim() == 4, "x must be rank 4");
+ TORCH_CHECK(f.dim() == 2, "f must be rank 2");
+ TORCH_CHECK(f.size(0) >= 1 && f.size(1) >= 1, "f must be at least 1x1");
+ TORCH_CHECK(upx >= 1 && upy >= 1, "upsampling factor must be at least 1");
+ TORCH_CHECK(downx >= 1 && downy >= 1, "downsampling factor must be at least 1");
+
+ // Create output tensor.
+ const at::cuda::OptionalCUDAGuard device_guard(device_of(x));
+ int outW = ((int)x.size(3) * upx + padx0 + padx1 - (int)f.size(1) + downx) / downx;
+ int outH = ((int)x.size(2) * upy + pady0 + pady1 - (int)f.size(0) + downy) / downy;
+ TORCH_CHECK(outW >= 1 && outH >= 1, "output must be at least 1x1");
+ torch::Tensor y = torch::empty({x.size(0), x.size(1), outH, outW}, x.options(), x.suggest_memory_format());
+ TORCH_CHECK(y.numel() <= INT_MAX, "output is too large");
+
+ // Initialize CUDA kernel parameters.
+ upfirdn2d_kernel_params p;
+ p.x = x.data_ptr();
+ p.f = f.data_ptr();
+ p.y = y.data_ptr();
+ p.up = make_int2(upx, upy);
+ p.down = make_int2(downx, downy);
+ p.pad0 = make_int2(padx0, pady0);
+ p.flip = (flip) ? 1 : 0;
+ p.gain = gain;
+ p.inSize = make_int4((int)x.size(3), (int)x.size(2), (int)x.size(1), (int)x.size(0));
+ p.inStride = make_int4((int)x.stride(3), (int)x.stride(2), (int)x.stride(1), (int)x.stride(0));
+ p.filterSize = make_int2((int)f.size(1), (int)f.size(0));
+ p.filterStride = make_int2((int)f.stride(1), (int)f.stride(0));
+ p.outSize = make_int4((int)y.size(3), (int)y.size(2), (int)y.size(1), (int)y.size(0));
+ p.outStride = make_int4((int)y.stride(3), (int)y.stride(2), (int)y.stride(1), (int)y.stride(0));
+ p.sizeMajor = (p.inStride.z == 1) ? p.inSize.w : p.inSize.w * p.inSize.z;
+ p.sizeMinor = (p.inStride.z == 1) ? p.inSize.z : 1;
+
+ // Choose CUDA kernel.
+ upfirdn2d_kernel_spec spec;
+ AT_DISPATCH_FLOATING_TYPES_AND_HALF(x.scalar_type(), "upfirdn2d_cuda", [&]
+ {
+ spec = choose_upfirdn2d_kernel(p);
+ });
+
+ // Set looping options.
+ p.loopMajor = (p.sizeMajor - 1) / 16384 + 1;
+ p.loopMinor = spec.loopMinor;
+ p.loopX = spec.loopX;
+ p.launchMinor = (p.sizeMinor - 1) / p.loopMinor + 1;
+ p.launchMajor = (p.sizeMajor - 1) / p.loopMajor + 1;
+
+ // Compute grid size.
+ dim3 blockSize, gridSize;
+ if (spec.tileOutW < 0) // large
+ {
+ blockSize = dim3(4, 32, 1);
+ gridSize = dim3(
+ ((p.outSize.y - 1) / blockSize.x + 1) * p.launchMinor,
+ (p.outSize.x - 1) / (blockSize.y * p.loopX) + 1,
+ p.launchMajor);
+ }
+ else // small
+ {
+ blockSize = dim3(256, 1, 1);
+ gridSize = dim3(
+ ((p.outSize.y - 1) / spec.tileOutH + 1) * p.launchMinor,
+ (p.outSize.x - 1) / (spec.tileOutW * p.loopX) + 1,
+ p.launchMajor);
+ }
+
+ // Launch CUDA kernel.
+ void* args[] = {&p};
+ AT_CUDA_CHECK(cudaLaunchKernel(spec.kernel, gridSize, blockSize, args, 0, at::cuda::getCurrentCUDAStream()));
+ return y;
+}
+
+//------------------------------------------------------------------------
+
+PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)
+{
+ m.def("upfirdn2d", &upfirdn2d);
+}
+
+//------------------------------------------------------------------------
diff --git a/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/upfirdn2d.cu b/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/upfirdn2d.cu
new file mode 100644
index 0000000..ebdd987
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/upfirdn2d.cu
@@ -0,0 +1,350 @@
+// Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+//
+// NVIDIA CORPORATION and its licensors retain all intellectual property
+// and proprietary rights in and to this software, related documentation
+// and any modifications thereto. Any use, reproduction, disclosure or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA CORPORATION is strictly prohibited.
+
+#include
+#include "upfirdn2d.h"
+
+//------------------------------------------------------------------------
+// Helpers.
+
+template struct InternalType;
+template <> struct InternalType { typedef double scalar_t; };
+template <> struct InternalType { typedef float scalar_t; };
+template <> struct InternalType { typedef float scalar_t; };
+
+static __device__ __forceinline__ int floor_div(int a, int b)
+{
+ int t = 1 - a / b;
+ return (a + t * b) / b - t;
+}
+
+//------------------------------------------------------------------------
+// Generic CUDA implementation for large filters.
+
+template static __global__ void upfirdn2d_kernel_large(upfirdn2d_kernel_params p)
+{
+ typedef typename InternalType::scalar_t scalar_t;
+
+ // Calculate thread index.
+ int minorBase = blockIdx.x * blockDim.x + threadIdx.x;
+ int outY = minorBase / p.launchMinor;
+ minorBase -= outY * p.launchMinor;
+ int outXBase = blockIdx.y * p.loopX * blockDim.y + threadIdx.y;
+ int majorBase = blockIdx.z * p.loopMajor;
+ if (outXBase >= p.outSize.x | outY >= p.outSize.y | majorBase >= p.sizeMajor)
+ return;
+
+ // Setup Y receptive field.
+ int midY = outY * p.down.y + p.up.y - 1 - p.pad0.y;
+ int inY = min(max(floor_div(midY, p.up.y), 0), p.inSize.y);
+ int h = min(max(floor_div(midY + p.filterSize.y, p.up.y), 0), p.inSize.y) - inY;
+ int filterY = midY + p.filterSize.y - (inY + 1) * p.up.y;
+ if (p.flip)
+ filterY = p.filterSize.y - 1 - filterY;
+
+ // Loop over major, minor, and X.
+ for (int majorIdx = 0, major = majorBase; majorIdx < p.loopMajor & major < p.sizeMajor; majorIdx++, major++)
+ for (int minorIdx = 0, minor = minorBase; minorIdx < p.loopMinor & minor < p.sizeMinor; minorIdx++, minor += p.launchMinor)
+ {
+ int nc = major * p.sizeMinor + minor;
+ int n = nc / p.inSize.z;
+ int c = nc - n * p.inSize.z;
+ for (int loopX = 0, outX = outXBase; loopX < p.loopX & outX < p.outSize.x; loopX++, outX += blockDim.y)
+ {
+ // Setup X receptive field.
+ int midX = outX * p.down.x + p.up.x - 1 - p.pad0.x;
+ int inX = min(max(floor_div(midX, p.up.x), 0), p.inSize.x);
+ int w = min(max(floor_div(midX + p.filterSize.x, p.up.x), 0), p.inSize.x) - inX;
+ int filterX = midX + p.filterSize.x - (inX + 1) * p.up.x;
+ if (p.flip)
+ filterX = p.filterSize.x - 1 - filterX;
+
+ // Initialize pointers.
+ const T* xp = &((const T*)p.x)[inX * p.inStride.x + inY * p.inStride.y + c * p.inStride.z + n * p.inStride.w];
+ const float* fp = &p.f[filterX * p.filterStride.x + filterY * p.filterStride.y];
+ int filterStepX = ((p.flip) ? p.up.x : -p.up.x) * p.filterStride.x;
+ int filterStepY = ((p.flip) ? p.up.y : -p.up.y) * p.filterStride.y;
+
+ // Inner loop.
+ scalar_t v = 0;
+ for (int y = 0; y < h; y++)
+ {
+ for (int x = 0; x < w; x++)
+ {
+ v += (scalar_t)(*xp) * (scalar_t)(*fp);
+ xp += p.inStride.x;
+ fp += filterStepX;
+ }
+ xp += p.inStride.y - w * p.inStride.x;
+ fp += filterStepY - w * filterStepX;
+ }
+
+ // Store result.
+ v *= p.gain;
+ ((T*)p.y)[outX * p.outStride.x + outY * p.outStride.y + c * p.outStride.z + n * p.outStride.w] = (T)v;
+ }
+ }
+}
+
+//------------------------------------------------------------------------
+// Specialized CUDA implementation for small filters.
+
+template
+static __global__ void upfirdn2d_kernel_small(upfirdn2d_kernel_params p)
+{
+ typedef typename InternalType::scalar_t scalar_t;
+ const int tileInW = ((tileOutW - 1) * downx + filterW - 1) / upx + 1;
+ const int tileInH = ((tileOutH - 1) * downy + filterH - 1) / upy + 1;
+ __shared__ volatile scalar_t sf[filterH][filterW];
+ __shared__ volatile scalar_t sx[tileInH][tileInW][loopMinor];
+
+ // Calculate tile index.
+ int minorBase = blockIdx.x;
+ int tileOutY = minorBase / p.launchMinor;
+ minorBase -= tileOutY * p.launchMinor;
+ minorBase *= loopMinor;
+ tileOutY *= tileOutH;
+ int tileOutXBase = blockIdx.y * p.loopX * tileOutW;
+ int majorBase = blockIdx.z * p.loopMajor;
+ if (tileOutXBase >= p.outSize.x | tileOutY >= p.outSize.y | majorBase >= p.sizeMajor)
+ return;
+
+ // Load filter (flipped).
+ for (int tapIdx = threadIdx.x; tapIdx < filterH * filterW; tapIdx += blockDim.x)
+ {
+ int fy = tapIdx / filterW;
+ int fx = tapIdx - fy * filterW;
+ scalar_t v = 0;
+ if (fx < p.filterSize.x & fy < p.filterSize.y)
+ {
+ int ffx = (p.flip) ? fx : p.filterSize.x - 1 - fx;
+ int ffy = (p.flip) ? fy : p.filterSize.y - 1 - fy;
+ v = (scalar_t)p.f[ffx * p.filterStride.x + ffy * p.filterStride.y];
+ }
+ sf[fy][fx] = v;
+ }
+
+ // Loop over major and X.
+ for (int majorIdx = 0, major = majorBase; majorIdx < p.loopMajor & major < p.sizeMajor; majorIdx++, major++)
+ {
+ int baseNC = major * p.sizeMinor + minorBase;
+ int n = baseNC / p.inSize.z;
+ int baseC = baseNC - n * p.inSize.z;
+ for (int loopX = 0, tileOutX = tileOutXBase; loopX < p.loopX & tileOutX < p.outSize.x; loopX++, tileOutX += tileOutW)
+ {
+ // Load input pixels.
+ int tileMidX = tileOutX * downx + upx - 1 - p.pad0.x;
+ int tileMidY = tileOutY * downy + upy - 1 - p.pad0.y;
+ int tileInX = floor_div(tileMidX, upx);
+ int tileInY = floor_div(tileMidY, upy);
+ __syncthreads();
+ for (int inIdx = threadIdx.x; inIdx < tileInH * tileInW * loopMinor; inIdx += blockDim.x)
+ {
+ int relC = inIdx;
+ int relInX = relC / loopMinor;
+ int relInY = relInX / tileInW;
+ relC -= relInX * loopMinor;
+ relInX -= relInY * tileInW;
+ int c = baseC + relC;
+ int inX = tileInX + relInX;
+ int inY = tileInY + relInY;
+ scalar_t v = 0;
+ if (inX >= 0 & inY >= 0 & inX < p.inSize.x & inY < p.inSize.y & c < p.inSize.z)
+ v = (scalar_t)((const T*)p.x)[inX * p.inStride.x + inY * p.inStride.y + c * p.inStride.z + n * p.inStride.w];
+ sx[relInY][relInX][relC] = v;
+ }
+
+ // Loop over output pixels.
+ __syncthreads();
+ for (int outIdx = threadIdx.x; outIdx < tileOutH * tileOutW * loopMinor; outIdx += blockDim.x)
+ {
+ int relC = outIdx;
+ int relOutX = relC / loopMinor;
+ int relOutY = relOutX / tileOutW;
+ relC -= relOutX * loopMinor;
+ relOutX -= relOutY * tileOutW;
+ int c = baseC + relC;
+ int outX = tileOutX + relOutX;
+ int outY = tileOutY + relOutY;
+
+ // Setup receptive field.
+ int midX = tileMidX + relOutX * downx;
+ int midY = tileMidY + relOutY * downy;
+ int inX = floor_div(midX, upx);
+ int inY = floor_div(midY, upy);
+ int relInX = inX - tileInX;
+ int relInY = inY - tileInY;
+ int filterX = (inX + 1) * upx - midX - 1; // flipped
+ int filterY = (inY + 1) * upy - midY - 1; // flipped
+
+ // Inner loop.
+ if (outX < p.outSize.x & outY < p.outSize.y & c < p.outSize.z)
+ {
+ scalar_t v = 0;
+ #pragma unroll
+ for (int y = 0; y < filterH / upy; y++)
+ #pragma unroll
+ for (int x = 0; x < filterW / upx; x++)
+ v += sx[relInY + y][relInX + x][relC] * sf[filterY + y * upy][filterX + x * upx];
+ v *= p.gain;
+ ((T*)p.y)[outX * p.outStride.x + outY * p.outStride.y + c * p.outStride.z + n * p.outStride.w] = (T)v;
+ }
+ }
+ }
+ }
+}
+
+//------------------------------------------------------------------------
+// CUDA kernel selection.
+
+template upfirdn2d_kernel_spec choose_upfirdn2d_kernel(const upfirdn2d_kernel_params& p)
+{
+ int s = p.inStride.z, fx = p.filterSize.x, fy = p.filterSize.y;
+
+ upfirdn2d_kernel_spec spec = {(void*)upfirdn2d_kernel_large, -1,-1,1, 4}; // contiguous
+ if (s == 1) spec = {(void*)upfirdn2d_kernel_large, -1,-1,4, 1}; // channels_last
+
+ if (s != 1 && p.up.x == 1 && p.up.y == 1 && p.down.x == 1 && p.down.y == 1) // contiguous
+ {
+ if (fx <= 7 && fy <= 7 ) spec = {(void*)upfirdn2d_kernel_small, 64,16,1, 1};
+ if (fx <= 6 && fy <= 6 ) spec = {(void*)upfirdn2d_kernel_small, 64,16,1, 1};
+ if (fx <= 5 && fy <= 5 ) spec = {(void*)upfirdn2d_kernel_small, 64,16,1, 1};
+ if (fx <= 4 && fy <= 4 ) spec = {(void*)upfirdn2d_kernel_small, 64,16,1, 1};
+ if (fx <= 3 && fy <= 3 ) spec = {(void*)upfirdn2d_kernel_small, 64,16,1, 1};
+ if (fx <= 24 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 128,8,1, 1};
+ if (fx <= 20 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 128,8,1, 1};
+ if (fx <= 16 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 128,8,1, 1};
+ if (fx <= 12 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 128,8,1, 1};
+ if (fx <= 8 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 128,8,1, 1};
+ if (fx <= 1 && fy <= 24) spec = {(void*)upfirdn2d_kernel_small, 32,32,1, 1};
+ if (fx <= 1 && fy <= 20) spec = {(void*)upfirdn2d_kernel_small, 32,32,1, 1};
+ if (fx <= 1 && fy <= 16) spec = {(void*)upfirdn2d_kernel_small, 32,32,1, 1};
+ if (fx <= 1 && fy <= 12) spec = {(void*)upfirdn2d_kernel_small, 32,32,1, 1};
+ if (fx <= 1 && fy <= 8 ) spec = {(void*)upfirdn2d_kernel_small, 32,32,1, 1};
+ }
+ if (s == 1 && p.up.x == 1 && p.up.y == 1 && p.down.x == 1 && p.down.y == 1) // channels_last
+ {
+ if (fx <= 7 && fy <= 7 ) spec = {(void*)upfirdn2d_kernel_small, 16,16,8, 1};
+ if (fx <= 6 && fy <= 6 ) spec = {(void*)upfirdn2d_kernel_small, 16,16,8, 1};
+ if (fx <= 5 && fy <= 5 ) spec = {(void*)upfirdn2d_kernel_small, 16,16,8, 1};
+ if (fx <= 4 && fy <= 4 ) spec = {(void*)upfirdn2d_kernel_small, 16,16,8, 1};
+ if (fx <= 3 && fy <= 3 ) spec = {(void*)upfirdn2d_kernel_small, 16,16,8, 1};
+ if (fx <= 24 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 128,1,16, 1};
+ if (fx <= 20 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 128,1,16, 1};
+ if (fx <= 16 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 128,1,16, 1};
+ if (fx <= 12 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 128,1,16, 1};
+ if (fx <= 8 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 128,1,16, 1};
+ if (fx <= 1 && fy <= 24) spec = {(void*)upfirdn2d_kernel_small, 1,128,16, 1};
+ if (fx <= 1 && fy <= 20) spec = {(void*)upfirdn2d_kernel_small, 1,128,16, 1};
+ if (fx <= 1 && fy <= 16) spec = {(void*)upfirdn2d_kernel_small, 1,128,16, 1};
+ if (fx <= 1 && fy <= 12) spec = {(void*)upfirdn2d_kernel_small, 1,128,16, 1};
+ if (fx <= 1 && fy <= 8 ) spec = {(void*)upfirdn2d_kernel_small, 1,128,16, 1};
+ }
+ if (s != 1 && p.up.x == 2 && p.up.y == 2 && p.down.x == 1 && p.down.y == 1) // contiguous
+ {
+ if (fx <= 8 && fy <= 8 ) spec = {(void*)upfirdn2d_kernel_small, 64,16,1, 1};
+ if (fx <= 6 && fy <= 6 ) spec = {(void*)upfirdn2d_kernel_small, 64,16,1, 1};
+ if (fx <= 4 && fy <= 4 ) spec = {(void*)upfirdn2d_kernel_small, 64,16,1, 1};
+ if (fx <= 2 && fy <= 2 ) spec = {(void*)upfirdn2d_kernel_small, 64,16,1, 1};
+ }
+ if (s == 1 && p.up.x == 2 && p.up.y == 2 && p.down.x == 1 && p.down.y == 1) // channels_last
+ {
+ if (fx <= 8 && fy <= 8 ) spec = {(void*)upfirdn2d_kernel_small, 16,16,8, 1};
+ if (fx <= 6 && fy <= 6 ) spec = {(void*)upfirdn2d_kernel_small, 16,16,8, 1};
+ if (fx <= 4 && fy <= 4 ) spec = {(void*)upfirdn2d_kernel_small, 16,16,8, 1};
+ if (fx <= 2 && fy <= 2 ) spec = {(void*)upfirdn2d_kernel_small, 16,16,8, 1};
+ }
+ if (s != 1 && p.up.x == 2 && p.up.y == 1 && p.down.x == 1 && p.down.y == 1) // contiguous
+ {
+ if (fx <= 24 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 128,8,1, 1};
+ if (fx <= 20 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 128,8,1, 1};
+ if (fx <= 16 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 128,8,1, 1};
+ if (fx <= 12 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 128,8,1, 1};
+ if (fx <= 8 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 128,8,1, 1};
+ }
+ if (s == 1 && p.up.x == 2 && p.up.y == 1 && p.down.x == 1 && p.down.y == 1) // channels_last
+ {
+ if (fx <= 24 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 128,1,16, 1};
+ if (fx <= 20 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 128,1,16, 1};
+ if (fx <= 16 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 128,1,16, 1};
+ if (fx <= 12 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 128,1,16, 1};
+ if (fx <= 8 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 128,1,16, 1};
+ }
+ if (s != 1 && p.up.x == 1 && p.up.y == 2 && p.down.x == 1 && p.down.y == 1) // contiguous
+ {
+ if (fx <= 1 && fy <= 24) spec = {(void*)upfirdn2d_kernel_small, 32,32,1, 1};
+ if (fx <= 1 && fy <= 20) spec = {(void*)upfirdn2d_kernel_small, 32,32,1, 1};
+ if (fx <= 1 && fy <= 16) spec = {(void*)upfirdn2d_kernel_small, 32,32,1, 1};
+ if (fx <= 1 && fy <= 12) spec = {(void*)upfirdn2d_kernel_small, 32,32,1, 1};
+ if (fx <= 1 && fy <= 8 ) spec = {(void*)upfirdn2d_kernel_small, 32,32,1, 1};
+ }
+ if (s == 1 && p.up.x == 1 && p.up.y == 2 && p.down.x == 1 && p.down.y == 1) // channels_last
+ {
+ if (fx <= 1 && fy <= 24) spec = {(void*)upfirdn2d_kernel_small, 1,128,16, 1};
+ if (fx <= 1 && fy <= 20) spec = {(void*)upfirdn2d_kernel_small, 1,128,16, 1};
+ if (fx <= 1 && fy <= 16) spec = {(void*)upfirdn2d_kernel_small, 1,128,16, 1};
+ if (fx <= 1 && fy <= 12) spec = {(void*)upfirdn2d_kernel_small, 1,128,16, 1};
+ if (fx <= 1 && fy <= 8 ) spec = {(void*)upfirdn2d_kernel_small, 1,128,16, 1};
+ }
+ if (s != 1 && p.up.x == 1 && p.up.y == 1 && p.down.x == 2 && p.down.y == 2) // contiguous
+ {
+ if (fx <= 8 && fy <= 8 ) spec = {(void*)upfirdn2d_kernel_small, 32,8,1, 1};
+ if (fx <= 6 && fy <= 6 ) spec = {(void*)upfirdn2d_kernel_small, 32,8,1, 1};
+ if (fx <= 4 && fy <= 4 ) spec = {(void*)upfirdn2d_kernel_small, 32,8,1, 1};
+ if (fx <= 2 && fy <= 2 ) spec = {(void*)upfirdn2d_kernel_small, 32,8,1, 1};
+ }
+ if (s == 1 && p.up.x == 1 && p.up.y == 1 && p.down.x == 2 && p.down.y == 2) // channels_last
+ {
+ if (fx <= 8 && fy <= 8 ) spec = {(void*)upfirdn2d_kernel_small, 8,8,8, 1};
+ if (fx <= 6 && fy <= 6 ) spec = {(void*)upfirdn2d_kernel_small, 8,8,8, 1};
+ if (fx <= 4 && fy <= 4 ) spec = {(void*)upfirdn2d_kernel_small, 8,8,8, 1};
+ if (fx <= 2 && fy <= 2 ) spec = {(void*)upfirdn2d_kernel_small, 8,8,8, 1};
+ }
+ if (s != 1 && p.up.x == 1 && p.up.y == 1 && p.down.x == 2 && p.down.y == 1) // contiguous
+ {
+ if (fx <= 24 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 64,8,1, 1};
+ if (fx <= 20 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 64,8,1, 1};
+ if (fx <= 16 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 64,8,1, 1};
+ if (fx <= 12 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 64,8,1, 1};
+ if (fx <= 8 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 64,8,1, 1};
+ }
+ if (s == 1 && p.up.x == 1 && p.up.y == 1 && p.down.x == 2 && p.down.y == 1) // channels_last
+ {
+ if (fx <= 24 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 64,1,8, 1};
+ if (fx <= 20 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 64,1,8, 1};
+ if (fx <= 16 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 64,1,8, 1};
+ if (fx <= 12 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 64,1,8, 1};
+ if (fx <= 8 && fy <= 1 ) spec = {(void*)upfirdn2d_kernel_small, 64,1,8, 1};
+ }
+ if (s != 1 && p.up.x == 1 && p.up.y == 1 && p.down.x == 1 && p.down.y == 2) // contiguous
+ {
+ if (fx <= 1 && fy <= 24) spec = {(void*)upfirdn2d_kernel_small, 32,16,1, 1};
+ if (fx <= 1 && fy <= 20) spec = {(void*)upfirdn2d_kernel_small, 32,16,1, 1};
+ if (fx <= 1 && fy <= 16) spec = {(void*)upfirdn2d_kernel_small, 32,16,1, 1};
+ if (fx <= 1 && fy <= 12) spec = {(void*)upfirdn2d_kernel_small, 32,16,1, 1};
+ if (fx <= 1 && fy <= 8 ) spec = {(void*)upfirdn2d_kernel_small, 32,16,1, 1};
+ }
+ if (s == 1 && p.up.x == 1 && p.up.y == 1 && p.down.x == 1 && p.down.y == 2) // channels_last
+ {
+ if (fx <= 1 && fy <= 24) spec = {(void*)upfirdn2d_kernel_small, 1,64,8, 1};
+ if (fx <= 1 && fy <= 20) spec = {(void*)upfirdn2d_kernel_small, 1,64,8, 1};
+ if (fx <= 1 && fy <= 16) spec = {(void*)upfirdn2d_kernel_small, 1,64,8, 1};
+ if (fx <= 1 && fy <= 12) spec = {(void*)upfirdn2d_kernel_small, 1,64,8, 1};
+ if (fx <= 1 && fy <= 8 ) spec = {(void*)upfirdn2d_kernel_small, 1,64,8, 1};
+ }
+ return spec;
+}
+
+//------------------------------------------------------------------------
+// Template specializations.
+
+template upfirdn2d_kernel_spec choose_upfirdn2d_kernel (const upfirdn2d_kernel_params& p);
+template upfirdn2d_kernel_spec choose_upfirdn2d_kernel (const upfirdn2d_kernel_params& p);
+template upfirdn2d_kernel_spec choose_upfirdn2d_kernel(const upfirdn2d_kernel_params& p);
+
+//------------------------------------------------------------------------
diff --git a/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/upfirdn2d.h b/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/upfirdn2d.h
new file mode 100644
index 0000000..c9e2032
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/upfirdn2d.h
@@ -0,0 +1,59 @@
+// Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+//
+// NVIDIA CORPORATION and its licensors retain all intellectual property
+// and proprietary rights in and to this software, related documentation
+// and any modifications thereto. Any use, reproduction, disclosure or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA CORPORATION is strictly prohibited.
+
+#include
+
+//------------------------------------------------------------------------
+// CUDA kernel parameters.
+
+struct upfirdn2d_kernel_params
+{
+ const void* x;
+ const float* f;
+ void* y;
+
+ int2 up;
+ int2 down;
+ int2 pad0;
+ int flip;
+ float gain;
+
+ int4 inSize; // [width, height, channel, batch]
+ int4 inStride;
+ int2 filterSize; // [width, height]
+ int2 filterStride;
+ int4 outSize; // [width, height, channel, batch]
+ int4 outStride;
+ int sizeMinor;
+ int sizeMajor;
+
+ int loopMinor;
+ int loopMajor;
+ int loopX;
+ int launchMinor;
+ int launchMajor;
+};
+
+//------------------------------------------------------------------------
+// CUDA kernel specialization.
+
+struct upfirdn2d_kernel_spec
+{
+ void* kernel;
+ int tileOutW;
+ int tileOutH;
+ int loopMinor;
+ int loopX;
+};
+
+//------------------------------------------------------------------------
+// CUDA kernel selection.
+
+template upfirdn2d_kernel_spec choose_upfirdn2d_kernel(const upfirdn2d_kernel_params& p);
+
+//------------------------------------------------------------------------
diff --git a/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/upfirdn2d.py b/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/upfirdn2d.py
new file mode 100644
index 0000000..a0bbd22
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/sg3_torch_utils/ops/upfirdn2d.py
@@ -0,0 +1,388 @@
+# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
+#
+# NVIDIA CORPORATION and its licensors retain all intellectual property
+# and proprietary rights in and to this software, related documentation
+# and any modifications thereto. Any use, reproduction, disclosure or
+# distribution of this software and related documentation without an express
+# license agreement from NVIDIA CORPORATION is strictly prohibited.
+
+"""Custom PyTorch ops for efficient resampling of 2D images."""
+
+import os
+import warnings
+import numpy as np
+import torch
+import traceback
+
+from .. import custom_ops
+from .. import misc
+from . import conv2d_gradfix
+from torch.cuda.amp import custom_bwd, custom_fwd
+
+#----------------------------------------------------------------------------
+
+_inited = False
+_plugin = None
+enabled = False
+
+def _init():
+ global _inited, _plugin
+ if not _inited:
+ sources = ['upfirdn2d.cpp', 'upfirdn2d.cu']
+ sources = [os.path.join(os.path.dirname(__file__), s) for s in sources]
+ try:
+ _plugin = custom_ops.get_plugin('upfirdn2d_plugin', sources=sources, extra_cuda_cflags=['--use_fast_math'])
+ except:
+ warnings.warn('Failed to build CUDA kernels for upfirdn2d. Falling back to slow reference implementation. Details:\n\n' + traceback.format_exc())
+ return _plugin is not None
+
+def _parse_scaling(scaling):
+ if isinstance(scaling, int):
+ scaling = [scaling, scaling]
+ assert isinstance(scaling, (list, tuple))
+ assert all(isinstance(x, int) for x in scaling)
+ sx, sy = scaling
+ assert sx >= 1 and sy >= 1
+ return sx, sy
+
+def _parse_padding(padding):
+ if isinstance(padding, int):
+ padding = [padding, padding]
+ assert isinstance(padding, (list, tuple))
+ assert all(isinstance(x, int) for x in padding)
+ if len(padding) == 2:
+ padx, pady = padding
+ padding = [padx, padx, pady, pady]
+ padx0, padx1, pady0, pady1 = padding
+ return padx0, padx1, pady0, pady1
+
+def _get_filter_size(f):
+ if f is None:
+ return 1, 1
+ assert isinstance(f, torch.Tensor) and f.ndim in [1, 2]
+ fw = f.shape[-1]
+ fh = f.shape[0]
+ with misc.suppress_tracer_warnings():
+ fw = int(fw)
+ fh = int(fh)
+ misc.assert_shape(f, [fh, fw][:f.ndim])
+ assert fw >= 1 and fh >= 1
+ return fw, fh
+
+#----------------------------------------------------------------------------
+
+def setup_filter(f, device=torch.device('cpu'), normalize=True, flip_filter=False, gain=1, separable=None):
+ r"""Convenience function to setup 2D FIR filter for `upfirdn2d()`.
+
+ Args:
+ f: Torch tensor, numpy array, or python list of the shape
+ `[filter_height, filter_width]` (non-separable),
+ `[filter_taps]` (separable),
+ `[]` (impulse), or
+ `None` (identity).
+ device: Result device (default: cpu).
+ normalize: Normalize the filter so that it retains the magnitude
+ for constant input signal (DC)? (default: True).
+ flip_filter: Flip the filter? (default: False).
+ gain: Overall scaling factor for signal magnitude (default: 1).
+ separable: Return a separable filter? (default: select automatically).
+
+ Returns:
+ Float32 tensor of the shape
+ `[filter_height, filter_width]` (non-separable) or
+ `[filter_taps]` (separable).
+ """
+ # Validate.
+ if f is None:
+ f = 1
+ f = torch.as_tensor(f, dtype=torch.float32)
+ assert f.ndim in [0, 1, 2]
+ assert f.numel() > 0
+ if f.ndim == 0:
+ f = f[np.newaxis]
+
+ # Separable?
+ if separable is None:
+ separable = (f.ndim == 1 and f.numel() >= 8)
+ if f.ndim == 1 and not separable:
+ f = f.ger(f)
+ assert f.ndim == (1 if separable else 2)
+
+ # Apply normalize, flip, gain, and device.
+ if normalize:
+ f /= f.sum()
+ if flip_filter:
+ f = f.flip(list(range(f.ndim)))
+ f = f * (gain ** (f.ndim / 2))
+ f = f.to(device=device)
+ return f
+
+#----------------------------------------------------------------------------
+
+def upfirdn2d(x, f, up=1, down=1, padding=0, flip_filter=False, gain=1, impl='cuda'):
+ r"""Pad, upsample, filter, and downsample a batch of 2D images.
+
+ Performs the following sequence of operations for each channel:
+
+ 1. Upsample the image by inserting N-1 zeros after each pixel (`up`).
+
+ 2. Pad the image with the specified number of zeros on each side (`padding`).
+ Negative padding corresponds to cropping the image.
+
+ 3. Convolve the image with the specified 2D FIR filter (`f`), shrinking it
+ so that the footprint of all output pixels lies within the input image.
+
+ 4. Downsample the image by keeping every Nth pixel (`down`).
+
+ This sequence of operations bears close resemblance to scipy.signal.upfirdn().
+ The fused op is considerably more efficient than performing the same calculation
+ using standard PyTorch ops. It supports gradients of arbitrary order.
+
+ Args:
+ x: Float32/float64/float16 input tensor of the shape
+ `[batch_size, num_channels, in_height, in_width]`.
+ f: Float32 FIR filter of the shape
+ `[filter_height, filter_width]` (non-separable),
+ `[filter_taps]` (separable), or
+ `None` (identity).
+ up: Integer upsampling factor. Can be a single int or a list/tuple
+ `[x, y]` (default: 1).
+ down: Integer downsampling factor. Can be a single int or a list/tuple
+ `[x, y]` (default: 1).
+ padding: Padding with respect to the upsampled image. Can be a single number
+ or a list/tuple `[x, y]` or `[x_before, x_after, y_before, y_after]`
+ (default: 0).
+ flip_filter: False = convolution, True = correlation (default: False).
+ gain: Overall scaling factor for signal magnitude (default: 1).
+ impl: Implementation to use. Can be `'ref'` or `'cuda'` (default: `'cuda'`).
+
+ Returns:
+ Tensor of the shape `[batch_size, num_channels, out_height, out_width]`.
+ """
+ assert isinstance(x, torch.Tensor)
+ assert impl in ['ref', 'cuda']
+ if impl == 'cuda' and x.device.type == 'cuda' and enabled and _init():
+ return _upfirdn2d_cuda(up=up, down=down, padding=padding, flip_filter=flip_filter, gain=gain).apply(x, f)
+ return _upfirdn2d_ref(x, f, up=up, down=down, padding=padding, flip_filter=flip_filter, gain=gain)
+
+#----------------------------------------------------------------------------
+
+@misc.profiled_function
+def _upfirdn2d_ref(x, f, up=1, down=1, padding=0, flip_filter=False, gain=1):
+ """Slow reference implementation of `upfirdn2d()` using standard PyTorch ops.
+ """
+ # Validate arguments.
+ assert isinstance(x, torch.Tensor) and x.ndim == 4
+ if f is None:
+ f = torch.ones([1, 1], dtype=torch.float32, device=x.device)
+ assert isinstance(f, torch.Tensor) and f.ndim in [1, 2]
+ assert f.dtype == torch.float32 and not f.requires_grad
+ batch_size, num_channels, in_height, in_width = x.shape
+ upx, upy = _parse_scaling(up)
+ downx, downy = _parse_scaling(down)
+ padx0, padx1, pady0, pady1 = _parse_padding(padding)
+
+ # Upsample by inserting zeros.
+ x = x.reshape([batch_size, num_channels, in_height, 1, in_width, 1])
+ x = torch.nn.functional.pad(x, [0, upx - 1, 0, 0, 0, upy - 1])
+ x = x.reshape([batch_size, num_channels, in_height * upy, in_width * upx])
+
+ # Pad or crop.
+ x = torch.nn.functional.pad(x, [max(padx0, 0), max(padx1, 0), max(pady0, 0), max(pady1, 0)])
+ x = x[:, :, max(-pady0, 0) : x.shape[2] - max(-pady1, 0), max(-padx0, 0) : x.shape[3] - max(-padx1, 0)]
+
+ # Setup filter.
+ f = f * (gain ** (f.ndim / 2))
+ f = f.to(x.dtype)
+ if not flip_filter:
+ f = f.flip(list(range(f.ndim)))
+
+ # Convolve with the filter.
+ f = f[np.newaxis, np.newaxis].repeat([num_channels, 1] + [1] * f.ndim)
+ if f.ndim == 4:
+ x = conv2d_gradfix.conv2d(input=x, weight=f, groups=num_channels)
+ else:
+ x = conv2d_gradfix.conv2d(input=x, weight=f.unsqueeze(2), groups=num_channels)
+ x = conv2d_gradfix.conv2d(input=x, weight=f.unsqueeze(3), groups=num_channels)
+
+ # Downsample by throwing away pixels.
+ x = x[:, :, ::downy, ::downx]
+ return x
+
+#----------------------------------------------------------------------------
+
+_upfirdn2d_cuda_cache = dict()
+
+def _upfirdn2d_cuda(up=1, down=1, padding=0, flip_filter=False, gain=1):
+ """Fast CUDA implementation of `upfirdn2d()` using custom ops.
+ """
+ # Parse arguments.
+ upx, upy = _parse_scaling(up)
+ downx, downy = _parse_scaling(down)
+ padx0, padx1, pady0, pady1 = _parse_padding(padding)
+
+ # Lookup from cache.
+ key = (upx, upy, downx, downy, padx0, padx1, pady0, pady1, flip_filter, gain)
+ if key in _upfirdn2d_cuda_cache:
+ return _upfirdn2d_cuda_cache[key]
+
+ # Forward op.
+ class Upfirdn2dCuda(torch.autograd.Function):
+ @staticmethod
+ @custom_fwd(cast_inputs=torch.float32)
+ def forward(ctx, x, f): # pylint: disable=arguments-differ
+ assert isinstance(x, torch.Tensor) and x.ndim == 4
+ if f is None:
+ f = torch.ones([1, 1], dtype=torch.float32, device=x.device)
+ assert isinstance(f, torch.Tensor) and f.ndim in [1, 2]
+ y = x
+ if f.ndim == 2:
+ y = _plugin.upfirdn2d(y, f, upx, upy, downx, downy, padx0, padx1, pady0, pady1, flip_filter, gain)
+ else:
+ y = _plugin.upfirdn2d(y, f.unsqueeze(0), upx, 1, downx, 1, padx0, padx1, 0, 0, flip_filter, np.sqrt(gain))
+ y = _plugin.upfirdn2d(y, f.unsqueeze(1), 1, upy, 1, downy, 0, 0, pady0, pady1, flip_filter, np.sqrt(gain))
+ ctx.save_for_backward(f)
+ ctx.x_shape = x.shape
+ return y
+
+ @staticmethod
+ @custom_bwd
+ def backward(ctx, dy): # pylint: disable=arguments-differ
+ f, = ctx.saved_tensors
+ _, _, ih, iw = ctx.x_shape
+ _, _, oh, ow = dy.shape
+ fw, fh = _get_filter_size(f)
+ p = [
+ fw - padx0 - 1,
+ iw * upx - ow * downx + padx0 - upx + 1,
+ fh - pady0 - 1,
+ ih * upy - oh * downy + pady0 - upy + 1,
+ ]
+ dx = None
+ df = None
+
+ if ctx.needs_input_grad[0]:
+ dx = _upfirdn2d_cuda(up=down, down=up, padding=p, flip_filter=(not flip_filter), gain=gain).apply(dy, f)
+
+ assert not ctx.needs_input_grad[1]
+ return dx, df
+
+ # Add to cache.
+ _upfirdn2d_cuda_cache[key] = Upfirdn2dCuda
+ return Upfirdn2dCuda
+
+#----------------------------------------------------------------------------
+
+def filter2d(x, f, padding=0, flip_filter=False, gain=1, impl='cuda'):
+ r"""Filter a batch of 2D images using the given 2D FIR filter.
+
+ By default, the result is padded so that its shape matches the input.
+ User-specified padding is applied on top of that, with negative values
+ indicating cropping. Pixels outside the image are assumed to be zero.
+
+ Args:
+ x: Float32/float64/float16 input tensor of the shape
+ `[batch_size, num_channels, in_height, in_width]`.
+ f: Float32 FIR filter of the shape
+ `[filter_height, filter_width]` (non-separable),
+ `[filter_taps]` (separable), or
+ `None` (identity).
+ padding: Padding with respect to the output. Can be a single number or a
+ list/tuple `[x, y]` or `[x_before, x_after, y_before, y_after]`
+ (default: 0).
+ flip_filter: False = convolution, True = correlation (default: False).
+ gain: Overall scaling factor for signal magnitude (default: 1).
+ impl: Implementation to use. Can be `'ref'` or `'cuda'` (default: `'cuda'`).
+
+ Returns:
+ Tensor of the shape `[batch_size, num_channels, out_height, out_width]`.
+ """
+ padx0, padx1, pady0, pady1 = _parse_padding(padding)
+ fw, fh = _get_filter_size(f)
+ p = [
+ padx0 + fw // 2,
+ padx1 + (fw - 1) // 2,
+ pady0 + fh // 2,
+ pady1 + (fh - 1) // 2,
+ ]
+ return upfirdn2d(x, f, padding=p, flip_filter=flip_filter, gain=gain, impl=impl)
+
+#----------------------------------------------------------------------------
+
+def upsample2d(x, f, up=2, padding=0, flip_filter=False, gain=1, impl='cuda'):
+ r"""Upsample a batch of 2D images using the given 2D FIR filter.
+
+ By default, the result is padded so that its shape is a multiple of the input.
+ User-specified padding is applied on top of that, with negative values
+ indicating cropping. Pixels outside the image are assumed to be zero.
+
+ Args:
+ x: Float32/float64/float16 input tensor of the shape
+ `[batch_size, num_channels, in_height, in_width]`.
+ f: Float32 FIR filter of the shape
+ `[filter_height, filter_width]` (non-separable),
+ `[filter_taps]` (separable), or
+ `None` (identity).
+ up: Integer upsampling factor. Can be a single int or a list/tuple
+ `[x, y]` (default: 1).
+ padding: Padding with respect to the output. Can be a single number or a
+ list/tuple `[x, y]` or `[x_before, x_after, y_before, y_after]`
+ (default: 0).
+ flip_filter: False = convolution, True = correlation (default: False).
+ gain: Overall scaling factor for signal magnitude (default: 1).
+ impl: Implementation to use. Can be `'ref'` or `'cuda'` (default: `'cuda'`).
+
+ Returns:
+ Tensor of the shape `[batch_size, num_channels, out_height, out_width]`.
+ """
+ upx, upy = _parse_scaling(up)
+ padx0, padx1, pady0, pady1 = _parse_padding(padding)
+ fw, fh = _get_filter_size(f)
+ p = [
+ padx0 + (fw + upx - 1) // 2,
+ padx1 + (fw - upx) // 2,
+ pady0 + (fh + upy - 1) // 2,
+ pady1 + (fh - upy) // 2,
+ ]
+ return upfirdn2d(x, f, up=up, padding=p, flip_filter=flip_filter, gain=gain*upx*upy, impl=impl)
+
+#----------------------------------------------------------------------------
+
+def downsample2d(x, f, down=2, padding=0, flip_filter=False, gain=1, impl='cuda'):
+ r"""Downsample a batch of 2D images using the given 2D FIR filter.
+
+ By default, the result is padded so that its shape is a fraction of the input.
+ User-specified padding is applied on top of that, with negative values
+ indicating cropping. Pixels outside the image are assumed to be zero.
+
+ Args:
+ x: Float32/float64/float16 input tensor of the shape
+ `[batch_size, num_channels, in_height, in_width]`.
+ f: Float32 FIR filter of the shape
+ `[filter_height, filter_width]` (non-separable),
+ `[filter_taps]` (separable), or
+ `None` (identity).
+ down: Integer downsampling factor. Can be a single int or a list/tuple
+ `[x, y]` (default: 1).
+ padding: Padding with respect to the input. Can be a single number or a
+ list/tuple `[x, y]` or `[x_before, x_after, y_before, y_after]`
+ (default: 0).
+ flip_filter: False = convolution, True = correlation (default: False).
+ gain: Overall scaling factor for signal magnitude (default: 1).
+ impl: Implementation to use. Can be `'ref'` or `'cuda'` (default: `'cuda'`).
+
+ Returns:
+ Tensor of the shape `[batch_size, num_channels, out_height, out_width]`.
+ """
+ downx, downy = _parse_scaling(down)
+ padx0, padx1, pady0, pady1 = _parse_padding(padding)
+ fw, fh = _get_filter_size(f)
+ p = [
+ padx0 + (fw - downx + 1) // 2,
+ padx1 + (fw - downx) // 2,
+ pady0 + (fh - downy + 1) // 2,
+ pady1 + (fh - downy) // 2,
+ ]
+ return upfirdn2d(x, f, down=down, padding=p, flip_filter=flip_filter, gain=gain, impl=impl)
+
+#----------------------------------------------------------------------------
diff --git a/project/models/deprecated_deep_privacy2/stylemc.py b/project/models/deprecated_deep_privacy2/stylemc.py
new file mode 100644
index 0000000..0296950
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/stylemc.py
@@ -0,0 +1,195 @@
+"""
+Approach: "StyleMC: Multi-Channel Based Fast Text-Guided Image Generation and Manipulation"
+Original source code:
+https://github.com/autonomousvision/stylegan_xl/blob/f9be58e98110bd946fcdadef2aac8345466faaf3/run_stylemc.py#
+Modified by Håkon Hukkelås
+"""
+import click
+from pathlib import Path
+import tqdm
+from dp2 import utils
+import tops
+from timeit import default_timer as timer
+import torch
+import torch.nn.functional as F
+from torchvision.transforms.functional import resize, normalize
+import clip
+from dp2.gan_trainer import AverageMeter
+from tops.config import instantiate
+from dp2.utils import vis_utils
+
+
+def spherical_dist_loss(x, y):
+ x = F.normalize(x, dim=-1)
+ y = F.normalize(y, dim=-1)
+ return (x - y).norm(dim=-1).div(2).arcsin().pow(2).mul(2)
+
+
+def prompts_dist_loss(x, targets):
+ loss = spherical_dist_loss
+ if len(targets) == 1:
+ return loss(x, targets[0])
+ distances = [loss(x, target) for target in targets]
+ return torch.stack(distances, dim=-1).sum(dim=-1)
+
+
+affine_modules = None
+max_ch = None
+
+
+@torch.no_grad()
+def init_affine_modules(G, batch):
+ global affine_modules, max_ch
+ affine_modules = []
+ max_ch = 0
+
+ def forward_hook(block, input_, output_):
+ global max_ch
+ affine_modules.append(block)
+ max_ch = max(max_ch, block.affine.out_features * (1 + hasattr(block, "affine_beta")))
+ removable_handles = []
+ for block in G.modules():
+ if hasattr(block, "affine") and hasattr(block.affine, "weight"):
+ removable_handles.append(block.register_forward_hook(forward_hook))
+ G(**batch)
+ for hook in removable_handles:
+ hook.remove()
+
+
+@torch.no_grad()
+def get_stylesW(w):
+ global affine_modules, max_ch
+ assert affine_modules is not None, "Have to run init_affine_modules first"
+
+ all_styles = torch.zeros((len(affine_modules), max_ch), device=w.device, dtype=torch.float32)
+ for i, block in enumerate(affine_modules):
+ gamma0 = block.affine(w)
+ if hasattr(block, "affine_beta"):
+ beta0 = block.affine_beta(w)
+ gamma0 = torch.cat((gamma0, beta0), dim=1)
+ all_styles[i] = F.pad(gamma0, ((0, max_ch - gamma0.shape[-1])), "constant", 0)
+
+ return all_styles
+
+@torch.no_grad()
+def get_styles(seed, G: torch.nn.Module, batch, truncation_value=1):
+ global affine_modules, max_ch
+ if affine_modules is None:
+ init_affine_modules(G, batch)
+ w = G.style_net.get_truncated(truncation_value, n=batch["condition"].shape[0], seed=seed)
+
+ all_styles = torch.zeros((len(affine_modules), max_ch), device=batch["img"].device, dtype=torch.float32)
+ for i, block in enumerate(affine_modules):
+ gamma0 = block.affine(w)
+ if hasattr(block, "affine_beta"):
+ beta0 = block.affine_beta(w)
+ gamma0 = torch.cat((gamma0, beta0), dim=1)
+ all_styles[i] = F.pad(gamma0, ((0, max_ch - gamma0.shape[-1])), "constant", 0)
+
+ return all_styles
+
+
+def get_and_cache_direction(output_dir: Path, dl_val, G, text_prompt):
+ cache_path = output_dir.joinpath("stylemc_cache", text_prompt.replace(" ", "_") + ".torch")
+ if cache_path.is_file():
+ return torch.load(cache_path)
+ direction = find_direction(G, text_prompt, dl_val=iter(dl_val))
+ cache_path.parent.mkdir(exist_ok=True, parents=True)
+ torch.save(direction, cache_path)
+ return direction
+
+@torch.enable_grad()
+@torch.cuda.amp.autocast()
+def find_direction(
+ G,
+ text_prompt,
+ n_iterations=128 * 8 * 10,
+ batch_size=8,
+ dl_val=None
+):
+ time_start = timer()
+ clip_model = clip.load("ViT-B/16", device=tops.get_device())[0]
+ target = [clip_model.encode_text(clip.tokenize(text_prompt).to(tops.get_device())).float()]
+ first_batch = next(dl_val)
+ first_batch["embedding"] = None if "embedding" not in first_batch else first_batch["embedding"]
+ s = get_styles(0, G, first_batch, 0)
+ # stats tracker
+ tracker = AverageMeter()
+ n_iterations = n_iterations // batch_size
+
+ # initalize styles direction
+ direction = torch.zeros(s.shape, device=tops.get_device())
+ direction.requires_grad_()
+ utils.set_requires_grad(G, False)
+ direction_tracker = torch.zeros_like(direction)
+ opt = torch.optim.AdamW([direction], lr=0.05, betas=(0., 0.999), weight_decay=0.25)
+
+ grads = []
+ for seed_idx in tqdm.trange(n_iterations):
+ # forward pass through synthesis network with new styles
+ if seed_idx == 0:
+ batch = first_batch
+ else:
+ batch = next(dl_val)
+ batch["embedding"] = None if "embedding" not in batch else batch["embedding"]
+ styles = get_styles(seed_idx, G, batch) + direction
+ img = G(**batch, s=iter(styles))["img"]
+
+ # clip loss
+ img = (img + 1) / 2
+ img = normalize(img, mean=(0.48145466, 0.4578275, 0.40821073), std=(0.26862954, 0.26130258, 0.27577711))
+ img = resize(img, (224, 224))
+ embeds = clip_model.encode_image(img)
+ cos_sim = prompts_dist_loss(embeds, target)
+ cos_sim.backward(retain_graph=True)
+ # track stats
+ tracker.update(dict(cos_sim=cos_sim, norm=torch.norm(direction)))
+ if not (seed_idx % batch_size):
+ opt.step()
+ grads.append(direction.grad.clone())
+ direction.grad.data.zero_()
+ print(tracker.get_average())
+ tracker = AverageMeter()
+
+ # throw out fluctuating channels
+ direction = direction.detach()
+ direction[direction_tracker > n_iterations / 4] = 0
+ print(direction)
+ print(f"Time for direction search: {timer() - time_start:.2f} s")
+ return direction
+
+
+@click.command()
+@click.argument("config_path")
+@click.argument("text_prompt")
+@click.option("-n", default=50, type=int)
+def main(config_path: str, text_prompt: str, n: int):
+ from dp2.infer import build_trained_generator
+ from PIL import Image
+ cfg = utils.load_config(config_path)
+ G = build_trained_generator(cfg)
+ cfg.train.batch_size = 1
+ dl_val = instantiate(cfg.data.val.loader)
+ direction = get_and_cache_direction(cfg.output_dir, dl_val, G, text_prompt)
+ output_dir = Path("stylemc_results")
+ output_dir.mkdir(exist_ok=True, parents=True)
+ strenghts = [0, 0.05, 0.1, 0.2, 0.3, 0.4, 1.0]
+ for i, batch in enumerate(iter(dl_val)):
+ imgs = []
+
+ img = vis_utils.visualize_batch(**batch)
+ img = tops.im2numpy(img, False)[0]
+ imgs.append(img)
+ if i > n:
+ break
+ for strength in strenghts:
+ styles = get_styles(i, G, batch, truncation_value=0) + direction * strength
+ img = G(**batch, s=iter(styles))["img"]
+ imgs.append(utils.im2numpy(img, True, True)[0])
+
+ img = tops.np_make_image_grid(imgs, nrow=1)
+ Image.fromarray(img).save(output_dir.joinpath(f"results_{i}.png"))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/project/models/deprecated_deep_privacy2/tools/__init__.py b/project/models/deprecated_deep_privacy2/tools/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/project/models/deprecated_deep_privacy2/tools/anonymization/bdd100k/annotate_faces.py b/project/models/deprecated_deep_privacy2/tools/anonymization/bdd100k/annotate_faces.py
new file mode 100644
index 0000000..473e8d9
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/tools/anonymization/bdd100k/annotate_faces.py
@@ -0,0 +1,74 @@
+import numpy as np
+import cv2
+import tqdm
+import json
+from pathlib import Path
+from face_detection import build_detector
+from pycocotools.coco import COCO
+from ..coco.annotate_faces import draw_faces, get_matches
+from PIL import Image
+from detectron2.data.detection_utils import _apply_exif_orientation
+
+def annotate_bdd100k():
+ detector = build_detector(
+ clip_boxes=True,
+ confidence_threshold=0.3
+ )
+ source_directory = Path("/mnt/work2/haakohu/datasets/bdd100k")
+ data = COCO(source_directory.joinpath("jsons/ins_seg_train_cocofmt.json"))
+
+ final_boxes = dict()
+ n_instances = 0
+ n_matched_boxes = 0
+ for image_id in tqdm.tqdm(data.imgs):
+ image_info = data.loadImgs([image_id])[0]
+ image_path = source_directory.joinpath("images", "10k", "train", image_info["file_name"])
+
+ im = Image.open(image_path)
+ im = _apply_exif_orientation(im)
+ im = np.array(im.convert("RGB"))
+ annotation_ids = data.getAnnIds([image_id])
+ annotations = data.loadAnns(annotation_ids)
+ if len(annotations) == 0:
+ continue
+ segmentation = []
+ for annotation in annotations:
+ if annotation["iscrowd"] or annotation["ignore"]:
+ continue
+ if annotation["category_id"] != 1:
+ continue
+ seg = data.annToMask(annotation)
+ segmentation.append(seg)
+ if len(segmentation) == 0:
+ continue
+ boxes = detector.detect(im)
+ n_instances += len(segmentation)
+ if len(boxes) == 0:
+ continue
+
+ segmentation = np.stack(segmentation)
+ matches, filtered_boxes_by_IoU_thr = get_matches(boxes, segmentation)
+ final_boxes_ = [boxes[i, :4].tolist() for i, j in matches]
+ final_boxes[str(image_id)] = final_boxes_
+ n_matched_boxes += len(final_boxes_)
+ if len(filtered_boxes_by_IoU_thr) > 0:
+ im = cv2.imread(str(image_path))
+ boxes = [boxes[i, :4] for i in filtered_boxes_by_IoU_thr]
+ draw_faces(im, boxes)
+ out_dir = Path(f"tools/anonymization/bdd100k/filtered_by_IOU/{image_path.name}")
+ out_dir.parent.mkdir(exist_ok=True, parents=True)
+ print("SAved to", out_dir)
+ mask = segmentation.any(axis=0)[:, :, None]
+ im = (im*.7 + 0.3*mask*255).astype(np.uint8)
+ cv2.imwrite(str(out_dir), im)
+ #cv2.imshow("frame", im)
+ #key = cv2.waitKey(0)
+ print(f"Out of {n_instances} instances, {n_matched_boxes} are matched to a segmentation.")
+
+ target_path = source_directory.joinpath("face_boxes_train.json")
+ with open(target_path, "w") as fp:
+ json.dump(final_boxes, fp)
+
+
+if __name__ == "__main__":
+ annotate_bdd100k()
diff --git a/project/models/deprecated_deep_privacy2/tools/anonymization/bdd100k/anonymize_body.py b/project/models/deprecated_deep_privacy2/tools/anonymization/bdd100k/anonymize_body.py
new file mode 100644
index 0000000..ff6dbb3
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/tools/anonymization/bdd100k/anonymize_body.py
@@ -0,0 +1,137 @@
+import numpy as np
+import tqdm
+import click
+from pathlib import Path
+import tops
+from pycocotools.coco import COCO
+from PIL import Image
+from detectron2.data.detection_utils import _apply_exif_orientation
+from dp2 import utils
+from tops.config import instantiate
+import torch
+import shutil
+from ..cityscapes.anonymize_body import cse_post_process_cfg
+from dp2.detection.structures import PersonDetection
+from dp2.anonymizer.histogram_match_anonymizers import HistogramMatchAnonymizer, LatentHistogramMatchAnonymizer
+
+def iteratively_anonymize(target_directory: Path, anonymizer, synthesis_kwargs):
+
+ source_directory = Path("/mnt/work2/haakohu/datasets/bdd100k")
+ data = COCO(source_directory.joinpath("jsons/ins_seg_train_cocofmt.json"))
+
+ with open(source_directory.joinpath("annotated_keypoints_train.json"), "r") as fp:
+ import json
+ all_keypoints = json.load(fp)
+ vis_thr = .3
+ all_boxes = []
+ n_filtered = 0
+ n_keypoints_all_zeros = 0
+ n_instances = 0
+ for image_id in tqdm.tqdm(data.imgs):
+ image_info = data.loadImgs([image_id])[0]
+
+ image_path = source_directory.joinpath("images", "10k", "train", image_info["file_name"])
+ output_path = target_directory.joinpath(image_path.name)
+ output_path.parent.mkdir(exist_ok=True, parents=True)
+ annotation_ids = data.getAnnIds([image_id])
+ annotations = data.loadAnns(annotation_ids)
+ if str(image_id) not in all_keypoints or len(annotations) == 0:
+ shutil.copy(image_path, output_path)
+ continue
+ segmentation = []
+ for annotation in annotations:
+ if annotation["iscrowd"] or annotation["ignore"]:
+ continue
+ if annotation["category_id"] != 1:
+ continue
+ seg = data.annToMask(annotation)
+ segmentation.append(seg)
+ if len(segmentation) == 0:
+ shutil.copy(image_path, output_path)
+ continue
+ assert len(segmentation) > 0
+
+ segmentation = torch.from_numpy(np.stack(segmentation))
+ keypoints = np.array(all_keypoints[str(image_id)]["keypoints"])
+ keypoints = torch.from_numpy(np.stack(keypoints)).float()
+ keypoints[:, :, 2] = keypoints[:, :, 2] > vis_thr
+ n_instances += keypoints.shape[0]
+ n_keypoints_all_zeros += (keypoints[:, :, -1] < 0.5).all(dim=-1).sum().item()
+ im = Image.open(image_path)
+ detection = PersonDetection(
+ segmentation,
+ **cse_post_process_cfg,
+ orig_imshape_CHW=(3, *im.size[::-1]),
+ keypoints=keypoints
+ )
+
+ detection.pre_process()
+ all_boxes.extend(detection.boxes)
+ n_filtered += len(keypoints) - len(detection)
+
+ orig_im_mode = im.mode
+ im = _apply_exif_orientation(im)
+ im = im.convert("RGB")
+ im = torch.from_numpy(np.rollaxis(np.array(im), 2))
+ im = anonymizer.forward(im, detections=[detection], **synthesis_kwargs)
+ im = Image.fromarray(utils.im2numpy(im)).convert(orig_im_mode)
+ im.save(output_path, format="JPEG", optimize=False, quality=100, subsampling=0)
+ print(f"Detected {n_instances}, where {n_keypoints_all_zeros} where not detected by keypoints. In total, {n_keypoints_all_zeros/n_instances*100:.2f}% where not detected with keypoints.")
+ area = [((b[2] - b[0])*(b[3] - b[1]))**0.5 for b in all_boxes]
+ widths = [(b[2] - b[0]) for b in all_boxes]
+ heights = [(b[3] - b[1]) for b in all_boxes]
+ print("Total boxes:", len(all_boxes))
+ print("Number of boxes", len(all_boxes))
+ print("Average area:", np.mean(area))
+ print("Average width:", np.mean(widths))
+ print("Average height:", np.mean(heights))
+ print("Percentage over 288x160:", np.mean([a**2 > 288*160 for a in area]))
+ print(f"Detected {n_instances}, where {n_filtered} where filtered by min size. In total, {n_filtered/n_instances*100:.2f}% where filtered out.")
+ print("Num filtered boxes:", n_filtered)
+
+
+@click.command()
+@click.argument("config_path")
+@click.option("--match-histogram", default=False, is_flag=True)
+@click.option("--sampler", default="MMT", type=click.Choice(["MMT", "SMT", "None"]))
+@click.option("--n-sampling-steps", "-n", default=1, type=int)
+@click.option("--min_size", default=None, type=click.Choice([None, '16', '32']))
+def main(config_path, match_histogram, sampler, n_sampling_steps, kp_fix, min_size):
+ cfg = utils.load_config(config_path)
+ target_dir = Path("/mnt/work2/haakohu/datasets/bdd100k_anonymized_2023/")
+ name = {
+ "configs/anonymizers/traditional/body/gaussian.py": "dp2_body_gaussian",
+ "configs/anonymizers/traditional/body/maskout.py": "dp2_body_maskout",
+ "configs/anonymizers/FB_triagan.py": "dp2_body_triaGAN"
+ }[config_path]
+ if match_histogram:
+ assert name not in ["dp2_body_gaussian", "dp2_body_maskout"]
+ name += "_MH"
+ cfg.anonymizer._target_ = HistogramMatchAnonymizer
+ if n_sampling_steps > 1:
+ cfg.anonymizer._target_ = LatentHistogramMatchAnonymizer
+ name += f"_sample{n_sampling_steps}"
+
+ if name not in ["dp2_body_gaussian", "dp2_body_maskout"]:
+ name += f"_{sampler}"
+ if min_size is not None:
+ name += f"_minsize{min_size}"
+ cse_post_process_cfg["exp_bbox_filter"]["minimum_area"] = int(min_size)*int(min_size)
+
+ target_dir = target_dir.joinpath(name, "bdd100k", "images", "10k", "train")
+ tops.set_seed(0)
+ tops.set_AMP(False)
+
+ anonymizer = instantiate(cfg.anonymizer, load_cache=True)
+ synthesis_kwargs = dict(
+ amp=False,
+ multi_modal_truncation=sampler == "MMT",
+ truncation_value=1 if sampler == "None" else 0)
+ if n_sampling_steps > 1:
+ synthesis_kwargs["n_sampling_steps"] = n_sampling_steps
+
+ iteratively_anonymize(
+ target_dir,
+ anonymizer, synthesis_kwargs)
+
+main()
diff --git a/project/models/deprecated_deep_privacy2/tools/anonymization/bdd100k/anonymize_faces.py b/project/models/deprecated_deep_privacy2/tools/anonymization/bdd100k/anonymize_faces.py
new file mode 100644
index 0000000..e563363
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/tools/anonymization/bdd100k/anonymize_faces.py
@@ -0,0 +1,83 @@
+import numpy as np
+import tqdm
+import click
+from pathlib import Path
+import tops
+from pycocotools.coco import COCO
+from PIL import Image
+from detectron2.data.detection_utils import _apply_exif_orientation
+from dp2 import utils
+from tops.config import instantiate
+import torch
+import shutil
+from dp2.detection.structures import FaceDetection
+
+def iteratively_anonymize(target_directory: Path, anonymizer, synthesis_kwargs):
+
+ source_directory = Path("/mnt/work2/haakohu/datasets/bdd100k")
+ data = COCO(source_directory.joinpath("jsons/ins_seg_train_cocofmt.json"))
+
+ with open(source_directory.joinpath("face_boxes_train.json"), "r") as fp:
+ import json
+ face_detections = json.load(fp)
+ for image_id in tqdm.tqdm(data.imgs):
+ image_info = data.loadImgs([image_id])[0]
+
+ image_path = source_directory.joinpath("images", "10k", "train", image_info["file_name"])
+ output_path = target_directory.joinpath(image_path.name)
+ output_path.parent.mkdir(exist_ok=True, parents=True)
+ annotation_ids = data.getAnnIds([image_id])
+ annotations = data.loadAnns(annotation_ids)
+
+ if str(image_id) not in face_detections or len(annotations) == 0:
+ shutil.copy(image_path, output_path)
+ continue
+ segmentation = []
+ for annotation in annotations:
+ if annotation["iscrowd"] or annotation["ignore"]:
+ continue
+ if annotation["category_id"] != 1:
+ continue
+ seg = data.annToMask(annotation)
+ segmentation.append(seg)
+ if len(segmentation) == 0:
+ shutil.copy(image_path, output_path)
+ continue
+
+ assert len(segmentation) > 0
+ boxes = torch.tensor(face_detections[str(image_id)]).round().long().view(-1, 4)
+ detection = [
+ FaceDetection(boxes, target_imsize=(128, 128), fdf128_expand=True)
+ ]
+ im = Image.open(image_path)
+ orig_im_mode = im.mode
+ im = _apply_exif_orientation(im)
+ im = im.convert("RGB")
+ im = torch.from_numpy(np.rollaxis(np.array(im), 2))
+ im = anonymizer.forward(im, detections=detection, **synthesis_kwargs)
+ im = Image.fromarray(utils.im2numpy(im)).convert(orig_im_mode)
+ im.save(output_path, format="JPEG", optimize=False, quality=100, subsampling=0)
+
+
+@click.command()
+@click.argument("config_path")
+def main(config_path):
+
+ target_dir = Path("/mnt/work2/haakohu/datasets/bdd100k_anonymized_2023/")
+ name = {
+ "configs/anonymizers/traditional/face/gaussian.py": "dp2_face_gaussian",
+ "configs/anonymizers/traditional/face/maskout.py": "dp2_face_maskout",
+ "configs/anonymizers/face_fdf128.py": "dp2_face_fdf128",
+ }[config_path]
+ target_dir = target_dir.joinpath(name, "bdd100k", "images", "10k", "train")
+ tops.set_seed(0)
+ tops.set_AMP(False)
+ cfg = utils.load_config(config_path)
+ anonymizer = instantiate(cfg.anonymizer, load_cache=True)
+ synthesis_kwargs = dict(amp=False, multi_modal_truncation=True, truncation_value=0)
+ iteratively_anonymize(
+ target_dir,
+ anonymizer, synthesis_kwargs)
+
+
+main()
diff --git a/project/models/deprecated_deep_privacy2/tools/anonymization/bdd100k/visualize_body.py b/project/models/deprecated_deep_privacy2/tools/anonymization/bdd100k/visualize_body.py
new file mode 100644
index 0000000..7293234
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/tools/anonymization/bdd100k/visualize_body.py
@@ -0,0 +1,65 @@
+from PIL import Image
+import numpy as np
+import torch
+import tqdm
+from detectron2.data.detection_utils import _apply_exif_orientation
+import pathlib
+from dp2.detection.structures import PersonDetection
+from pycocotools.coco import COCO
+from ..cityscapes.anonymize_body import cse_post_process_cfg
+from dp2 import utils
+
+def main():
+ source_directory = pathlib.Path("/mnt/work2/haakohu/datasets/bdd100k")
+ data = COCO(source_directory.joinpath("jsons/ins_seg_train_cocofmt.json"))
+ with open(source_directory.joinpath("annotated_keypoints_train.json"), "r") as fp:
+ import json
+ all_keypoints = json.load(fp)
+ vis_thr = .5
+ for image_id in tqdm.tqdm(data.imgs):
+ image_info = data.loadImgs([image_id])[0]
+
+ image_path = source_directory.joinpath("images", "10k", "train", image_info["file_name"])
+ im = Image.open(image_path)
+
+ im = _apply_exif_orientation(im)
+ im = np.array(im.convert("RGB"))
+ annotation_ids = data.getAnnIds([image_id])
+ annotations = data.loadAnns(annotation_ids)
+ if str(image_id) not in all_keypoints or len(annotations) == 0:
+ continue
+ segmentation = []
+ for annotation in annotations:
+ if annotation["iscrowd"] or annotation["ignore"]:
+ continue
+ if annotation["category_id"] != 1:
+ continue
+ seg = data.annToMask(annotation)
+ segmentation.append(seg)
+ if len(segmentation) == 0:
+ continue
+ assert len(segmentation) > 0
+ segmentation = torch.from_numpy(np.stack(segmentation))
+ keypoints = np.array(all_keypoints[str(image_id)]["keypoints"])
+ keypoints = torch.from_numpy(np.stack(keypoints)).float()
+ keypoints[:, :, 2] = keypoints[:, :, 2] > vis_thr
+
+ detection = PersonDetection(
+ segmentation,
+ **cse_post_process_cfg,
+ orig_imshape_CHW=(3, *im.shape[:2]),
+ keypoints=keypoints
+ )
+ im = torch.from_numpy(np.rollaxis(im, 2))
+ im = detection.visualize(im)
+ im = utils.im2numpy(im)
+ import cv2
+ cv2.imshow("lol", im[:, :, ::-1])
+ key = cv2.waitKey(0)
+ if key == ord("q"):
+ exit()
+
+
+
+
+main()
diff --git a/project/models/deprecated_deep_privacy2/tools/anonymization/cityscapes/annotate_faces.py b/project/models/deprecated_deep_privacy2/tools/anonymization/cityscapes/annotate_faces.py
new file mode 100644
index 0000000..490b27c
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/tools/anonymization/cityscapes/annotate_faces.py
@@ -0,0 +1,88 @@
+import numpy as np
+import cv2
+import tqdm
+import json
+from pathlib import Path
+from face_detection import build_detector
+from face_detection.dsfd import DSFDDetector
+from detectron2.data.detection_utils import _apply_exif_orientation
+from PIL import Image
+from detectron2.data.datasets.cityscapes import load_cityscapes_instances
+from detectron2.structures.masks import polygons_to_bitmask
+from ..coco.annotate_faces import get_matches
+
+def draw_faces(im, bboxes):
+ for bbox in bboxes:
+ x0, y0, x1, y1 = [int(_) for _ in bbox]
+ cv2.rectangle(im, (x0, y0), (x1, y1), (0, 0, 255), 2)
+
+
+def draw_keypoints(im, keypoints):
+ for kp in keypoints:
+ for x0, y0, visible in kp:
+ if visible == 0:
+ continue
+ cv2.circle(im, (x0, y0), 1, color=(0, 255,0), thickness=2)
+
+ddir = Path("/mnt/work2/haakohu/datasets/cityscapes/")
+def iterate_dataset():
+ dataset = load_cityscapes_instances(ddir.joinpath("leftImg8bit/train"), ddir.joinpath("gtFine/train"))
+
+ for sample in tqdm.tqdm(dataset): # dict_keys(['file_name', 'image_id', 'height', 'width', 'annotations'])
+ masks = []
+ for i, instance_annotation in enumerate(sample["annotations"]): # dict_keys(['iscrowd', 'category_id', 'segmentation', 'bbox', 'bbox_mode'])
+ # Detectron2 filters out all instances part of crowd
+ # In keypoint annotation I did not filter out crowd label
+ assert isinstance(instance_annotation["iscrowd"], bool)
+ if instance_annotation["iscrowd"]:
+ continue
+ if int(instance_annotation["category_id"]) != 0:
+ continue
+ mask = polygons_to_bitmask(instance_annotation["segmentation"], height=sample["height"], width=sample["width"])
+ masks.append(mask)
+ if len(masks) == 0:
+ yield sample["file_name"], sample["image_id"], None, None, None
+ continue
+ im = Image.open(sample["file_name"])
+ im = _apply_exif_orientation(im)
+ orig_im_mode = im.mode
+ im = im.convert("RGB")
+ im = np.array(im)
+ masks = np.stack(masks)
+ yield sample["file_name"], sample["image_id"], im, masks, orig_im_mode
+
+def draw_faces(im, bboxes):
+ for bbox in bboxes:
+ x0, y0, x1, y1 = [int(_) for _ in bbox]
+ cv2.rectangle(im, (x0, y0), (x1, y1), (0, 0, 255), 2)
+
+def annotate_cityscapes(detector: DSFDDetector):
+ target_path = ddir.joinpath("face_boxes_train.json")
+ #print(dataset[0]["annotations"][0].keys(())
+ all_results = dict()
+ n_instances = 0
+ n_boxes = 0
+ for file_name, image_id, im, masks, orig_im_mode in iterate_dataset():
+ if im is None:
+ continue
+ boxes = detector.detect(im)
+ n_instances += len(masks)
+ if len(boxes) == 0:
+ continue
+ matches, _ = get_matches(boxes, masks)
+ n_boxes += len(matches)
+ boxes = [boxes[i].tolist() for i, j in matches]
+ all_results[image_id] = boxes
+ print(f"There are {n_instances}, where {n_boxes} are detected with face detector.")
+ with open(target_path, "w") as fp:
+ json.dump(all_results, fp)
+
+
+if __name__ == "__main__":
+ detector = build_detector(
+ clip_boxes=True,
+ confidence_threshold=0.2
+ )
+ annotate_cityscapes(
+ detector,
+ )
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/tools/anonymization/cityscapes/anonymize_body.py b/project/models/deprecated_deep_privacy2/tools/anonymization/cityscapes/anonymize_body.py
new file mode 100644
index 0000000..2f1e437
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/tools/anonymization/cityscapes/anonymize_body.py
@@ -0,0 +1,103 @@
+from .visualize_body import iterate_dataset, cse_post_process_cfg, ddir
+from pathlib import Path
+import numpy as np
+import torch
+import click
+import tops
+from tops.config import instantiate
+from PIL import Image
+from dp2.detection.structures import PersonDetection
+from dp2 import utils
+import shutil
+from detectron2.data.detection_utils import _apply_exif_orientation
+import tqdm
+from dp2.anonymizer.histogram_match_anonymizers import HistogramMatchAnonymizer, LatentHistogramMatchAnonymizer
+
+def iteratively_anonymize(anonymizer, target_directory: Path, synthesis_kwargs, split):
+ target_directory.mkdir(exist_ok=True, parents=True)
+ all_boxes = []
+ n_keypoints_all_zeros = 0
+ n_instances = 0
+ n_filtered = 0
+ for impath, keypoints, masks in tqdm.tqdm(iterate_dataset(split), total=2975 if split == "train" else 500):
+ file_name = "/".join(Path(impath).parts[len(ddir.parts):])
+ output_path = target_directory.joinpath(file_name)
+ output_path.parent.mkdir(exist_ok=True, parents=True)
+ if keypoints is None:
+ shutil.copy(impath, output_path)
+ continue
+ im = Image.open(impath)
+ im = _apply_exif_orientation(im)
+ orig_im_mode = im.mode
+ im = im.convert("RGB")
+ n_instances += keypoints.shape[0]
+ n_keypoints_all_zeros += (keypoints[:, :, -1] < 0.5).all(dim=-1).sum().item()
+ detection = PersonDetection(masks, **cse_post_process_cfg, orig_imshape_CHW=(3, *im.size[::-1]), keypoints=keypoints.float())
+ detection.pre_process()
+ n_filtered += len(keypoints) - len(detection)
+
+ all_boxes.extend(detection.boxes)
+ im = torch.from_numpy(np.rollaxis(np.array(im), 2))
+ im = anonymizer.forward(im, detections=[detection], **synthesis_kwargs)
+ im = Image.fromarray(utils.im2numpy(im)).convert(orig_im_mode)
+ print("Saving to:", output_path)
+ im.save(output_path, optimize=False, quality=100, subsampling=0)
+ area = [((b[2] - b[0])*(b[3] - b[1]))**0.5 for b in all_boxes]
+ widths = [(b[2] - b[0]) for b in all_boxes]
+ heights = [(b[3] - b[1]) for b in all_boxes]
+ print(f"Detected {n_instances}, where {n_keypoints_all_zeros} where not detected by keypoints. In total, {n_keypoints_all_zeros/n_instances*100:.2f}% where not detected with keypoints.")
+ print("Average area:", np.mean(area))
+ print("Average width:", np.mean(widths))
+ print("Average height:", np.mean(heights))
+ print("Percentage over 288x160:", np.mean([a**2 > 288*160 for a in area]))
+ print(f"Detected {n_instances}, where {n_filtered} where filtered by min size. In total, {n_filtered/n_instances*100:.2f}% where filtered out.")
+
+@click.command()
+@click.argument("config_path")
+@click.option("--val", default=False, is_flag=True)
+@click.option("--match-histogram", default=False, is_flag=True)
+@click.option("--sampler", default="MMT", type=click.Choice(["MMT", "SMT", "None"]))
+@click.option("--n-sampling-steps", "-n", default=1, type=int)
+@click.option("--min_size", default=None, type=click.Choice([None, '16', '32']))
+def main(config_path, val: bool, match_histogram, sampler, n_sampling_steps, kp_fix, min_size):
+ cfg = utils.load_config(config_path)
+ target_dir = Path("/mnt/work2/haakohu/datasets/cityscapes_anonymized_2023/")
+ if val:
+ target_dir = target_dir.parent.joinpath("cityscapes_anonymized_val")
+ name = {
+ "configs/anonymizers/traditional/body/gaussian.py": "dp2_body_gaussian",
+ "configs/anonymizers/traditional/body/maskout.py": "dp2_body_maskout",
+ "configs/anonymizers/FB_triagan.py": "dp2_body_triaGAN"
+ }[config_path]
+ if match_histogram:
+ assert name not in ["dp2_body_gaussian", "dp2_body_maskout"]
+ name += "_MH"
+ cfg.anonymizer._target_ = HistogramMatchAnonymizer
+ if n_sampling_steps > 1:
+ cfg.anonymizer._target_ = LatentHistogramMatchAnonymizer
+ if name not in ["dp2_body_gaussian", "dp2_body_maskout"]:
+ name += f"_{sampler}"
+ if n_sampling_steps > 1:
+ name += f"_sample{n_sampling_steps}"
+
+ if min_size is not None:
+ name += f"_minsize{min_size}"
+ cse_post_process_cfg["exp_bbox_filter"]["minimum_area"] = int(min_size)*int(min_size)
+
+ target_dir = target_dir.joinpath(name, "cityscapes")
+
+ tops.set_seed(0)
+ tops.set_AMP(False)
+
+ anonymizer = instantiate(cfg.anonymizer, load_cache=True)
+ synthesis_kwargs = dict(
+ amp=False,
+ multi_modal_truncation=sampler == "MMT",
+ truncation_value=1 if sampler == "None" else 0,)
+ if n_sampling_steps > 1:
+ synthesis_kwargs["n_sampling_steps"] = n_sampling_steps
+ iteratively_anonymize(anonymizer, target_dir, synthesis_kwargs, split="val" if val else "train")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/project/models/deprecated_deep_privacy2/tools/anonymization/cityscapes/anonymize_face.py b/project/models/deprecated_deep_privacy2/tools/anonymization/cityscapes/anonymize_face.py
new file mode 100644
index 0000000..ee88aa4
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/tools/anonymization/cityscapes/anonymize_face.py
@@ -0,0 +1,62 @@
+import shutil
+from PIL import Image
+import numpy as np
+import torch
+import json
+from dp2 import utils
+from dp2.detection.structures import FaceDetection
+import click, pathlib
+from tops.config import instantiate
+import tops
+from .annotate_faces import iterate_dataset, ddir
+
+def iteratively_anonymize(
+ target_directory: pathlib.Path,
+ anonymizer, synthesis_kwargs):
+ target_directory.mkdir(exist_ok=True, parents=True)
+ annotation_path = ddir.joinpath("face_boxes_train.json")
+ with open(annotation_path, "r") as fp:
+ annotation_boxes = json.load(fp)
+ for impath, image_id, im, masks, orig_im_mode in iterate_dataset():
+ file_name = "/".join(pathlib.Path(impath).parts[len(ddir.parts):])
+ output_path = target_directory.joinpath(file_name)
+ output_path.parent.mkdir(exist_ok=True, parents=True)
+ if im is None or image_id not in annotation_boxes:
+ shutil.copy(impath, output_path)
+ continue
+ boxes = torch.tensor(annotation_boxes[image_id]).round().long()
+ if len(boxes) == 0:
+ shutil.copy(impath, output_path)
+ continue
+ boxes = boxes[:, :4]
+ detection = [
+ FaceDetection(boxes, target_imsize=(128, 128), fdf128_expand=True)
+ ]
+ im = torch.from_numpy(np.rollaxis(im, 2))
+ im = anonymizer(im, **synthesis_kwargs, detections=detection)
+ im = utils.im2numpy(im)
+ im = Image.fromarray(im).convert(orig_im_mode)
+ im.save(output_path, optimize=False, quality=100, subsampling=0)
+
+
+@click.command()
+@click.argument("config_path")
+def main(config_path):
+ target_dir = pathlib.Path("/mnt/work2/haakohu/datasets/cityscapes_anonymized_2023/")
+ name = {
+ "configs/anonymizers/face_fdf128.py": "dp2_face_fdf128",
+ "configs/anonymizers/traditional/face/gaussian.py": "dp2_face_gaussian",
+ "configs/anonymizers/traditional/face/maskout.py": "dp2_face_maskout",
+ }[config_path]
+ target_dir = target_dir.joinpath(name, "cityscapes")
+ tops.set_seed(0)
+ tops.set_AMP(False)
+ cfg = utils.load_config(config_path)
+ cfg.detector.score_threshold = .3
+ anonymizer = instantiate(cfg.anonymizer, load_cache=True)
+ synthesis_kwargs = dict(amp=False, multi_modal_truncation=False, truncation_value=0)
+ iteratively_anonymize(
+ target_dir,
+ anonymizer, synthesis_kwargs)
+
+main()
diff --git a/project/models/deprecated_deep_privacy2/tools/anonymization/cityscapes/visualize_body.py b/project/models/deprecated_deep_privacy2/tools/anonymization/cityscapes/visualize_body.py
new file mode 100644
index 0000000..f7a3b6a
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/tools/anonymization/cityscapes/visualize_body.py
@@ -0,0 +1,87 @@
+from pathlib import Path
+import numpy as np
+import torch
+import tqdm
+from detectron2.data.datasets.cityscapes import load_cityscapes_instances
+from PIL import Image
+from detectron2.structures.masks import polygons_to_bitmask
+from dp2.detection.structures import PersonDetection
+from dp2 import utils
+import cv2
+from detectron2.data.detection_utils import _apply_exif_orientation
+
+cse_post_process_cfg = dict(
+ target_imsize=(288, 160),
+ exp_bbox_cfg=dict(percentage_background=0.3, axis_minimum_expansion=.1),
+ exp_bbox_filter=dict(minimum_area=8*8, min_bbox_ratio_inside=0, aspect_ratio_range=[0, 99999]),
+ dilation_percentage=0.02,
+ kp_vis_thr=0.3
+)
+ddir = Path("/mnt/work2/haakohu/datasets/cityscapes/")
+def iterate_dataset(split="train"):
+ dataset = load_cityscapes_instances(ddir.joinpath(f"leftImg8bit/{split}"), ddir.joinpath(f"gtFine/{split}"))
+ vis_thr = 0.3
+ with open(ddir.joinpath(f"annotated_keypoints_{split}.json"), "r") as fp:
+ import json
+ data = json.load(fp)
+ n_instances = 0
+ n_detected_with_keypoints = 0
+ for sample in dataset: # dict_keys(['file_name', 'image_id', 'height', 'width', 'annotations'])
+ keypoints = data[sample["image_id"]]
+ boxes = []
+ masks = []
+ kp_to_keep = []
+ cur_idx = 0
+ for i, instance_annotation in enumerate(sample["annotations"]): # dict_keys(['iscrowd', 'category_id', 'segmentation', 'bbox', 'bbox_mode'])
+ # Detectron2 filters out all instances part of crowd
+ if int(instance_annotation["category_id"]) != 0:
+ continue
+
+ # In keypoint annotation I did not filter out crowd label
+ assert isinstance(instance_annotation["iscrowd"], bool)
+ if instance_annotation["iscrowd"]:
+ cur_idx += 1
+ continue
+ n_instances += 1
+ kp_to_keep.append(cur_idx)
+ bbox_XYXY = instance_annotation["bbox"]
+ mask = polygons_to_bitmask(instance_annotation["segmentation"], height=sample["height"], width=sample["width"])
+ masks.append(mask)
+ boxes.append(bbox_XYXY)
+ cur_idx += 1
+
+ if len(boxes) == 0:
+ yield sample["file_name"], None, None
+ continue
+
+ keypoints = [keypoints[i] for i in kp_to_keep]
+ n_detected_with_keypoints += len(keypoints)
+ boxes = torch.from_numpy(np.stack(boxes))
+ masks = torch.from_numpy(np.stack(masks))
+ keypoints = torch.from_numpy(np.stack(keypoints))
+ keypoints[:, :, -1] = keypoints[:, :, -1] >= vis_thr
+
+ yield sample["file_name"], keypoints, masks
+ print(f"There are {n_instances} where {n_detected_with_keypoints} are detected with keypoints")
+
+
+def main():
+ #print(dataset[0]["annotations"][0].keys(())
+ for file_name, keypoints, masks in iterate_dataset():
+ continue
+ if keypoints is None:
+ continue
+ im = Image.open(file_name)
+ im = _apply_exif_orientation(im)
+ im = im.convert("RGB")
+ detection = PersonDetection(masks, **cse_post_process_cfg, orig_imshape_CHW=(3, *im.size[::-1]), keypoints=keypoints)
+ im = torch.from_numpy(np.rollaxis(np.array(im), 2))
+ im = detection.visualize(im)
+ im = utils.im2numpy(im)
+ cv2.imshow("test", im[:, :, ::-1])
+ key = cv2.waitKey(0)
+ if key == ord("q"):
+ exit()
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/tools/anonymization/cityscapes/visualize_faces.py b/project/models/deprecated_deep_privacy2/tools/anonymization/cityscapes/visualize_faces.py
new file mode 100644
index 0000000..10ce9a8
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/tools/anonymization/cityscapes/visualize_faces.py
@@ -0,0 +1,26 @@
+import numpy as np
+import cv2
+import json
+from detectron2.data.datasets.cityscapes import load_cityscapes_instances
+from .annotate_faces import iterate_dataset, ddir
+def draw_faces(im, bboxes):
+ for bbox in bboxes:
+ x0, y0, x1, y1 = [int(_) for _ in bbox]
+ cv2.rectangle(im, (x0, y0), (x1, y1), (0, 0, 255), 2)
+
+if __name__ == "__main__":
+ target_path = ddir.joinpath("face_boxes_train.json")
+ print(target_path)
+ dataset = load_cityscapes_instances(ddir.joinpath("leftImg8bit/train"), ddir.joinpath("gtFine/train"))
+
+ with open(target_path, "r") as fp:
+ all_results = json.load(fp)
+ for file_name, image_id, im, masks, orig_im_mode in iterate_dataset():
+ if im is None or image_id not in all_results:
+ continue
+ boxes = all_results[image_id]
+ draw_faces(im, boxes)
+ cv2.imshow("test", im)
+ key = cv2.waitKey(0)
+ if key == ord("q"):
+ exit()
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/tools/anonymization/coco/annotate_faces.py b/project/models/deprecated_deep_privacy2/tools/anonymization/coco/annotate_faces.py
new file mode 100644
index 0000000..17396fb
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/tools/anonymization/coco/annotate_faces.py
@@ -0,0 +1,134 @@
+import numpy as np
+import cv2
+import tqdm
+import json
+from pathlib import Path
+from face_detection import build_detector
+from pycocotools.coco import COCO
+
+
+def draw_faces(im, bboxes):
+ for bbox in bboxes:
+ x0, y0, x1, y1 = [int(_) for _ in bbox]
+ cv2.rectangle(im, (x0, y0), (x1, y1), (0, 0, 255), 2)
+
+
+def boxes2masks(boxes, shape):
+ segmentation = np.zeros((len(boxes), *shape), dtype=bool)
+ for i, box in enumerate(boxes):
+ x0, y0, x1, y1 = [int(x) for x in box[:4]]
+ segmentation[i, y0:y1, x0:x1] = 1
+ return segmentation
+
+
+def calculate_IoU(boxes, masks):
+ boxes = boxes2masks(boxes, masks.shape[1:])
+ masks = masks >= .5
+ IoU = np.zeros((len(boxes), len(masks)), dtype=float)
+ for i in range(len(boxes)):
+ inter = np.logical_and(boxes[i:i+1], masks).reshape(masks.shape[0], -1).sum(axis=1)
+ union = np.logical_or(boxes[i:i+1], masks).reshape(masks.shape[0], -1).sum(axis=1)
+ IoU[i] = inter / (union +1e-7)
+ return IoU
+
+def get_matches(boxes: np.ndarray, masks: np.ndarray, min_iou_thr=0.01):
+ IoU = calculate_IoU(boxes, masks)
+ box_scores = boxes[:, 4]
+ match_box_indices, match_mask_indices = np.where(IoU > min_iou_thr)
+ match_mask_idx_unique, match_mask_idx_num_matches = np.unique(match_mask_indices, return_counts=True)
+ mask_to_num_matches = np.zeros((len(masks)), dtype=int)
+ mask_to_num_matches[match_mask_idx_unique] = match_mask_idx_num_matches
+ # Sort by
+ match_indices = list(range(len(match_mask_indices)))
+ def sort_key(match_idx):
+ box_idx = match_box_indices[match_idx]
+ mask_idx = match_mask_indices[match_idx]
+ match_IoU = IoU[box_idx, mask_idx]
+ num_matches = mask_to_num_matches[mask_idx]
+ box_score = box_scores[box_idx]
+ return (-match_IoU, -box_score, num_matches)
+ match_indices.sort(key=sort_key)
+ taken_box = np.zeros(((len(boxes))), dtype=bool)
+ taken_mask = np.zeros((len(masks)), dtype=bool)
+ final_matches = []
+ for match_idx in match_indices:
+ box_idx = match_box_indices[match_idx]
+ mask_idx = match_mask_indices[match_idx]
+ if taken_box[box_idx] or taken_mask[mask_idx]:
+ continue
+ taken_box[box_idx] = True
+ taken_mask[mask_idx] = True
+ final_matches.append((box_idx, mask_idx))
+
+ # Get filtered boxes
+ final_boxes = [i for i,j in final_matches]
+ match_box_indices_, match_mask_indices_ = np.where(np.logical_and(IoU > 1e-7, IoU <= min_iou_thr))
+ filtered_boxes_by_IoU_thr = [bidx for bidx, midx in zip(match_box_indices_, match_mask_indices_) if bidx not in match_box_indices and bidx not in final_boxes and not taken_mask[midx]]
+ return final_matches, filtered_boxes_by_IoU_thr
+
+
+def annotate_coco(coco_path: Path):
+ data = COCO(coco_path.joinpath("annotations", "person_keypoints_train2017.json"))
+
+ with open(coco_path.joinpath("initial_detected_boxes_train2017.json"), "r") as fp:
+ face_detections = json.load(fp)
+ final_boxes = dict()
+ n_instances = 0
+ n_matched_boxes = 0
+ for image_id in tqdm.tqdm(data.imgs):
+ image_info = data.loadImgs([image_id])[0]
+ image_path = coco_path.joinpath("train2017", image_info["file_name"])
+ annotation_ids = data.getAnnIds([image_id])
+ annotations = data.loadAnns(annotation_ids)
+ if len(annotations) == 0:
+ continue
+ boxes = np.array(face_detections[str(image_id)]).reshape(-1, 5)
+
+ segmentation = []
+ keypoints = []
+ for annotation in annotations:
+ kp = np.array(annotation["keypoints"]).reshape(17, 3)
+ if (kp[:, 2] == 0).all():
+ continue
+ seg = data.annToMask(annotation)
+ segmentation.append(seg)
+ keypoints.append(kp)
+ n_instances += len(keypoints)
+ if len(keypoints) == 0:
+ continue
+ if len(boxes) == 0:
+ continue
+ segmentation = np.stack(segmentation)
+ matches, filtered_boxes_by_IoU_thr = get_matches(boxes, segmentation)
+ final_boxes_ = [boxes[i, :4].tolist() for i, j in matches]
+ keypoint_indices = [int(j) for i,j in matches]
+ final_boxes[str(image_id)] = dict(boxes=final_boxes_, keypoint_indices=keypoint_indices)
+ n_matched_boxes += len(final_boxes_)
+ if len(filtered_boxes_by_IoU_thr) > 0:
+ image_info = data.loadImgs([image_id])[0]
+ image_path = coco_path.joinpath("train2017", image_info["file_name"])
+ im = cv2.imread(str(image_path))
+ boxes = [boxes[i, :4] for i in filtered_boxes_by_IoU_thr]
+ draw_faces(im, boxes)
+ out_dir = Path(f"tools/anonymization/coco/filtered_by_IOU/{image_path.name}")
+ out_dir.parent.mkdir(exist_ok=True, parents=True)
+ print("SAved to", out_dir)
+ mask = segmentation.any(axis=0)[:, :, None]
+ im = (im*.7 + 0.3*mask*255).astype(np.uint8)
+ cv2.imwrite(str(out_dir), im)
+ #cv2.imshow("frame", im)
+ #key = cv2.waitKey(0)
+ print(f"Out of {n_instances} instances, {n_matched_boxes} are matched to a segmentation.")
+
+ target_path = coco_path.joinpath("boxes_train2017.json")
+ with open(target_path, "w") as fp:
+ json.dump(final_boxes, fp)
+
+
+if __name__ == "__main__":
+ detector = build_detector(
+ clip_boxes=True,
+ confidence_threshold=0.3
+ )
+ coco_path = Path("/mnt/work2/haakohu/datasets/coco/")
+ annotate_coco(coco_path)
diff --git a/project/models/deprecated_deep_privacy2/tools/anonymization/coco/anonymize_body.py b/project/models/deprecated_deep_privacy2/tools/anonymization/coco/anonymize_body.py
new file mode 100644
index 0000000..b02e70e
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/tools/anonymization/coco/anonymize_body.py
@@ -0,0 +1,110 @@
+import shutil
+from PIL import Image
+import numpy as np
+import torch
+import tqdm
+from dp2 import utils
+from detectron2.data.detection_utils import _apply_exif_orientation
+from dp2.detection.structures import PersonDetection
+import click, pathlib
+from tops.config import instantiate
+import tops
+from pycocotools.coco import COCO
+from dp2.anonymizer.histogram_match_anonymizers import HistogramMatchAnonymizer, LatentHistogramMatchAnonymizer
+
+
+def iteratively_anonymize(
+ source_directory: pathlib.Path,
+ target_directory: pathlib.Path,
+ anonymizer, synthesis_kwargs):
+ target_directory.mkdir(exist_ok=True, parents=True)
+ data = COCO(source_directory.joinpath("annotations", "person_keypoints_train2017.json"))
+ vis_thr = .3
+ for image_id in tqdm.tqdm(data.imgs):
+ image_info = data.loadImgs([image_id])[0]
+ image_path = source_directory.joinpath("train2017", image_info["file_name"])
+
+ im = Image.open(image_path)
+ im = _apply_exif_orientation(im)
+ orig_im_mode = im.mode
+ im = im.convert("RGB")
+ annotation_ids = data.getAnnIds([image_id])
+ annotations = data.loadAnns(annotation_ids)
+ segmentation = []
+ keypoints = []
+ output_path = target_directory.joinpath(image_path.name)
+ for annotation in annotations:
+ kp = np.array(annotation["keypoints"]).reshape(17, 3)
+ if (kp[:, 2] == 0).all():
+ continue
+ seg = data.annToMask(annotation)
+ segmentation.append(seg)
+ keypoints.append(kp)
+ if len(keypoints) == 0:
+ shutil.copy(image_path, output_path)
+ continue
+ print(output_path)
+ segmentation = torch.from_numpy(np.stack(segmentation))
+ keypoints = torch.from_numpy(np.stack(keypoints)).float()
+ keypoints[:,:, 2] = keypoints[:, :, 2] >= vis_thr
+ cse_post_process_cfg = dict(
+ target_imsize=(288, 160),
+ exp_bbox_cfg=dict(percentage_background=0.3, axis_minimum_expansion=.1),
+ exp_bbox_filter=dict(minimum_area=8*8, min_bbox_ratio_inside=0, aspect_ratio_range=[0, 99999]),
+ dilation_percentage=0.02,
+ kp_vis_thr=0.3
+ )
+ detection = PersonDetection(
+ segmentation,
+ **cse_post_process_cfg,
+ orig_imshape_CHW=(3, *im.size[::-1]),
+ keypoints=keypoints
+ )
+ im = torch.from_numpy(np.rollaxis(np.array(im), 2))
+ im = anonymizer.forward(im, detections=[detection], **synthesis_kwargs)
+ im = Image.fromarray(utils.im2numpy(im)).convert(orig_im_mode)
+
+ im.save(output_path, format="JPEG", optimize=False, quality=100, subsampling=0)
+
+@click.command()
+@click.argument("config_path")
+@click.option("--match-histogram", default=False, is_flag=True)
+@click.option("--sampler", default="MMT", type=click.Choice(["MMT", "SMT", "None"]))
+@click.option("--n-sampling-steps", "-n", default=1, type=int)
+def main(config_path, match_histogram: bool, n_sampling_steps: int, sampler: str, kp_fix: bool,):
+ cfg = utils.load_config(config_path)
+ source_directory = pathlib.Path("/mnt/work2/haakohu/datasets/coco/")
+ target_dir = pathlib.Path("/mnt/work2/haakohu/datasets/coco_anonymized_2023/")
+ name = {
+ "configs/anonymizers/traditional/body/gaussian.py": "dp2_body_gaussian",
+ "configs/anonymizers/traditional/body/maskout.py": "dp2_body_maskout",
+ "configs/anonymizers/FB_triagan.py": "dp2_body_triaGAN"
+ }[config_path]
+ if match_histogram:
+ assert name not in ["dp2_body_gaussian", "dp2_body_maskout"]
+ name += "_MH"
+ cfg.anonymizer._target_ = HistogramMatchAnonymizer
+ if n_sampling_steps > 1:
+ cfg.anonymizer._target_ = LatentHistogramMatchAnonymizer
+
+ if name not in ["dp2_body_gaussian", "dp2_body_maskout"]:
+ name += f"_{sampler}"
+ if n_sampling_steps > 1:
+ name += f"_sample{n_sampling_steps}"
+ target_dir = target_dir.joinpath(name, "coco", "train2017")
+ tops.set_seed(0)
+ tops.set_AMP(False)
+
+ anonymizer = instantiate(cfg.anonymizer, load_cache=True)
+ synthesis_kwargs = dict(
+ amp=False,
+ multi_modal_truncation=sampler == "MMT",
+ truncation_value=1 if sampler == "None" else 0)
+ if n_sampling_steps > 1:
+ synthesis_kwargs["n_sampling_steps"] = n_sampling_steps
+
+ iteratively_anonymize(
+ source_directory, target_dir,
+ anonymizer, synthesis_kwargs)
+
+main()
diff --git a/project/models/deprecated_deep_privacy2/tools/anonymization/coco/anonymize_faces.py b/project/models/deprecated_deep_privacy2/tools/anonymization/coco/anonymize_faces.py
new file mode 100644
index 0000000..da2e437
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/tools/anonymization/coco/anonymize_faces.py
@@ -0,0 +1,83 @@
+import shutil
+from PIL import Image
+import numpy as np
+import torch
+import json
+import tqdm
+from dp2 import utils
+from detectron2.data.detection_utils import _apply_exif_orientation
+from dp2.detection.structures import FaceDetection
+import click, pathlib
+from tops.config import instantiate
+import tops
+from pycocotools.coco import COCO
+
+def iteratively_anonymize(
+ anonymizer,
+ target_directory: pathlib.Path,
+ synthesis_kwargs):
+ target_directory.mkdir(exist_ok=True, parents=True)
+ coco_path = pathlib.Path("/mnt/work2/haakohu/datasets/coco/")
+ data = COCO(coco_path.joinpath("annotations", "person_keypoints_train2017.json"))
+
+ with open(coco_path.joinpath("boxes_train2017.json"), "r") as fp:
+ face_detections = json.load(fp)
+ for image_id in tqdm.tqdm(data.imgs):
+ image_info = data.loadImgs([image_id])[0]
+ image_path = coco_path.joinpath("train2017", image_info["file_name"])
+ output_path = target_directory.joinpath(image_path.name)
+ if str(image_id) not in face_detections:
+ shutil.copy(image_path, output_path)
+ continue
+ detections = face_detections[str(image_id)]
+ boxes = torch.tensor(detections["boxes"]).round().long().view(-1, 4)
+ if len(boxes) == 0:
+ shutil.copy(image_path, output_path)
+ continue
+ annotation_ids = data.getAnnIds([image_id])
+ annotations = data.loadAnns(annotation_ids)
+ keypoints = []
+ for annotation in annotations:
+ kp = np.array(annotation["keypoints"]).reshape(17, 3)
+ if (kp[:, 2] == 0).all():
+ continue
+ keypoints.append(kp)
+ keypoints = torch.from_numpy(np.stack(keypoints)).float()
+ keypoints = keypoints[detections["keypoint_indices"]]
+ keypoints[:,:, 2] = keypoints[:, :, 2] > .5
+ keypoints = keypoints[:, :, :2]
+ assert len(keypoints) == len(boxes), (len(boxes), len(keypoints))
+ im = Image.open(image_path)
+ im = _apply_exif_orientation(im)
+ orig_im_mode = im.mode
+ im = im.convert("RGB")
+ im = np.array(im)
+ detection = [
+ FaceDetection(boxes, target_imsize=(128, 128), fdf128_expand=True, keypoints=keypoints)
+ ]
+ im = torch.from_numpy(np.rollaxis(im, 2))
+ im = anonymizer(im, **synthesis_kwargs, detections=detection)
+ im = utils.im2numpy(im)
+ im = Image.fromarray(im).convert(orig_im_mode)
+ im.save(output_path, format="JPEG", optimize=False, quality=100, subsampling=0)
+
+
+@click.command()
+@click.argument("config_path")
+def main(config_path):
+ target_dir = pathlib.Path("/mnt/work2/haakohu/datasets/coco_anonymized_2023/")
+ name = {
+ "configs/anonymizers/face_fdf128.py": "dp2_face_fdf128",
+ "configs/anonymizers/deep_privacy1.py": "dp2_face_deep_privacy1",
+ "configs/anonymizers/traditional/face/gaussian.py": "dp2_face_gaussian",
+ "configs/anonymizers/traditional/face/maskout.py": "dp2_face_maskout",
+ }[config_path]
+ target_dir = target_dir.joinpath(name, "coco", "train2017")
+ tops.set_seed(0)
+ tops.set_AMP(False)
+ cfg = utils.load_config(config_path)
+ anonymizer = instantiate(cfg.anonymizer, load_cache=True)
+ synthesis_kwargs = dict(amp=False, multi_modal_truncation=False, truncation_value=0)
+ iteratively_anonymize(anonymizer, target_dir, synthesis_kwargs)
+
+main()
diff --git a/project/models/deprecated_deep_privacy2/tools/anonymization/coco/detect_faces.py b/project/models/deprecated_deep_privacy2/tools/anonymization/coco/detect_faces.py
new file mode 100644
index 0000000..88c2cd4
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/tools/anonymization/coco/detect_faces.py
@@ -0,0 +1,42 @@
+import numpy as np
+import tqdm
+import json
+from pathlib import Path
+from face_detection import build_detector
+from face_detection.dsfd import DSFDDetector
+import tops
+from detectron2.data.detection_utils import _apply_exif_orientation
+from PIL import Image
+from pycocotools.coco import COCO
+
+def annotate_coco(coco_path: Path, detector: DSFDDetector, target_path: Path):
+ face_detection = dict()
+ data = COCO(coco_path.joinpath("annotations", "person_keypoints_train2017.json"))
+ for image_id in tqdm.tqdm(data.imgs):
+ image_info = data.loadImgs([image_id])[0]
+ annotation_ids = data.getAnnIds([image_id])
+ annotations = data.loadAnns(annotation_ids)
+ if len(annotations) == 0:
+ continue
+ image_path = coco_path.joinpath("train2017", image_info["file_name"])
+ im = Image.open(image_path)
+
+ im = _apply_exif_orientation(im)
+ im = im.convert("RGB")
+ im = np.array(im)
+ boxes = detector.detect(im).tolist()
+ face_detection[image_id] = boxes
+ with open(target_path, "w") as fp:
+ json.dump(face_detection, fp)
+
+if __name__ == "__main__":
+ detector = build_detector(
+ clip_boxes=True,
+ confidence_threshold=0.3
+ )
+ coco_path = Path("/mnt/work2/haakohu/datasets/coco/")
+ annotate_coco(
+ coco_path,
+ detector,
+ coco_path.joinpath("initial_detected_boxes_train2017.json")
+ )
diff --git a/project/models/deprecated_deep_privacy2/tools/anonymization/coco/refine_faces.py b/project/models/deprecated_deep_privacy2/tools/anonymization/coco/refine_faces.py
new file mode 100644
index 0000000..8947cea
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/tools/anonymization/coco/refine_faces.py
@@ -0,0 +1,74 @@
+import shutil
+from PIL import Image
+import numpy as np
+import torch
+import json
+import tqdm
+from dp2 import utils
+from detectron2.data.detection_utils import _apply_exif_orientation
+from dp2.detection.structures import FaceDetection
+import pathlib
+from tops.config import instantiate
+import tops
+from pycocotools.coco import COCO
+from dp2.detection.box_utils_fdf import expand_bbox
+def iteratively_anonymize(
+ anonymizer,
+ target_directory: pathlib.Path,
+ synthesis_kwargs):
+ criteria = 128*128
+ target_directory.mkdir(exist_ok=True, parents=True)
+ coco_path = pathlib.Path("/mnt/work2/haakohu/datasets/coco/")
+ data = COCO(coco_path.joinpath("annotations", "person_keypoints_train2017.json"))
+ image_dir = pathlib.Path("/mnt/work2/haakohu/datasets/coco_anonymized_2023/dp2_face_fdf128/coco/train2017")
+ with open(coco_path.joinpath("boxes_train2017.json"), "r") as fp:
+ face_detections = json.load(fp)
+ num_boxes_total = 0
+ for image_id in tqdm.tqdm(data.imgs):
+ image_info = data.loadImgs([image_id])[0]
+ image_path = image_dir.joinpath(image_info["file_name"])
+ output_path = target_directory.joinpath(image_path.name)
+ if str(image_id) not in face_detections:
+ shutil.copy(image_path, output_path)
+ continue
+ boxes = torch.tensor(face_detections[str(image_id)]["boxes"]).round().long().view(-1, 4)
+ if len(boxes) == 0:
+ shutil.copy(image_path, output_path)
+ continue
+ im = Image.open(image_path)
+ im = _apply_exif_orientation(im)
+ orig_im_mode = im.mode
+ im = im.convert("RGB")
+ im = np.array(im)
+ expanded_boxes_old = np.stack([expand_bbox(box, im.shape[-2:], False) for box in boxes.numpy()])
+ area = (expanded_boxes_old[:, 2] - expanded_boxes_old[:, 0]) * (expanded_boxes_old[:, 3] - expanded_boxes_old[:, 1])
+ boxes = boxes[area >= criteria]
+
+ output_path.parent.mkdir(exist_ok=True, parents=True)
+ if len(boxes) == 0:
+ shutil.copy(image_path, output_path)
+ continue
+ num_boxes_total += boxes.shape[0]
+ detection = [
+ FaceDetection(boxes, target_imsize=(256, 256), fdf128_expand=False)
+ ]
+ im = torch.from_numpy(np.rollaxis(im, 2))
+ im = anonymizer(im, **synthesis_kwargs, detections=detection)
+ im = utils.im2numpy(im)
+ im = Image.fromarray(im).convert(orig_im_mode)
+ im.save(output_path, format="JPEG", optimize=False, quality=100, subsampling=0)
+ print("Total number of boxes larger than 128x128:", num_boxes_total)
+
+def main():
+ config_path = "configs/anonymizers/face.py"
+ name = "dp2_face_fdf128_plus256_refine"
+ target_dir = pathlib.Path("/mnt/work2/haakohu/datasets/coco_anonymized_2023/")
+ target_dir = target_dir.joinpath(name, "coco", "train2017")
+ tops.set_seed(0)
+ tops.set_AMP(False)
+ cfg = utils.load_config(config_path)
+ anonymizer = instantiate(cfg.anonymizer, load_cache=True)
+ synthesis_kwargs = dict(amp=False, multi_modal_truncation=False, truncation_value=0, n_sampling_steps=1)
+ iteratively_anonymize(anonymizer, target_dir, synthesis_kwargs)
+
+main()
diff --git a/project/models/deprecated_deep_privacy2/tools/compute_cluster_means.py b/project/models/deprecated_deep_privacy2/tools/compute_cluster_means.py
new file mode 100644
index 0000000..1199b44
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/tools/compute_cluster_means.py
@@ -0,0 +1,47 @@
+# Compute k-means cluster for W (Self-Distilled StyleGAN: Towards Generation from Internet Photos)
+# pip install fast-pytorch-kmeans
+import click
+import tqdm
+import torch
+from dp2.utils import load_config
+from dp2.infer import build_trained_generator
+import tops
+from tops.checkpointer.checkpointer import get_ckpt_paths, load_checkpoint
+from fast_pytorch_kmeans import KMeans
+
+
+@click.command()
+@click.argument("config_path")
+@click.option("-n", "--n_samples", default=int(600e3), type=int)
+@click.option( "--n_centers", "--nc", default=512, type=int)
+@click.option( "--batch_size", default=512, type=int)
+def compute_cluster_means(config_path, n_samples, n_centers, batch_size):
+ cfg = load_config(config_path)
+ G = build_trained_generator(cfg, map_location=torch.device("cpu"))
+ n_batches = n_samples // batch_size
+ n_samples = n_samples // batch_size * batch_size
+ print("Computing clusters over", n_samples, "samples.")
+ style_net = G.stylenet if hasattr(G, "stylenet") else G.style_net
+ style_net = tops.to_cuda(style_net)
+ w_dim = style_net.w_dim
+ z_dim = style_net.z_dim
+ with torch.inference_mode():
+ w = torch.zeros((n_samples, w_dim), device=tops.get_device(), dtype=torch.float32)
+
+ for i in tqdm.trange(n_batches):
+ w[i*batch_size:(i+1)*batch_size] = style_net(torch.randn((batch_size, z_dim), device=tops.get_device())).cpu()
+ kmeans = KMeans(n_clusters=n_centers, mode='euclidean', verbose=10, max_iter=1000, tol=0.00001)
+
+ kmeans.fit_predict(w)
+ centers = kmeans.centroids
+
+ if hasattr(style_net, "w_centers"):
+ del style_net.w_centers
+ style_net.register_buffer("w_centers", centers)
+ ckpt_path = get_ckpt_paths(cfg.checkpoint_dir)[-1]
+ ckpt = load_checkpoint(ckpt_path, map_location="cpu")
+ ckpt["EMA_generator"] = G.state_dict()
+ torch.save(ckpt, ckpt_path)
+
+compute_cluster_means()
+
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/tools/dataset/copy_fdh_remove_embedding.py b/project/models/deprecated_deep_privacy2/tools/dataset/copy_fdh_remove_embedding.py
new file mode 100644
index 0000000..2063dc3
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/tools/dataset/copy_fdh_remove_embedding.py
@@ -0,0 +1,73 @@
+from pathlib import Path
+import webdataset as wds
+import numpy as np
+import tqdm
+import io
+from PIL import Image # This fixes a bug in webdataset writer...
+
+
+def png_decoder(x):
+ with Image.open(io.BytesIO(x)) as im:
+ return np.array(im)
+
+
+def kp_decoder(x):
+ # Keypoints are between [0, 1] for webdataset
+ keypoints = np.load(io.BytesIO(x))
+ return keypoints
+
+
+def process_dataset(source_path: Path, target_path: Path):
+ decoder = [
+ wds.handle_extension("image.png", png_decoder),
+ wds.handle_extension("mask.png", png_decoder),
+ wds.handle_extension("maskrcnn_mask.png", png_decoder),
+ wds.handle_extension("keypoints.npy", kp_decoder),
+ ]
+ pipeline = [
+ wds.SimpleShardList(str(source_path)),
+ wds.tarfile_to_samples(),
+ wds.decode(*decoder),
+ ]
+ pipeline = wds.DataPipeline(*pipeline)
+
+ # max size is number of bytes
+ target_path.mkdir(exist_ok=True, parents=True)
+
+ writer = wds.ShardWriter(str(target_path.joinpath("out-%06d.tar")), maxsize=200*1024*1024, maxcount=3000) # maxsize 200MB
+
+ for sample in tqdm.tqdm(pipeline):
+ keypoints = sample["keypoints.npy"].astype(np.float32)
+ im = sample["image.png"]
+ keypoints[:, 0] /= im.shape[1]
+ keypoints[:, 1] /= im.shape[0]
+ writer.write({
+ "__key__": sample["__key__"],
+ "image.png": sample["image.png"],
+ "mask.png": sample["mask.png"],
+ "keypoints.npy": keypoints,
+ "maskrcnn_mask.png": sample["maskrcnn_mask.png"],
+ })
+ writer.close()
+
+
+def main():
+ import os
+ dataset_base_dir = (
+ os.environ["BASE_DATASET_DIR"] if "BASE_DATASET_DIR" in os.environ else "data"
+ )
+ data_dir = Path(dataset_base_dir, "fdh")
+ sources = [
+ data_dir.joinpath("train", "out-{000000..001421}.tar"),
+ data_dir.joinpath("val", "out-{000000..000023}.tar")
+ ]
+ target_path = [
+ data_dir.parent.joinpath("fdh_no_embeddings", "train"),
+ data_dir.parent.joinpath("fdh_no_embeddings", "val")
+ ]
+ for s, t in zip(sources, target_path):
+ process_dataset(s, t)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/project/models/deprecated_deep_privacy2/tools/dataset/create_webdataset_progressive.py b/project/models/deprecated_deep_privacy2/tools/dataset/create_webdataset_progressive.py
new file mode 100644
index 0000000..8f70ac4
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/tools/dataset/create_webdataset_progressive.py
@@ -0,0 +1,107 @@
+from pathlib import Path
+import webdataset as wds
+import numpy as np
+import torch
+import tqdm
+import io
+from PIL import Image # This fixes a bug in webdataset writer...
+from torchvision.transforms.functional import resize
+from torchvision.transforms.functional import InterpolationMode
+
+
+def png_decoder(x):
+ with Image.open(io.BytesIO(x)) as im:
+ return np.array(im)
+
+
+def kp_decoder(x):
+ # Keypoints are between [0, 1] for webdataset
+ keypoints = np.load(io.BytesIO(x))
+ return keypoints
+
+
+def process_dataset(source_path: Path, target_path: Path, imsizes):
+ decoder = [
+ wds.handle_extension("image.png", png_decoder),
+ wds.handle_extension("mask.png", png_decoder),
+ wds.handle_extension("maskrcnn_mask.png", png_decoder),
+ wds.handle_extension("keypoints.npy", kp_decoder),
+ ]
+ pipeline = [
+ wds.SimpleShardList(str(source_path)),
+ wds.tarfile_to_samples(),
+ wds.decode(*decoder),
+ ]
+ pipeline = wds.DataPipeline(*pipeline)
+
+ # max size is number of bytes
+ target_paths = [
+ target_path.joinpath(str(s[0]))
+ for s in imsizes
+ ]
+ for t in target_paths:
+ t.mkdir(exist_ok=True, parents=True)
+
+ writers = [
+ wds.ShardWriter(str(t.joinpath("out-%06d.tar")), maxsize=200*1024*1024, maxcount=3000) # maxsize 200MB
+ for t in target_paths
+ ]
+
+ for sample in tqdm.tqdm(pipeline, total=int(2e6)):
+ keypoints = sample["keypoints.npy"].astype(np.float32)
+ im = sample["image.png"]
+ mask_float = sample["mask.png"][:, :, None].astype(np.uint8)
+ mask = torch.from_numpy(sample["mask.png"])[None, None] > 0
+ assert mask.dtype == torch.bool
+ maskrcnn_mask = torch.from_numpy(sample["maskrcnn_mask.png"])[None, None]
+
+ condition = im * mask_float + ((1 - mask_float) * 127)
+ assert condition.dtype == np.uint8
+ condition = Image.fromarray(condition)
+ im = Image.fromarray(im)
+ for widx, imsize in enumerate(imsizes):
+ im_ = np.array(im.resize(list(imsize)[::-1], resample=Image.BILINEAR))
+ condition_ = np.array(condition.resize(list(imsize)[::-1], resample=Image.BILINEAR))
+ mask_ = (torch.nn.functional.adaptive_max_pool2d(mask.logical_not().float(), output_size=imsize) > 0).logical_not()
+ maskrcnn_mask_ = resize(maskrcnn_mask, imsize, InterpolationMode.NEAREST)
+ assert mask_.dtype == torch.bool
+ assert maskrcnn_mask.dtype == torch.bool
+ to_replace = mask_.squeeze()[:, :, None].repeat(1, 1, 3).cpu().numpy()
+ condition_[to_replace] = np.array(im_)[to_replace]
+ writers[widx].write({
+ "__key__": sample["__key__"],
+ "image.png": im_,
+ "mask.png": np.array(mask_.squeeze()),
+ "keypoints.npy": keypoints,
+ "maskrcnn_mask.png": np.array(maskrcnn_mask_).squeeze(),
+ "condition.png": condition_
+ })
+ for w in writers:
+ w.close()
+
+def main():
+ import os
+ dataset_base_dir = (
+ os.environ["BASE_DATASET_DIR"] if "BASE_DATASET_DIR" in os.environ else "data"
+ )
+ data_dir = Path(dataset_base_dir, "fdh_no_embeddings")
+ sources = [
+ data_dir.joinpath("val", "out-{000000..000010}.tar"),
+ data_dir.joinpath("train", "out-{000000..000612}.tar"),
+ ]
+ target_path = [
+ data_dir.parent.joinpath("fdh_no_embeddings_resampled", "val"),
+ data_dir.parent.joinpath("fdh_no_embeddings_resampled", "train"),
+ ]
+ imsizes = [
+ (18, 10),
+ (36, 20),
+ (72, 40),
+ (144, 80),
+ ]
+ for s, t in zip(sources, target_path):
+ process_dataset(s, t, imsizes)
+
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/tools/dataset/fdf128_create_webdataset.py b/project/models/deprecated_deep_privacy2/tools/dataset/fdf128_create_webdataset.py
new file mode 100644
index 0000000..2696c5e
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/tools/dataset/fdf128_create_webdataset.py
@@ -0,0 +1,84 @@
+from pathlib import Path
+import webdataset as wds
+import numpy as np
+import torch
+import tqdm
+import io
+from PIL import Image # This fixes a bug in webdataset writer...
+from torchvision.transforms.functional import resize
+from torchvision.transforms.functional import InterpolationMode
+from dp2.data.datasets.fdf import FDFDataset
+
+def png_decoder(x):
+ with Image.open(io.BytesIO(x)) as im:
+ return np.array(im)
+
+
+def kp_decoder(x):
+ # Keypoints are between [0, 1] for webdataset
+ keypoints = np.load(io.BytesIO(x))
+ return keypoints
+
+
+def process_dataset(source_path: Path, target_path: Path, imsizes):
+ dataset = FDFDataset(
+ source_path, (128, 128), load_keypoints=True, transform=None
+ )
+ # max size is number of bytes
+ target_paths = [
+ target_path.joinpath(str(s[0]))
+ for s in imsizes
+ ]
+ for t in target_paths:
+ t.mkdir(exist_ok=True, parents=True)
+
+ writers = [
+ wds.ShardWriter(str(t.joinpath("out-%06d.tar")), maxsize=200*1024*1024, maxcount=3000) # maxsize 200MB
+ for t in target_paths
+ ]
+ for i in tqdm.trange(len(dataset)):
+ keypoints = dataset.landmarks[i]
+ im = Image.open(dataset.image_paths[i])
+ bounding_box = np.array(dataset.bounding_boxes[i]).astype(np.float32) / 128
+ for widx, imsize in enumerate(imsizes):
+ if imsize[0] != im.size[0]:
+ im_ = np.array(im.resize(list(imsize)[::-1], resample=Image.BILINEAR))
+ else:
+ im_ = np.array(im)
+ assert bounding_box.shape == (4, ), bounding_box.shape
+ assert keypoints.shape == (7, 2), keypoints.shape
+ writers[widx].write({
+ "__key__": dataset.image_paths[i].stem,
+ "image.png": im_,
+ "keypoints.npy": keypoints,
+ "bounding_box.npy": bounding_box
+ })
+ for w in writers:
+ w.close()
+
+def main():
+ import os
+ dataset_base_dir = (
+ os.environ["BASE_DATASET_DIR"] if "BASE_DATASET_DIR" in os.environ else "data"
+ )
+ data_dir = Path(dataset_base_dir, "fdf")
+ sources = [
+ data_dir.joinpath("val"),
+ data_dir.joinpath("train"),
+ ]
+ target_path = [
+ data_dir.parent.joinpath("fdf_resampled", "val"),
+ data_dir.parent.joinpath("fdf_resampled", "train"),
+ ]
+ imsizes = [
+ (16, 16),
+ (32, 32),
+ (64, 64),
+ (128, 128)
+ ]
+ for s, t in zip(sources, target_path):
+ process_dataset(s, t, imsizes)
+
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/tools/dryrun.py b/project/models/deprecated_deep_privacy2/tools/dryrun.py
new file mode 100644
index 0000000..5392273
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/tools/dryrun.py
@@ -0,0 +1,49 @@
+import click
+import torch
+import tops
+from tops.config import instantiate
+from dp2 import utils
+
+@click.command()
+@click.argument("config_path")
+def run(config_path):
+ cfg = utils.load_config(config_path)
+ utils.print_config(cfg)
+
+ G = tops.to_cuda(instantiate(cfg.generator))
+
+ D = tops.to_cuda(instantiate(cfg.discriminator))
+ cfg.train.batch_size = 2
+ print(G)
+ dl_val = instantiate(cfg.data.val.loader)
+ cfg.train.amp.scaler_D.init_scale = 1
+ scaler = instantiate(cfg.train.amp.scaler_D)
+ loss_fnc = instantiate(cfg.loss_fnc, D=D, G=G)
+ batch = next(iter(dl_val))
+ tops.print_module_summary(G, batch, max_nesting=10)
+# tops.print_module_summary(D, batch, max_nesting=10)
+
+ print("G PARAMS:", tops.num_parameters(G) / 10 ** 6)
+ print("D PARAMS:", tops.num_parameters(D) / 10 ** 6)
+ print(f"Number of trainable parameters in D: {sum(p.numel() for p in D.parameters() if p.requires_grad)/10**6}M")
+ print(f"Number of trainable parameters in G: {sum(p.numel() for p in G.parameters() if p.requires_grad)/10**6}M" )
+
+ with torch.cuda.amp.autocast(True):
+ o_G = G(**batch)
+ o_D = D(**batch)
+ print("FORWARD OK")
+ D_loss, to_log = loss_fnc.D_loss(batch, grad_scaler=scaler)
+ D_loss.backward()
+ assert all([p.grad is not None or not p.requires_grad for p in D.parameters()])
+ print(to_log)
+
+ G_loss, _ = loss_fnc.G_loss(batch, grad_scaler=scaler)
+ G_loss.backward()
+ G: torch.nn.Module = G
+ for name, p in G.named_parameters():
+ if p.grad is None and p.requires_grad:
+ print(name)
+ assert all([p.grad is not None or not p.requires_grad for p in G.parameters()])
+
+if __name__ == "__main__":
+ run()
diff --git a/project/models/deprecated_deep_privacy2/tools/inspect_dataset.py b/project/models/deprecated_deep_privacy2/tools/inspect_dataset.py
new file mode 100644
index 0000000..14a19d8
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/tools/inspect_dataset.py
@@ -0,0 +1,52 @@
+import cv2
+import torch
+import click
+import tops
+from tops.config import LazyConfig, instantiate
+from dp2 import utils
+from dp2.utils import vis_utils
+import numpy as np
+from PIL import Image
+
+def get_image(batch, cfg, fscale_vis):
+ im0 = batch["condition"]
+ im1 = batch["img"]
+ im = utils.denormalize_img(torch.cat((im0, im1), dim=-1)).mul(255).byte()
+ im = torch.cat((im, vis_utils.visualize_batch(**batch)), dim=-1)
+
+ im = utils.im2numpy(im)
+
+ im = tops.np_make_image_grid(im, nrow=len(im0))
+ if fscale_vis != 1:
+ new_shape = [int(_*fscale_vis) for _ in im.shape[:2][::-1]]
+ im = np.array(Image.fromarray(im).resize(new_shape))
+ return im
+
+
+@click.command()
+@click.argument("config_path")
+@click.option("--train", default=False, is_flag=True)
+@click.option("-n", "--num_images", default=8, type=int)
+@click.option("-f", "--fscale_vis", default=1)
+def main(config_path: str, train: bool, num_images: int, fscale_vis):
+ cfg = LazyConfig.load(config_path)
+ if train:
+ dl_cfg = cfg.data.train.loader
+ else:
+ dl_cfg = cfg.data.val.loader
+ dl_cfg.batch_size = num_images
+ dl = instantiate(dl_cfg)
+ print(dl.image_gpu_transform)
+ dl = iter(dl)
+
+ while True:
+ batch = next(dl)
+ im = get_image(batch, cfg, fscale_vis)
+ cv2.imshow("", im[:, :, ::-1])
+ key = cv2.waitKey(0)
+ if key == ord("q"):
+ exit()
+
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/tools/show_examples.py b/project/models/deprecated_deep_privacy2/tools/show_examples.py
new file mode 100644
index 0000000..7af5208
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/tools/show_examples.py
@@ -0,0 +1,86 @@
+import cv2
+import torch
+import numpy as np
+import click
+import tops
+import tqdm
+from tops.config import instantiate
+from PIL import Image
+from dp2 import utils, infer
+from dp2.utils import vis_utils
+from torchvision.transforms.functional import resize
+
+
+@torch.no_grad()
+@torch.cuda.amp.autocast()
+def get_im(dl, G, num_images, num_z, fscale_vis, truncation_value: float, b_idx, multi_modal_truncation, show_lowres: bool):
+ ims = []
+ for im_idx in tqdm.trange(num_images, desc="Sampling images"):
+ batch = next(dl)
+ ims.append(utils.im2numpy(batch["img"], True, True)[0])
+ ims.append(utils.im2numpy(batch["condition"], True, True)[0])
+ ims.append(utils.im2numpy(vis_utils.visualize_batch(**batch))[0])
+ for z_idx in range(num_z):
+ # Sample same Z by setting seed for different images
+ tops.set_seed(b_idx*num_z + z_idx)
+ if multi_modal_truncation and z_idx > 0:
+ fake = G.multi_modal_truncate(**batch, truncation_value=0, w_indices=[z_idx-1])
+ else:
+ fake = G.sample(**batch, truncation_value=truncation_value)
+ if "x_lowres" in fake and show_lowres:
+ for x in fake["x_lowres"]:
+ x = resize(x, fake["img"].shape[-2:])
+ ims.append(utils.im2numpy(x, to_uint8=True, denormalize=True)[0])
+ ims.append(utils.im2numpy(fake["img"], to_uint8=True, denormalize=True)[0])
+ if fscale_vis != 1:
+ new_shape = [int(_*fscale_vis) for _ in ims[0].shape[:2][::-1]]
+ ims = [np.array(Image.fromarray(im).resize(new_shape)) for im in ims]
+ im = tops.np_make_image_grid(ims, nrow=num_images)
+ return im
+
+
+@click.command()
+@click.argument("config_path")
+@click.option("-n", "--num_images", default=8)
+@click.option("--num_z", "--nz", default=8)
+@click.option("-f", "--fscale_vis", default=1, type=float, help="Scale the output image resultion")
+@click.option("-t", "--truncation_value", default=None, type=float)
+@click.option("-l", "--show-lowres", default=False, is_flag=True)
+@click.option("--save", default=False, is_flag=True)
+@click.option("--train", default=False, is_flag=True)
+@click.option("--multi-modal-truncation", "--mt", default=False, is_flag=True)
+def show_samples(
+ config_path: str,
+ save: bool,
+ train: bool,
+ **kwargs):
+ tops.set_seed(1)
+ cfg = utils.load_config(config_path)
+ G = infer.build_trained_generator(cfg)
+ cfg.train.batch_size = 1
+ if train:
+ dl_val = cfg.data.train.loader
+ else:
+ dl_val = cfg.data.val.loader
+ dl_val.num_workers = 1
+ dl_val.shuffle = False
+ dl_val.infinite = False
+ tops.set_seed(1)
+ dl_val = iter(instantiate(dl_val))
+ b_idx = 0
+ im = get_im(dl_val, G, b_idx=b_idx, **kwargs)
+ print("Press 'a' for next image, 'q' to quit.")
+ while True:
+ b_idx += 1
+ cv2.imshow("image", im[:, :, ::-1])
+ if save:
+ cv2.imwrite("test.png", im[:, :, ::-1])
+ print("Saved file to test.png")
+ key = cv2.waitKey(0)
+ if key == ord("q"):
+ break
+ if key == ord("a"):
+ im = get_im(dl_val, G, b_idx=b_idx, **kwargs)
+
+if __name__ == "__main__":
+ show_samples()
\ No newline at end of file
diff --git a/project/models/deprecated_deep_privacy2/tools/triagan/compute_oks.py b/project/models/deprecated_deep_privacy2/tools/triagan/compute_oks.py
new file mode 100644
index 0000000..97d2d01
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/tools/triagan/compute_oks.py
@@ -0,0 +1,114 @@
+from pathlib import Path
+import numpy as np
+import torch
+import tqdm
+import cv2
+import io
+import click
+from PIL import Image # This fixes a bug in webdataset writer...
+from dp2.detection.models.vit_pose.vit_pose import VitPoseModel
+from dp2.infer import build_trained_generator
+from tops.config import instantiate
+from dp2 import utils
+from dp2.detection.utils import masks_to_boxes
+
+
+def computeOks(dt, gt, bbox_area):
+ kpt_oks_sigmas = (
+ np.array(
+ [
+ 0.26,
+ 0.25,
+ 0.25,
+ 0.35,
+ 0.35,
+ 0.79,
+ 0.79,
+ 0.72,
+ 0.72,
+ 0.62,
+ 0.62,
+ 1.07,
+ 1.07,
+ 0.87,
+ 0.87,
+ 0.89,
+ 0.89,
+ ]
+ )
+ / 10.0
+ )
+ sigmas = kpt_oks_sigmas
+ vars = (sigmas * 2) ** 2
+ k = len(sigmas)
+ # compute oks between each detection and ground truth object
+ # create bounds for ignore regions(double the gt bbox)
+ g = gt
+ xg, yg, vg = gt.T
+ # xg = g[0::3]; yg = g[1::3]; vg = g[2::3]
+ k1 = np.count_nonzero(vg > 0)
+ d = dt
+ xd, yd, vd = dt.T
+ if k1 > 0:
+ # measure the per-keypoint distance if keypoints visible
+ dx = xd - xg
+ dy = yd - yg
+ else:
+ # measure minimum distance to keypoints in (x0,y0) & (x1,y1)
+ return None
+ z = np.zeros((k))
+ raise Exception()
+ dx = np.max((z, x0 - xd), axis=0) + np.max((z, xd - x1), axis=0)
+ dy = np.max((z, y0 - yd), axis=0) + np.max((z, yd - y1), axis=0)
+ e = (dx**2 + dy**2) / vars / (bbox_area + np.spacing(1)) / 2
+ e = e[vg > 0]
+ iou = np.sum(np.exp(-e)) / e.shape[0]
+ return iou
+
+
+@click.command()
+@click.argument("config_path")
+@torch.no_grad()
+def main(config_path):
+ pose_model = VitPoseModel("vit_huge")
+ cfg = utils.load_config(config_path)
+ G = build_trained_generator(cfg)
+ cfg.train.batch_size = 1
+ dl = instantiate(cfg.data.val.loader)
+ vis_thr = 0.5 # Same as used for annotating FDH
+ oks = 0
+ n = 0
+ for i, batch in enumerate(tqdm.tqdm(iter(dl), total=30_000)):
+ box = masks_to_boxes((batch["mask"][0] > 0.5).logical_not())
+ keypoints = batch["keypoints"][0].clone()
+ im = batch["img"]
+ with torch.cuda.amp.autocast():
+ fake = G.sample(**batch, truncation_value=0)["img"]
+ keypoints[:, 0] *= im.shape[-1]
+ keypoints[:, 1] *= im.shape[-2]
+ img_uint8 = fake.add(1).div(2).mul(255).round().byte()[0]
+ predicted_keypoints = pose_model(img_uint8, box)[0]
+
+ assert keypoints.shape == predicted_keypoints.shape, (
+ keypoints.shape,
+ predicted_keypoints.shape,
+ )
+ keypoints[:, -1] = keypoints[:, -1] > vis_thr
+ predicted_keypoints[:, -1] = predicted_keypoints[:, -1] > vis_thr
+ assert predicted_keypoints.shape == (17, 3), predicted_keypoints.shape
+ oks_ = computeOks(
+ keypoints.cpu().numpy(),
+ predicted_keypoints.cpu().numpy(),
+ im.shape[-1] * im.shape[-2],
+ )
+ if oks_ is None:
+ continue
+ oks += oks_
+ n += 1
+
+ oks = oks / n
+ print("FINAL OKS:", oks)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/project/models/deprecated_deep_privacy2/tools/triagan/validate_triaGAN.py b/project/models/deprecated_deep_privacy2/tools/triagan/validate_triaGAN.py
new file mode 100644
index 0000000..c7aef98
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/tools/triagan/validate_triaGAN.py
@@ -0,0 +1,81 @@
+import click
+import torch
+import os
+import json
+from dp2.infer import build_trained_generator
+from tops.config import instantiate
+from dp2.utils import load_config
+import tops
+import subprocess
+from dp2.metrics.ppl import calculate_ppl
+from dp2.metrics.fid_clip import compute_fid_clip
+from dp2.metrics.torch_metrics import compute_metrics_iteratively
+
+torch.backends.cuda.matmul.allow_tf32 = True
+torch.backends.cudnn.allow_tf32 = True
+torch.backends.cudnn.benchmark = True
+
+def print_metric(path):
+ with open(path, "r") as fp:
+ all_metrics = json.load(fp)
+ print("="*80)
+ print("="*80)
+ print("="*80)
+ for k, v in all_metrics.items():
+ print(f"{k:40}: {v}")
+ print("="*80)
+ print("="*80)
+ print("="*80)
+
+def validate(
+ config_path,
+ recompute: bool,
+ ):
+ tops.set_seed(0)
+ tops.set_AMP(True)
+ os.environ["CUDA_VISIBLE_DEVICES"] = "0"
+ cfg = load_config(config_path)
+ output_path = cfg.output_dir.joinpath("final_metrics.json")
+ if output_path.is_file():
+ print_metric(output_path)
+ if not recompute:
+ return
+
+ batch_size = 8
+ cfg.train.batch_size = batch_size
+ dl_val = instantiate(cfg.data.val.loader)
+ G = build_trained_generator(cfg)
+ tops.set_seed(0)
+
+ ppl = calculate_ppl(dl_val, G, data_len=30_000, upsample_size=(288, 160))
+ print(ppl)
+ tops.set_seed(0)
+ metrics = compute_metrics_iteratively(dl_val, G, cache_directory=f".final_metrics_cache{cfg.data.imsize[0]}", data_len=30_000)
+ tops.set_seed(0)
+ fid_clip = compute_fid_clip(dl_val, G, cache_directory=f".final_metrics_cache{cfg.data.imsize[0]}", data_len=30_000)
+ commit = str(subprocess.check_output("git rev-parse HEAD", shell=True).decode()).strip()
+ all_metrics = {
+ **ppl, **metrics, **fid_clip,
+ }
+ all_metrics["commit"] = commit
+ for k, v in all_metrics.items():
+ if isinstance(v, torch.Tensor):
+ print(k)
+ all_metrics[k] = float(v.cpu().item())
+
+ with open(output_path, mode="w") as fp:
+ json.dump(all_metrics, fp)
+ print_metric(output_path)
+
+
+
+@click.command()
+@click.argument("config_paths", nargs=-1)
+@click.option("-r", "--recompute", default=False, is_flag=True)
+def main(config_paths, recompute: bool):
+ for cfg_path in config_paths:
+ validate(cfg_path, recompute)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/project/models/deprecated_deep_privacy2/train.py b/project/models/deprecated_deep_privacy2/train.py
new file mode 100644
index 0000000..b75d408
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/train.py
@@ -0,0 +1,190 @@
+import tempfile
+import click
+import tops
+import warnings
+import traceback
+import torch
+import os
+from tops import checkpointer
+from sg3_torch_utils.ops import conv2d_gradfix, grid_sample_gradfix, bias_act, upfirdn2d
+from tops.config import instantiate
+from tops import logger
+from dp2 import utils, infer
+from dp2.gan_trainer import GANTrainer
+
+
+torch.backends.cudnn.benchmark = True
+
+
+def start_train(rank, world_size, debug, cfg_path, temp_dir, benchmark: bool):
+ print(rank, world_size)
+ cfg = utils.load_config(cfg_path)
+ if debug:
+ torch.backends.cudnn.benchmark = False
+ torch.backends.cudnn.deterministic = True
+ torch.set_printoptions(precision=10)
+ else:
+ torch.backends.cuda.matmul.allow_tf32 = True
+ torch.backends.cudnn.allow_tf32 = True
+ conv2d_gradfix.enabled = cfg.train.conv2d_gradfix_enabled
+ grid_sample_gradfix.enabled = cfg.train.grid_sample_gradfix_enabled
+ upfirdn2d.enabled = cfg.train.grid_sample_gradfix_enabled
+ bias_act.enabled = cfg.train.bias_act_plugin_enabled
+ if world_size > 1:
+ init_file = os.path.abspath(os.path.join(temp_dir, ".torch_distributed_init"))
+ init_method = f"file://{init_file}"
+ torch.distributed.init_process_group(
+ "nccl", rank=rank, world_size=world_size, init_method=init_method
+ )
+ # pin memory in dataloader would allocate memory on device:0 for distributed training.
+ torch.cuda.set_device(tops.get_device())
+
+ tops.set_AMP(cfg.train.amp.enabled)
+ utils.init_tops(cfg)
+ if tops.rank() == 0:
+ utils.print_config(cfg)
+ with open(cfg.output_dir.joinpath("config_path.py"), "w") as fp:
+ fp.write(utils.config_to_str(cfg))
+
+ if world_size > 1:
+ assert cfg.train.batch_size > tops.world_size()
+ assert cfg.train.batch_size % tops.world_size() == 0
+ cfg.train.batch_size //= world_size
+ if rank != 0:
+ warnings.filterwarnings("ignore", category=DeprecationWarning)
+ warnings.filterwarnings("ignore", category=UserWarning)
+ tops.set_seed(cfg.train.seed + rank)
+ logger.log("Loading dataset.")
+ dl_val = instantiate(cfg.data.val.loader, channels_last=cfg.train.channels_last)
+ dl_train = instantiate(cfg.data.train.loader, channels_last=cfg.train.channels_last)
+ dl_train = iter(dl_train)
+
+ logger.log("Initializing models.")
+ G = instantiate(cfg.generator)
+ D = tops.to_cuda(instantiate(cfg.discriminator))
+ if tops.rank() == 0:
+ print(G)
+ print(D)
+
+ # TODO: EMA MIGHT NEED TO BE SYNCED ACCROSS GPUs before instantiate
+ G_EMA = utils.EMA(G, cfg.train.batch_size * world_size, **cfg.EMA)
+ G = tops.to_cuda(G)
+ if world_size > 1:
+ logger.log("Syncing models accross GPUs")
+ # Distributed is implemented self. # Buffers are never broadcasted during training.
+ for module in [G_EMA, G, D]:
+ params_and_buffers = list(module.named_parameters())
+ params_and_buffers += list(module.named_buffers())
+ for name, param in params_and_buffers:
+ torch.distributed.broadcast(param, src=0)
+ if cfg.train.compile_D.enabled:
+ compile_kwargs = instantiate(cfg.train.compile_D)
+ compile_kwargs.pop("enabled")
+ D = torch.compile(D, **compile_kwargs)
+ if cfg.train.compile_G.enabled:
+ compile_kwargs = instantiate(cfg.train.compile_G)
+ compile_kwargs.pop("enabled")
+ G = torch.compile(G, **compile_kwargs)
+ logger.log("Initializing optimizers")
+ grad_scaler_D = instantiate(cfg.train.amp.scaler_D)
+ grad_scaler_G = instantiate(cfg.train.amp.scaler_G)
+
+ G_optim = instantiate(cfg.G_optim, params=G.parameters())
+ D_optim = instantiate(cfg.D_optim, params=D.parameters())
+
+ loss_fnc = instantiate(cfg.loss_fnc, D=D, G=G)
+ logger.add_scalar("stats/gpu_batch_size", cfg.train.batch_size)
+ logger.add_scalar("stats/ngpus", world_size)
+
+ D.train()
+ G.train()
+ if hasattr(cfg.train, "discriminator_init_cfg") and not benchmark:
+ cfg_ = utils.load_config(cfg.train.discriminator_init_cfg)
+ ckpt = checkpointer.load_checkpoint(cfg_.checkpoint_dir)["discriminator"]
+ if hasattr(cfg_, "ckpt_mapper_D"):
+ ckpt = instantiate(cfg_.ckpt_mapper_D)(ckpt)
+ D.load_state_dict(ckpt)
+ if hasattr(cfg.train, "generator_init_cfg") and not benchmark:
+ cfg_ = utils.load_config(cfg.train.generator_init_cfg)
+ ckpt = checkpointer.load_checkpoint(cfg_.checkpoint_dir)["EMA_generator"]
+ if hasattr(cfg_, "ckpt_mapper"):
+ ckpt = instantiate(cfg_.ckpt_mapper)(ckpt)
+ infer.load_state_dict(G, ckpt)
+ infer.load_state_dict(G_EMA.generator, ckpt)
+
+ G_EMA.eval()
+ if cfg.train.channels_last:
+ G = G.to(memory_format=torch.channels_last)
+ D = D.to(memory_format=torch.channels_last)
+
+ if tops.world_size() > 1:
+ torch.distributed.barrier()
+
+ trainer = GANTrainer(
+ G=G,
+ D=D,
+ G_EMA=G_EMA,
+ D_optim=D_optim,
+ G_optim=G_optim,
+ dl_train=dl_train,
+ dl_val=dl_val,
+ scaler_D=grad_scaler_D,
+ scaler_G=grad_scaler_G,
+ ims_per_log=cfg.train.ims_per_log,
+ max_images_to_train=cfg.train.max_images_to_train,
+ ims_per_val=cfg.train.ims_per_val,
+ loss_handler=loss_fnc,
+ evaluate_fn=instantiate(cfg.data.train_evaluation_fn),
+ batch_size=cfg.train.batch_size,
+ broadcast_buffers=cfg.train.broadcast_buffers,
+ fp16_ddp_accumulate=cfg.train.fp16_ddp_accumulate,
+ save_state=not benchmark
+ )
+ if benchmark:
+ trainer.estimate_ims_per_hour()
+ if world_size > 1:
+ torch.distributed.barrier()
+ logger.finish()
+ if world_size > 1:
+ torch.distributed.destroy_process_group()
+ return
+
+ try:
+ trainer.train_loop()
+ except Exception as e:
+ traceback.print_exc()
+ exit()
+ tops.set_AMP(False)
+ tops.set_seed(0)
+ metrics = instantiate(cfg.data.evaluation_fn)(generator=G_EMA, dataloader=dl_val)
+ metrics = {f"metrics_final/{k}": v for k, v in metrics.items()}
+ logger.add_dict(metrics, level=logger.logger.INFO)
+ if world_size > 1:
+ torch.distributed.barrier()
+ logger.finish()
+
+ if world_size > 1:
+ torch.distributed.destroy_process_group()
+
+
+@click.command()
+@click.argument("config_path")
+@click.option("--debug", default=False, is_flag=True)
+@click.option("--benchmark", default=False, is_flag=True)
+def main(config_path: str, debug: bool, benchmark: bool):
+ world_size = (
+ torch.cuda.device_count()
+ ) # Manually overriding this does not work. have to set CUDA_VISIBLE_DEVICES environment variable
+ if world_size > 1:
+ torch.multiprocessing.set_start_method("spawn", force=True)
+ with tempfile.TemporaryDirectory() as temp_dir:
+ torch.multiprocessing.spawn(
+ start_train,
+ args=(world_size, debug, config_path, temp_dir, benchmark),
+ nprocs=torch.cuda.device_count(),
+ )
+ else:
+ start_train(0, 1, debug, config_path, None, benchmark)
+
+if __name__ == "__main__":
+ main()
diff --git a/project/models/deprecated_deep_privacy2/validate.py b/project/models/deprecated_deep_privacy2/validate.py
new file mode 100644
index 0000000..b0deff7
--- /dev/null
+++ b/project/models/deprecated_deep_privacy2/validate.py
@@ -0,0 +1,66 @@
+import click
+import torch
+import os
+import tempfile
+from dp2.infer import build_trained_generator
+from tops.config import instantiate
+from dp2.utils import load_config
+import tops
+from tops import logger
+
+
+def validate(
+ rank,
+ config_path,
+ batch_size: int,
+ truncation_value: float,
+ multi_modal_truncate: bool,
+ world_size,
+ temp_dir,
+ ):
+ tops.set_seed(0)
+ tops.set_AMP(False)
+ if world_size > 1:
+ init_file = os.path.abspath(os.path.join(temp_dir, '.torch_distributed_init'))
+ init_method = f'file://{init_file}'
+ torch.distributed.init_process_group(
+ "nccl", rank=rank, world_size=world_size, init_method=init_method)
+ torch.cuda.set_device(tops.get_device()) # pin memory in dataloader would allocate memory on device:0 for distributed training.
+ cfg = load_config(config_path)
+
+ if batch_size is not None:
+ assert cfg.train.batch_size % world_size == 0
+ cfg.train.batch_size = batch_size // world_size
+ dl_val = instantiate(cfg.data.val.loader)
+ G = build_trained_generator(cfg)
+ tops.set_seed(0)
+ tops.set_AMP(False)
+ metrics = instantiate(cfg.data.evaluation_fn)(generator=G, dataloader=dl_val, truncation_value=truncation_value, multi_modal_truncate=multi_modal_truncate)
+ metrics = {f"metrics_final/{k}": v for k,v in metrics.items()}
+ if rank == 0:
+ tops.init(cfg.output_dir)
+ logger.add_dict(metrics)
+ logger.finish()
+
+
+@click.command()
+@click.argument("config_path")
+@click.option("--batch_size", default=16, type=int)
+@click.option("--truncation-value", default=None, type=float)
+@click.option("--multi-modal-truncate", "--mmt", default=False, is_flag=True)
+def main(config_path, batch_size: int, truncation_value: float, multi_modal_truncate: bool):
+ world_size = torch.cuda.device_count()
+ if world_size > 1:
+ torch.multiprocessing.set_start_method("spawn", force=True)
+ with tempfile.TemporaryDirectory() as temp_dir:
+ torch.multiprocessing.spawn(validate,
+ args=(config_path, batch_size, truncation_value, multi_modal_truncate, world_size, temp_dir),
+ nprocs=world_size)
+ else:
+ validate(
+ 0, config_path, batch_size, truncation_value,multi_modal_truncate,
+ world_size=1, temp_dir=None)
+
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/project/models/face_anon_simple/.gitignore b/project/models/deprecated_face_anon_simple/.gitignore
similarity index 100%
rename from project/models/face_anon_simple/.gitignore
rename to project/models/deprecated_face_anon_simple/.gitignore
diff --git a/project/models/face_anon_simple/LICENSE b/project/models/deprecated_face_anon_simple/LICENSE
similarity index 100%
rename from project/models/face_anon_simple/LICENSE
rename to project/models/deprecated_face_anon_simple/LICENSE
diff --git a/project/models/face_anon_simple/README.md b/project/models/deprecated_face_anon_simple/README.md
similarity index 100%
rename from project/models/face_anon_simple/README.md
rename to project/models/deprecated_face_anon_simple/README.md
diff --git a/project/models/deprecated_face_anon_simple/START_OBFUSCATION_SERVER_README.txt b/project/models/deprecated_face_anon_simple/START_OBFUSCATION_SERVER_README.txt
new file mode 100644
index 0000000..c69bf5a
--- /dev/null
+++ b/project/models/deprecated_face_anon_simple/START_OBFUSCATION_SERVER_README.txt
@@ -0,0 +1 @@
+obfuscation_platform_face_anon_simple
\ No newline at end of file
diff --git a/project/models/deprecated_face_anon_simple/anon.png b/project/models/deprecated_face_anon_simple/anon.png
new file mode 100644
index 0000000..8420ced
Binary files /dev/null and b/project/models/deprecated_face_anon_simple/anon.png differ
diff --git a/project/models/face_anon_simple/demo.ipynb b/project/models/deprecated_face_anon_simple/demo.ipynb
similarity index 100%
rename from project/models/face_anon_simple/demo.ipynb
rename to project/models/deprecated_face_anon_simple/demo.ipynb
diff --git a/project/models/face_anon_simple/environment.yml b/project/models/deprecated_face_anon_simple/environment.yml
similarity index 100%
rename from project/models/face_anon_simple/environment.yml
rename to project/models/deprecated_face_anon_simple/environment.yml
diff --git a/project/models/face_anon_simple/examples/referencenet/infer_referencenet.py b/project/models/deprecated_face_anon_simple/examples/referencenet/infer_referencenet.py
similarity index 100%
rename from project/models/face_anon_simple/examples/referencenet/infer_referencenet.py
rename to project/models/deprecated_face_anon_simple/examples/referencenet/infer_referencenet.py
diff --git a/project/models/face_anon_simple/examples/referencenet/train_referencenet.py b/project/models/deprecated_face_anon_simple/examples/referencenet/train_referencenet.py
similarity index 100%
rename from project/models/face_anon_simple/examples/referencenet/train_referencenet.py
rename to project/models/deprecated_face_anon_simple/examples/referencenet/train_referencenet.py
diff --git a/project/models/face_anon_simple/face_obfuscator.py b/project/models/deprecated_face_anon_simple/face_obfuscator.py
similarity index 95%
rename from project/models/face_anon_simple/face_obfuscator.py
rename to project/models/deprecated_face_anon_simple/face_obfuscator.py
index 64079a9..2c369a7 100644
--- a/project/models/face_anon_simple/face_obfuscator.py
+++ b/project/models/deprecated_face_anon_simple/face_obfuscator.py
@@ -54,12 +54,12 @@ class FACE_ANON_SIMPLE():
anon_image = self.pipe(
source_image=face_img,
conditioning_image=face_img,
- num_inference_steps=1,
+ num_inference_steps=200,
guidance_scale=4.0,
generator=self.generator,
anonymization_degree=1.25,
- width=256,
- height=256,
+ width=64,#512
+ height=64,#512
).images[0]
return anon_image
@@ -97,7 +97,7 @@ def main():
print("TEST RUN")
obfuscator = FACE_ANON_SIMPLE()
print("INIT DONE")
- original_image = load_image("my_dataset/test/14795.png")
+ original_image = load_image("my_dataset/test/face.jpg")
print("Image LOADING DONE")
obfuscated = obfuscator.obfuscate(original_image)
print("OBFUSCATION DONE")
diff --git a/project/models/face_anon_simple/my_dataset/test/00482.png b/project/models/deprecated_face_anon_simple/my_dataset/test/00482.png
similarity index 100%
rename from project/models/face_anon_simple/my_dataset/test/00482.png
rename to project/models/deprecated_face_anon_simple/my_dataset/test/00482.png
diff --git a/project/models/face_anon_simple/my_dataset/test/14795.png b/project/models/deprecated_face_anon_simple/my_dataset/test/14795.png
similarity index 100%
rename from project/models/face_anon_simple/my_dataset/test/14795.png
rename to project/models/deprecated_face_anon_simple/my_dataset/test/14795.png
diff --git a/project/models/deprecated_face_anon_simple/my_dataset/test/face.jpg b/project/models/deprecated_face_anon_simple/my_dataset/test/face.jpg
new file mode 100644
index 0000000..eb88398
Binary files /dev/null and b/project/models/deprecated_face_anon_simple/my_dataset/test/face.jpg differ
diff --git a/project/models/face_anon_simple/my_dataset/test/friends.jpg b/project/models/deprecated_face_anon_simple/my_dataset/test/friends.jpg
similarity index 100%
rename from project/models/face_anon_simple/my_dataset/test/friends.jpg
rename to project/models/deprecated_face_anon_simple/my_dataset/test/friends.jpg
diff --git a/project/models/face_anon_simple/my_dataset/train/celeb/fake/18147_06771-01758_01758.png b/project/models/deprecated_face_anon_simple/my_dataset/train/celeb/fake/18147_06771-01758_01758.png
similarity index 100%
rename from project/models/face_anon_simple/my_dataset/train/celeb/fake/18147_06771-01758_01758.png
rename to project/models/deprecated_face_anon_simple/my_dataset/train/celeb/fake/18147_06771-01758_01758.png
diff --git a/project/models/face_anon_simple/my_dataset/train/celeb/real/01758_01758.png b/project/models/deprecated_face_anon_simple/my_dataset/train/celeb/real/01758_01758.png
similarity index 100%
rename from project/models/face_anon_simple/my_dataset/train/celeb/real/01758_01758.png
rename to project/models/deprecated_face_anon_simple/my_dataset/train/celeb/real/01758_01758.png
diff --git a/project/models/face_anon_simple/my_dataset/train/celeb/real/01758_09704.png b/project/models/deprecated_face_anon_simple/my_dataset/train/celeb/real/01758_09704.png
similarity index 100%
rename from project/models/face_anon_simple/my_dataset/train/celeb/real/01758_09704.png
rename to project/models/deprecated_face_anon_simple/my_dataset/train/celeb/real/01758_09704.png
diff --git a/project/models/face_anon_simple/my_dataset/train/celeb/real/18147_06771.png b/project/models/deprecated_face_anon_simple/my_dataset/train/celeb/real/18147_06771.png
similarity index 100%
rename from project/models/face_anon_simple/my_dataset/train/celeb/real/18147_06771.png
rename to project/models/deprecated_face_anon_simple/my_dataset/train/celeb/real/18147_06771.png
diff --git a/project/models/face_anon_simple/my_dataset/train/train.jsonl b/project/models/deprecated_face_anon_simple/my_dataset/train/train.jsonl
similarity index 100%
rename from project/models/face_anon_simple/my_dataset/train/train.jsonl
rename to project/models/deprecated_face_anon_simple/my_dataset/train/train.jsonl
diff --git a/project/models/face_anon_simple/my_dataset/train_dataset_loading_script.py b/project/models/deprecated_face_anon_simple/my_dataset/train_dataset_loading_script.py
similarity index 100%
rename from project/models/face_anon_simple/my_dataset/train_dataset_loading_script.py
rename to project/models/deprecated_face_anon_simple/my_dataset/train_dataset_loading_script.py
diff --git a/project/models/face_anon_simple/src/diffusers/__init__.py b/project/models/deprecated_face_anon_simple/src/diffusers/__init__.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/__init__.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/__init__.py
diff --git a/project/models/face_anon_simple/src/diffusers/commands/__init__.py b/project/models/deprecated_face_anon_simple/src/diffusers/commands/__init__.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/commands/__init__.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/commands/__init__.py
diff --git a/project/models/face_anon_simple/src/diffusers/commands/diffusers_cli.py b/project/models/deprecated_face_anon_simple/src/diffusers/commands/diffusers_cli.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/commands/diffusers_cli.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/commands/diffusers_cli.py
diff --git a/project/models/face_anon_simple/src/diffusers/commands/env.py b/project/models/deprecated_face_anon_simple/src/diffusers/commands/env.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/commands/env.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/commands/env.py
diff --git a/project/models/face_anon_simple/src/diffusers/commands/fp16_safetensors.py b/project/models/deprecated_face_anon_simple/src/diffusers/commands/fp16_safetensors.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/commands/fp16_safetensors.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/commands/fp16_safetensors.py
diff --git a/project/models/face_anon_simple/src/diffusers/configuration_utils.py b/project/models/deprecated_face_anon_simple/src/diffusers/configuration_utils.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/configuration_utils.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/configuration_utils.py
diff --git a/project/models/face_anon_simple/src/diffusers/dependency_versions_check.py b/project/models/deprecated_face_anon_simple/src/diffusers/dependency_versions_check.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/dependency_versions_check.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/dependency_versions_check.py
diff --git a/project/models/face_anon_simple/src/diffusers/dependency_versions_table.py b/project/models/deprecated_face_anon_simple/src/diffusers/dependency_versions_table.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/dependency_versions_table.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/dependency_versions_table.py
diff --git a/project/models/face_anon_simple/src/diffusers/experimental/README.md b/project/models/deprecated_face_anon_simple/src/diffusers/experimental/README.md
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/experimental/README.md
rename to project/models/deprecated_face_anon_simple/src/diffusers/experimental/README.md
diff --git a/project/models/face_anon_simple/src/diffusers/experimental/__init__.py b/project/models/deprecated_face_anon_simple/src/diffusers/experimental/__init__.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/experimental/__init__.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/experimental/__init__.py
diff --git a/project/models/face_anon_simple/src/diffusers/experimental/rl/__init__.py b/project/models/deprecated_face_anon_simple/src/diffusers/experimental/rl/__init__.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/experimental/rl/__init__.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/experimental/rl/__init__.py
diff --git a/project/models/face_anon_simple/src/diffusers/experimental/rl/value_guided_sampling.py b/project/models/deprecated_face_anon_simple/src/diffusers/experimental/rl/value_guided_sampling.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/experimental/rl/value_guided_sampling.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/experimental/rl/value_guided_sampling.py
diff --git a/project/models/face_anon_simple/src/diffusers/image_processor.py b/project/models/deprecated_face_anon_simple/src/diffusers/image_processor.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/image_processor.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/image_processor.py
diff --git a/project/models/face_anon_simple/src/diffusers/loaders/__init__.py b/project/models/deprecated_face_anon_simple/src/diffusers/loaders/__init__.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/loaders/__init__.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/loaders/__init__.py
diff --git a/project/models/face_anon_simple/src/diffusers/loaders/ip_adapter.py b/project/models/deprecated_face_anon_simple/src/diffusers/loaders/ip_adapter.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/loaders/ip_adapter.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/loaders/ip_adapter.py
diff --git a/project/models/face_anon_simple/src/diffusers/loaders/lora.py b/project/models/deprecated_face_anon_simple/src/diffusers/loaders/lora.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/loaders/lora.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/loaders/lora.py
diff --git a/project/models/face_anon_simple/src/diffusers/loaders/lora_conversion_utils.py b/project/models/deprecated_face_anon_simple/src/diffusers/loaders/lora_conversion_utils.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/loaders/lora_conversion_utils.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/loaders/lora_conversion_utils.py
diff --git a/project/models/face_anon_simple/src/diffusers/loaders/single_file.py b/project/models/deprecated_face_anon_simple/src/diffusers/loaders/single_file.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/loaders/single_file.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/loaders/single_file.py
diff --git a/project/models/face_anon_simple/src/diffusers/loaders/textual_inversion.py b/project/models/deprecated_face_anon_simple/src/diffusers/loaders/textual_inversion.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/loaders/textual_inversion.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/loaders/textual_inversion.py
diff --git a/project/models/face_anon_simple/src/diffusers/loaders/unet.py b/project/models/deprecated_face_anon_simple/src/diffusers/loaders/unet.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/loaders/unet.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/loaders/unet.py
diff --git a/project/models/face_anon_simple/src/diffusers/loaders/utils.py b/project/models/deprecated_face_anon_simple/src/diffusers/loaders/utils.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/loaders/utils.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/loaders/utils.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/README.md b/project/models/deprecated_face_anon_simple/src/diffusers/models/README.md
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/README.md
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/README.md
diff --git a/project/models/face_anon_simple/src/diffusers/models/__init__.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/__init__.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/__init__.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/__init__.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/activations.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/activations.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/activations.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/activations.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/adapter.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/adapter.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/adapter.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/adapter.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/attention.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/attention.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/attention.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/attention.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/attention_flax.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/attention_flax.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/attention_flax.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/attention_flax.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/attention_processor.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/attention_processor.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/attention_processor.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/attention_processor.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/autoencoders/__init__.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/autoencoders/__init__.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/autoencoders/__init__.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/autoencoders/__init__.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/autoencoders/autoencoder_asym_kl.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/autoencoders/autoencoder_asym_kl.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/autoencoders/autoencoder_asym_kl.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/autoencoders/autoencoder_asym_kl.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/autoencoders/autoencoder_kl.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/autoencoders/autoencoder_kl.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/autoencoders/autoencoder_kl.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/autoencoders/autoencoder_kl.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/autoencoders/autoencoder_tiny.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/autoencoders/autoencoder_tiny.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/autoencoders/autoencoder_tiny.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/autoencoders/autoencoder_tiny.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/autoencoders/consistency_decoder_vae.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/autoencoders/consistency_decoder_vae.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/autoencoders/consistency_decoder_vae.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/autoencoders/consistency_decoder_vae.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/autoencoders/vae.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/autoencoders/vae.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/autoencoders/vae.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/autoencoders/vae.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/controlnet.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/controlnet.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/controlnet.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/controlnet.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/controlnet_flax.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/controlnet_flax.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/controlnet_flax.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/controlnet_flax.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/downsampling.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/downsampling.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/downsampling.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/downsampling.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/dual_transformer_2d.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/dual_transformer_2d.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/dual_transformer_2d.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/dual_transformer_2d.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/embeddings.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/embeddings.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/embeddings.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/embeddings.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/embeddings_flax.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/embeddings_flax.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/embeddings_flax.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/embeddings_flax.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/lora.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/lora.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/lora.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/lora.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/modeling_flax_pytorch_utils.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/modeling_flax_pytorch_utils.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/modeling_flax_pytorch_utils.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/modeling_flax_pytorch_utils.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/modeling_flax_utils.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/modeling_flax_utils.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/modeling_flax_utils.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/modeling_flax_utils.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/modeling_outputs.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/modeling_outputs.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/modeling_outputs.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/modeling_outputs.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/modeling_pytorch_flax_utils.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/modeling_pytorch_flax_utils.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/modeling_pytorch_flax_utils.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/modeling_pytorch_flax_utils.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/modeling_utils.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/modeling_utils.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/modeling_utils.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/modeling_utils.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/normalization.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/normalization.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/normalization.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/normalization.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/prior_transformer.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/prior_transformer.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/prior_transformer.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/prior_transformer.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/referencenet/attention.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/referencenet/attention.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/referencenet/attention.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/referencenet/attention.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/referencenet/referencenet_transformer_2d.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/referencenet/referencenet_transformer_2d.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/referencenet/referencenet_transformer_2d.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/referencenet/referencenet_transformer_2d.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/referencenet/referencenet_unet_2d_blocks.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/referencenet/referencenet_unet_2d_blocks.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/referencenet/referencenet_unet_2d_blocks.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/referencenet/referencenet_unet_2d_blocks.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/referencenet/referencenet_unet_2d_condition.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/referencenet/referencenet_unet_2d_condition.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/referencenet/referencenet_unet_2d_condition.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/referencenet/referencenet_unet_2d_condition.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/referencenet/transformer_2d.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/referencenet/transformer_2d.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/referencenet/transformer_2d.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/referencenet/transformer_2d.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/referencenet/unet_2d_blocks.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/referencenet/unet_2d_blocks.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/referencenet/unet_2d_blocks.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/referencenet/unet_2d_blocks.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/referencenet/unet_2d_condition.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/referencenet/unet_2d_condition.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/referencenet/unet_2d_condition.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/referencenet/unet_2d_condition.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/resnet.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/resnet.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/resnet.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/resnet.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/resnet_flax.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/resnet_flax.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/resnet_flax.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/resnet_flax.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/t5_film_transformer.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/t5_film_transformer.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/t5_film_transformer.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/t5_film_transformer.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/transformer_2d.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/transformer_2d.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/transformer_2d.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/transformer_2d.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/transformer_temporal.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/transformer_temporal.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/transformer_temporal.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/transformer_temporal.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/unet_1d.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/unet_1d.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/unet_1d.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/unet_1d.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/unet_1d_blocks.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/unet_1d_blocks.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/unet_1d_blocks.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/unet_1d_blocks.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/unet_2d.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/unet_2d.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/unet_2d.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/unet_2d.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/unet_2d_blocks.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/unet_2d_blocks.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/unet_2d_blocks.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/unet_2d_blocks.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/unet_2d_blocks_flax.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/unet_2d_blocks_flax.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/unet_2d_blocks_flax.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/unet_2d_blocks_flax.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/unet_2d_condition.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/unet_2d_condition.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/unet_2d_condition.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/unet_2d_condition.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/unet_2d_condition_flax.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/unet_2d_condition_flax.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/unet_2d_condition_flax.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/unet_2d_condition_flax.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/unet_3d_blocks.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/unet_3d_blocks.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/unet_3d_blocks.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/unet_3d_blocks.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/unet_3d_condition.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/unet_3d_condition.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/unet_3d_condition.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/unet_3d_condition.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/unet_kandinsky3.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/unet_kandinsky3.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/unet_kandinsky3.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/unet_kandinsky3.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/unet_motion_model.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/unet_motion_model.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/unet_motion_model.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/unet_motion_model.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/unet_spatio_temporal_condition.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/unet_spatio_temporal_condition.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/unet_spatio_temporal_condition.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/unet_spatio_temporal_condition.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/upsampling.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/upsampling.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/upsampling.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/upsampling.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/uvit_2d.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/uvit_2d.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/uvit_2d.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/uvit_2d.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/vae_flax.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/vae_flax.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/vae_flax.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/vae_flax.py
diff --git a/project/models/face_anon_simple/src/diffusers/models/vq_model.py b/project/models/deprecated_face_anon_simple/src/diffusers/models/vq_model.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/models/vq_model.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/models/vq_model.py
diff --git a/project/models/face_anon_simple/src/diffusers/optimization.py b/project/models/deprecated_face_anon_simple/src/diffusers/optimization.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/optimization.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/optimization.py
diff --git a/project/models/face_anon_simple/src/diffusers/pipelines/referencenet/pipeline_referencenet.py b/project/models/deprecated_face_anon_simple/src/diffusers/pipelines/referencenet/pipeline_referencenet.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/pipelines/referencenet/pipeline_referencenet.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/pipelines/referencenet/pipeline_referencenet.py
diff --git a/project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/README.md b/project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/README.md
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/README.md
rename to project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/README.md
diff --git a/project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/__init__.py b/project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/__init__.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/__init__.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/__init__.py
diff --git a/project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/clip_image_project_model.py b/project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/clip_image_project_model.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/clip_image_project_model.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/clip_image_project_model.py
diff --git a/project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/convert_from_ckpt.py b/project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/convert_from_ckpt.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/convert_from_ckpt.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/convert_from_ckpt.py
diff --git a/project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py b/project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py
diff --git a/project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_img2img.py b/project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_img2img.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_img2img.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_img2img.py
diff --git a/project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_inpaint.py b/project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_inpaint.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_inpaint.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_inpaint.py
diff --git a/project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion.py b/project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion.py
diff --git a/project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py b/project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py
diff --git a/project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py b/project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py
diff --git a/project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_upscale.py b/project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_upscale.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_upscale.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_upscale.py
diff --git a/project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_output.py b/project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_output.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_output.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_output.py
diff --git a/project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py b/project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py
diff --git a/project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py b/project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py
diff --git a/project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py b/project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py
diff --git a/project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py b/project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py
diff --git a/project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py b/project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py
diff --git a/project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py b/project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py
diff --git a/project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py b/project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py
diff --git a/project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py b/project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py
diff --git a/project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py b/project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py
diff --git a/project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py b/project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py
diff --git a/project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/safety_checker.py b/project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/safety_checker.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/safety_checker.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/safety_checker.py
diff --git a/project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/safety_checker_flax.py b/project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/safety_checker_flax.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/safety_checker_flax.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/safety_checker_flax.py
diff --git a/project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/stable_unclip_image_normalizer.py b/project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/stable_unclip_image_normalizer.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/pipelines/stable_diffusion/stable_unclip_image_normalizer.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/pipelines/stable_diffusion/stable_unclip_image_normalizer.py
diff --git a/project/models/deprecated_face_anon_simple/src/diffusers/py.typed b/project/models/deprecated_face_anon_simple/src/diffusers/py.typed
new file mode 100644
index 0000000..e69de29
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/README.md b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/README.md
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/README.md
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/README.md
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/__init__.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/__init__.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/__init__.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/__init__.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/deprecated/__init__.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/deprecated/__init__.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/deprecated/__init__.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/deprecated/__init__.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/deprecated/scheduling_karras_ve.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/deprecated/scheduling_karras_ve.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/deprecated/scheduling_karras_ve.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/deprecated/scheduling_karras_ve.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/deprecated/scheduling_sde_vp.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/deprecated/scheduling_sde_vp.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/deprecated/scheduling_sde_vp.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/deprecated/scheduling_sde_vp.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_amused.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_amused.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_amused.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_amused.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_consistency_decoder.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_consistency_decoder.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_consistency_decoder.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_consistency_decoder.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_consistency_models.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_consistency_models.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_consistency_models.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_consistency_models.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_ddim.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_ddim.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_ddim.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_ddim.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_ddim_flax.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_ddim_flax.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_ddim_flax.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_ddim_flax.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_ddim_inverse.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_ddim_inverse.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_ddim_inverse.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_ddim_inverse.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_ddim_parallel.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_ddim_parallel.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_ddim_parallel.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_ddim_parallel.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_ddpm.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_ddpm.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_ddpm.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_ddpm.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_ddpm_flax.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_ddpm_flax.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_ddpm_flax.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_ddpm_flax.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_ddpm_parallel.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_ddpm_parallel.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_ddpm_parallel.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_ddpm_parallel.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_ddpm_wuerstchen.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_ddpm_wuerstchen.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_ddpm_wuerstchen.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_ddpm_wuerstchen.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_deis_multistep.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_deis_multistep.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_deis_multistep.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_deis_multistep.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_dpmsolver_multistep.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_dpmsolver_multistep.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_dpmsolver_multistep.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_dpmsolver_multistep.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_dpmsolver_multistep_flax.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_dpmsolver_multistep_flax.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_dpmsolver_multistep_flax.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_dpmsolver_multistep_flax.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_dpmsolver_sde.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_dpmsolver_sde.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_dpmsolver_sde.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_dpmsolver_sde.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_dpmsolver_singlestep.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_dpmsolver_singlestep.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_dpmsolver_singlestep.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_dpmsolver_singlestep.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_euler_ancestral_discrete.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_euler_ancestral_discrete.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_euler_ancestral_discrete.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_euler_ancestral_discrete.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_euler_discrete.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_euler_discrete.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_euler_discrete.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_euler_discrete.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_euler_discrete_flax.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_euler_discrete_flax.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_euler_discrete_flax.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_euler_discrete_flax.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_heun_discrete.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_heun_discrete.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_heun_discrete.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_heun_discrete.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_ipndm.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_ipndm.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_ipndm.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_ipndm.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_k_dpm_2_discrete.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_k_dpm_2_discrete.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_k_dpm_2_discrete.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_k_dpm_2_discrete.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_karras_ve_flax.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_karras_ve_flax.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_karras_ve_flax.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_karras_ve_flax.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_lcm.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_lcm.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_lcm.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_lcm.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_lms_discrete.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_lms_discrete.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_lms_discrete.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_lms_discrete.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_lms_discrete_flax.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_lms_discrete_flax.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_lms_discrete_flax.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_lms_discrete_flax.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_pndm.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_pndm.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_pndm.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_pndm.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_pndm_flax.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_pndm_flax.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_pndm_flax.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_pndm_flax.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_repaint.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_repaint.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_repaint.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_repaint.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_sde_ve.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_sde_ve.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_sde_ve.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_sde_ve.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_sde_ve_flax.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_sde_ve_flax.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_sde_ve_flax.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_sde_ve_flax.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_unclip.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_unclip.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_unclip.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_unclip.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_unipc_multistep.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_unipc_multistep.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_unipc_multistep.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_unipc_multistep.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_utils.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_utils.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_utils.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_utils.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_utils_flax.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_utils_flax.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_utils_flax.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_utils_flax.py
diff --git a/project/models/face_anon_simple/src/diffusers/schedulers/scheduling_vq_diffusion.py b/project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_vq_diffusion.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/schedulers/scheduling_vq_diffusion.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/schedulers/scheduling_vq_diffusion.py
diff --git a/project/models/face_anon_simple/src/diffusers/training_utils.py b/project/models/deprecated_face_anon_simple/src/diffusers/training_utils.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/training_utils.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/training_utils.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/__init__.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/__init__.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/__init__.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/__init__.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/accelerate_utils.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/accelerate_utils.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/accelerate_utils.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/accelerate_utils.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/constants.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/constants.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/constants.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/constants.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/deprecation_utils.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/deprecation_utils.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/deprecation_utils.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/deprecation_utils.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/doc_utils.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/doc_utils.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/doc_utils.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/doc_utils.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/dummy_flax_and_transformers_objects.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/dummy_flax_and_transformers_objects.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/dummy_flax_and_transformers_objects.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/dummy_flax_and_transformers_objects.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/dummy_flax_objects.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/dummy_flax_objects.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/dummy_flax_objects.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/dummy_flax_objects.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/dummy_note_seq_objects.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/dummy_note_seq_objects.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/dummy_note_seq_objects.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/dummy_note_seq_objects.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/dummy_onnx_objects.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/dummy_onnx_objects.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/dummy_onnx_objects.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/dummy_onnx_objects.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/dummy_pt_objects.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/dummy_pt_objects.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/dummy_pt_objects.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/dummy_pt_objects.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/dummy_torch_and_librosa_objects.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/dummy_torch_and_librosa_objects.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/dummy_torch_and_librosa_objects.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/dummy_torch_and_librosa_objects.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/dummy_torch_and_scipy_objects.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/dummy_torch_and_scipy_objects.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/dummy_torch_and_scipy_objects.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/dummy_torch_and_scipy_objects.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/dummy_torch_and_torchsde_objects.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/dummy_torch_and_torchsde_objects.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/dummy_torch_and_torchsde_objects.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/dummy_torch_and_torchsde_objects.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/dummy_torch_and_transformers_and_k_diffusion_objects.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/dummy_torch_and_transformers_and_k_diffusion_objects.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/dummy_torch_and_transformers_and_k_diffusion_objects.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/dummy_torch_and_transformers_and_k_diffusion_objects.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/dummy_torch_and_transformers_and_onnx_objects.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/dummy_torch_and_transformers_and_onnx_objects.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/dummy_torch_and_transformers_and_onnx_objects.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/dummy_torch_and_transformers_and_onnx_objects.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/dummy_torch_and_transformers_objects.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/dummy_torch_and_transformers_objects.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/dummy_torch_and_transformers_objects.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/dummy_torch_and_transformers_objects.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/dummy_transformers_and_torch_and_note_seq_objects.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/dummy_transformers_and_torch_and_note_seq_objects.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/dummy_transformers_and_torch_and_note_seq_objects.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/dummy_transformers_and_torch_and_note_seq_objects.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/dynamic_modules_utils.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/dynamic_modules_utils.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/dynamic_modules_utils.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/dynamic_modules_utils.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/export_utils.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/export_utils.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/export_utils.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/export_utils.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/hub_utils.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/hub_utils.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/hub_utils.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/hub_utils.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/import_utils.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/import_utils.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/import_utils.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/import_utils.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/loading_utils.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/loading_utils.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/loading_utils.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/loading_utils.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/logging.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/logging.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/logging.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/logging.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/model_card_template.md b/project/models/deprecated_face_anon_simple/src/diffusers/utils/model_card_template.md
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/model_card_template.md
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/model_card_template.md
diff --git a/project/models/face_anon_simple/src/diffusers/utils/outputs.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/outputs.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/outputs.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/outputs.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/peft_utils.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/peft_utils.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/peft_utils.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/peft_utils.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/pil_utils.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/pil_utils.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/pil_utils.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/pil_utils.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/state_dict_utils.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/state_dict_utils.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/state_dict_utils.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/state_dict_utils.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/testing_utils.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/testing_utils.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/testing_utils.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/testing_utils.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/torch_utils.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/torch_utils.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/torch_utils.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/torch_utils.py
diff --git a/project/models/face_anon_simple/src/diffusers/utils/versions.py b/project/models/deprecated_face_anon_simple/src/diffusers/utils/versions.py
similarity index 100%
rename from project/models/face_anon_simple/src/diffusers/utils/versions.py
rename to project/models/deprecated_face_anon_simple/src/diffusers/utils/versions.py
diff --git a/project/models/face_anon_simple/teaser.jpg b/project/models/deprecated_face_anon_simple/teaser.jpg
similarity index 100%
rename from project/models/face_anon_simple/teaser.jpg
rename to project/models/deprecated_face_anon_simple/teaser.jpg
diff --git a/project/models/face_anon_simple/train_referencenet.sh b/project/models/deprecated_face_anon_simple/train_referencenet.sh
similarity index 100%
rename from project/models/face_anon_simple/train_referencenet.sh
rename to project/models/deprecated_face_anon_simple/train_referencenet.sh
diff --git a/project/models/face_anon_simple/utils/anonymize_faces_in_image.py b/project/models/deprecated_face_anon_simple/utils/anonymize_faces_in_image.py
similarity index 100%
rename from project/models/face_anon_simple/utils/anonymize_faces_in_image.py
rename to project/models/deprecated_face_anon_simple/utils/anonymize_faces_in_image.py
diff --git a/project/models/face_anon_simple/utils/extractor.py b/project/models/deprecated_face_anon_simple/utils/extractor.py
similarity index 100%
rename from project/models/face_anon_simple/utils/extractor.py
rename to project/models/deprecated_face_anon_simple/utils/extractor.py
diff --git a/project/models/face_anon_simple/utils/merger.py b/project/models/deprecated_face_anon_simple/utils/merger.py
similarity index 100%
rename from project/models/face_anon_simple/utils/merger.py
rename to project/models/deprecated_face_anon_simple/utils/merger.py
diff --git a/project/models/ganonymization/.github/workflows/pylint.yml b/project/models/ganonymization/.github/workflows/pylint.yml
new file mode 100644
index 0000000..5309dab
--- /dev/null
+++ b/project/models/ganonymization/.github/workflows/pylint.yml
@@ -0,0 +1,24 @@
+name: Pylint
+
+on: [push]
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ strategy:
+ matrix:
+ python-version: ["3.8"]
+ steps:
+ - uses: actions/checkout@v3
+ - name: Set up Python ${{ matrix.python-version }}
+ uses: actions/setup-python@v3
+ with:
+ python-version: ${{ matrix.python-version }}
+ - name: Install dependencies
+ run: |
+ python -m pip install --upgrade pip
+ pip install pylint
+ pip install -r requirements.txt
+ - name: Analysing the code with pylint
+ run: |
+ pylint $(git ls-files '*.py')
diff --git a/project/models/ganonymization/.gitignore b/project/models/ganonymization/.gitignore
new file mode 100644
index 0000000..892e879
--- /dev/null
+++ b/project/models/ganonymization/.gitignore
@@ -0,0 +1,139 @@
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+*$py.class
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+pip-wheel-metadata/
+share/python-wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+
+# PyInstaller
+# Usually these files are written by a python script from a template
+# before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.nox/
+.coverage
+.coverage.*
+.cache
+nosetests.xml
+coverage.xml
+*.cover
+*.py,cover
+.hypothesis/
+.pytest_cache/
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+local_settings.py
+db.sqlite3
+db.sqlite3-journal
+
+# Flask stuff:
+instance/
+.webassets-cache
+
+# Scrapy stuff:
+.scrapy
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+target/
+
+# Jupyter Notebook
+.ipynb_checkpoints
+
+# IPython
+profile_default/
+ipython_config.py
+
+# pyenv
+.python-version
+
+# pipenv
+# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
+# However, in case of collaboration, if having platform-specific dependencies or dependencies
+# having no cross-platform support, pipenv may install dependencies that don't work, or not
+# install all needed dependencies.
+#Pipfile.lock
+
+# PEP 582; used by e.g. github.com/David-OConnor/pyflow
+__pypackages__/
+
+# Celery stuff
+celerybeat-schedule
+celerybeat.pid
+
+# SageMath parsed files
+*.sage.py
+
+# Environments
+.env
+.venv
+env/
+venv/
+ENV/
+env.bak/
+venv.bak/
+
+# Spyder project settings
+.spyderproject
+.spyproject
+
+# Rope project settings
+.ropeproject
+
+# mkdocs documentation
+/site
+
+# mypy
+.mypy_cache/
+.dmypy.json
+dmypy.json
+
+# Pyre type checker
+.pyre/
+
+# Others
+data/
+output/
+logs/
+.idea
+*.pth
+*.ckpt
+*.onnx
+
+GANonymization.ckpt
\ No newline at end of file
diff --git a/project/models/ganonymization/.pylintrc b/project/models/ganonymization/.pylintrc
new file mode 100644
index 0000000..b5345e2
--- /dev/null
+++ b/project/models/ganonymization/.pylintrc
@@ -0,0 +1,445 @@
+[MASTER]
+
+# Specify a configuration file.
+#rcfile=
+
+# Python code to execute, usually for sys.path manipulation such as
+# pygtk.require().
+#init-hook=
+
+# Add files or directories to the blacklist. They should be base names, not
+# paths.
+ignore=CVS
+
+# Pickle collected data for later comparisons.
+persistent=yes
+
+# List of plugins (as comma separated values of python modules names) to load,
+# usually to register additional checkers.
+load-plugins=
+
+# Use multiple processes to speed up Pylint.
+jobs=1
+
+# Allow loading of arbitrary C extensions. Extensions are imported into the
+# active Python interpreter and may run arbitrary code.
+unsafe-load-any-extension=no
+
+# A comma-separated list of package or module names from where C extensions may
+# be loaded. Extensions are loading into the active Python interpreter and may
+# run arbitrary code
+extension-pkg-whitelist=
+
+
+[MESSAGES CONTROL]
+
+# Only show warnings with the listed confidence levels. Leave empty to show
+# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED
+confidence=
+
+# Enable the message, report, category or checker with the given id(s). You can
+# either give multiple identifier separated by comma (,) or put this option
+# multiple time. See also the "--disable" option for examples.
+#enable=
+
+# Disable the message, report, category or checker with the given id(s). You
+# can either give multiple identifiers separated by comma (,) or put this
+# option multiple times (only on the command line, not in the configuration
+# file where it should appear only once).You can also use "--disable=all" to
+# disable everything first and then reenable specific checks. For example, if
+# you want to run only the similarities checker, you can use "--disable=all
+# --enable=similarities". If you want to run only the classes checker, but have
+# no Warning level messages displayed, use"--disable=all --enable=classes
+# --disable=W"
+#
+# -----------------------------------------------------------------------
+# 2015-01-12 - What follows is the list of all disabled items necessary
+# to get a clean run of lint across CourseBuilder. These are separated
+# into three tiers:
+#
+# - Fix-worthy. This includes:
+# - Probable bugs
+# - Easily-addressed hygiene issues,
+# - Real warnings which we may mark as suppressed on a case-by-case basis.
+# - Items that are questionable practice, but not necessarily economical to fix.
+# - Items that we intend to ignore, as we do not consider them bad practice.
+#
+# Warning messages are documented at http://docs.pylint.org/features.html
+#
+# ----------------------------------------------------------------------
+# Fix-worthy:
+#
+# ---- Possible bugs:
+# disable=super-on-old-class
+# disable=arguments-differ (# of arguments to overriding/overridden method)
+# disable=signature-differs
+# disable=method-hidden
+# disable=abstract-method (Abstract method not overridden in derived class)
+# disable=no-member (self.foo used when foo not declared in class)
+#
+# ---- Easy-to-fix and improves readability, cleanliness:
+# disable=relative-import
+#
+# ---- Probably legitimate, but needs markup to indicate intentionality
+# disable=no-init (Class does not have __init__, nor do ancestor classes)
+# disable=import-error
+# disable=attribute-defined-outside-init
+#
+# ----------------------------------------------------------------------
+# Fix when economical:
+#
+# ---- Minor code cleanliness problems; fix when encountered.
+# disable=unused-argument
+# disable=unused-variable
+# disable=invalid-name (Variable name does not meet coding standard)
+# disable=duplicate-code
+#
+# ---- Laundry list of tunable parameters for when things are too big/small
+# disable=abstract-class-little-used
+# disable=too-few-public-methods
+# disable=too-many-instance-attributes
+# disable=too-many-ancestors
+# disable=too-many-return-statements
+# disable=too-many-lines
+# disable=too-many-locals
+# disable=too-many-function-args
+# disable=too-many-public-methods
+# disable=too-many-arguments
+#
+# ----------------------------------------------------------------------
+# Ignored; OK by our coding standard:
+#
+# disable=bad-continuation (Bad whitespace on following line)
+# disable=no-self-use (Member function never uses 'self' parameter)
+# disable=missing-docstring
+# disable=fixme
+# disable=star-args
+# disable=locally-disabled (Notes local suppression of warning)
+# disable=locally-enabled (Notes re-enable of suppressed warning)
+# disable=bad-option-value (Notes suppression of unknown warning)
+# disable=abstract-class-not-used (Warns when not used in same file)
+#
+# Unfortunately, since the options parsing does not support multi-line entries
+# nor line continuation, all of the above items are redundantly specified here
+# in a way that pylint is willing to parse.
+disable=
+ no-member,
+ no-name-in-module,
+ no-init,
+ no-else-return,
+ no-value-for-parameter,
+ arguments-differ,
+ unpacking-non-sequence,
+ not-callable,
+ useless-parent-delegation,
+ attribute-defined-outside-init,
+ unused-argument,
+ unused-variable,
+ invalid-name,
+ duplicate-code,
+ abstract-class-little-used,
+ too-few-public-methods,
+ too-many-instance-attributes,
+ too-many-ancestors,
+ too-many-return-statements,
+ too-many-lines,
+ too-many-locals,
+ too-many-function-args,
+ too-many-public-methods,
+ too-many-arguments,
+ bad-continuation,
+ no-self-use,
+ missing-docstring,
+ fixme,
+ star-args,
+ locally-disabled,
+ locally-enabled,
+ bad-option-value
+
+[REPORTS]
+
+# Set the output format. Available formats are text, parseable, colorized, msvs
+# (visual studio) and html. You can also give a reporter class, eg
+# mypackage.mymodule.MyReporterClass.
+output-format=text
+
+# Tells whether to display a full report or only the messages
+reports=no
+
+# Python expression which should return a note less than 10 (10 is the highest
+# note). You have access to the variables errors warning, statement which
+# respectively contain the number of errors / warnings messages and the total
+# number of statements analyzed. This is used by the global evaluation report
+# (RP0004).
+evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10))
+
+# Template used to display messages. This is a python new-style format string
+# used to format the message information. See doc for all details
+#msg-template=
+
+# Activate the evaluation score.
+score=yes
+
+
+[SPELLING]
+
+# Spelling dictionary name. Available dictionaries: none. To make it working
+# install python-enchant package.
+spelling-dict=
+
+# List of comma separated words that should not be checked.
+spelling-ignore-words=
+
+# A path to a file that contains private dictionary; one word per line.
+spelling-private-dict-file=
+
+# Tells whether to store unknown words to indicated private dictionary in
+# --spelling-private-dict-file option instead of raising a message.
+spelling-store-unknown-words=no
+
+
+[SIMILARITIES]
+
+# Minimum lines number of a similarity.
+min-similarity-lines=4
+
+# Ignore comments when computing similarities.
+ignore-comments=yes
+
+# Ignore docstrings when computing similarities.
+ignore-docstrings=yes
+
+# Ignore imports when computing similarities.
+ignore-imports=no
+
+
+[LOGGING]
+
+# Logging modules to check that the string format arguments are in logging
+# function parameter format
+logging-modules=logging
+
+
+[MISCELLANEOUS]
+
+# List of note tags to take in consideration, separated by a comma.
+notes=FIXME,XXX,TODO
+
+
+[VARIABLES]
+
+# Tells whether we should check for unused import in __init__ files.
+init-import=yes
+
+# A regular expression matching the name of dummy variables (i.e. expectedly
+# not used).
+dummy-variables-rgx=_$|dummy
+
+# List of additional names supposed to be defined in builtins. Remember that
+# you should avoid to define new builtins when possible.
+additional-builtins=
+
+# List of strings which can identify a callback function by name. A callback
+# name must start or end with one of those strings.
+callbacks=cb_,_cb
+
+
+[TYPECHECK]
+
+# Tells whether missing members accessed in mixin class should be ignored. A
+# mixin class is detected if its name ends with "mixin" (case insensitive).
+ignore-mixin-members=yes
+
+# List of module names for which member attributes should not be checked
+# (useful for modules/projects where namespaces are manipulated during runtime
+# and thus existing member attributes cannot be deduced by static analysis
+ignored-modules=
+
+# List of classes names for which member attributes should not be checked
+# (useful for classes with attributes dynamically set).
+ignored-classes=SQLObject
+
+# List of members which are set dynamically and missed by pylint inference
+# system, and so shouldn't trigger E0201 when accessed. Python regular
+# expressions are accepted.
+generated-members=REQUEST,acl_users,aq_parent
+
+
+[BASIC]
+
+# Good variable names which should always be accepted, separated by a comma
+good-names=i,j,k,ex,Run,_
+
+# Bad variable names which should always be refused, separated by a comma
+bad-names=foo,bar,baz,toto,tutu,tata
+
+# Colon-delimited sets of names that determine each other's naming style when
+# the name regexes allow several styles.
+name-group=
+
+# Include a hint for the correct naming format with invalid-name
+include-naming-hint=no
+
+# Regular expression matching correct function names
+function-rgx=[a-z_][a-z0-9_]{2,50}$
+
+# Regular expression matching correct variable names
+variable-rgx=[a-z_][a-z0-9_]{1,30}$
+
+# Regular expression matching correct constant names
+const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$
+
+# Regular expression matching correct attribute names
+attr-rgx=[a-z_][a-z0-9_]{2,30}$
+
+# Regular expression matching correct argument names
+argument-rgx=[a-z_][a-z0-9_]{2,30}$
+
+# Regular expression matching correct class attribute names
+class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
+
+# Regular expression matching correct inline iteration names
+inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$
+
+# Regular expression matching correct class names
+class-rgx=[A-Z_][a-zA-Z0-9]+$
+
+# Regular expression matching correct module names
+module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
+
+# Regular expression matching correct method names
+method-rgx=[a-z_][a-z0-9_]{2,30}$
+
+# Regular expression which should only match function or class names that do
+# not require a docstring.
+no-docstring-rgx=__.*__
+
+# Minimum line length for functions/classes that require docstrings, shorter
+# ones are exempt.
+docstring-min-length=-1
+
+
+[FORMAT]
+
+# Maximum number of characters on a single line.
+max-line-length=100
+
+# Regexp for a line that is allowed to be longer than the limit.
+ignore-long-lines=^\s*(# )??$
+
+# Allow the body of an if to be on the same line as the test if there is no
+# else.
+single-line-if-stmt=no
+
+# Maximum number of lines in a module
+max-module-lines=2000
+
+# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
+# tab).
+indent-string=' '
+
+# Number of spaces of indent required inside a hanging or continued line.
+indent-after-paren=4
+
+# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
+expected-line-ending-format=CRLF
+
+
+[IMPORTS]
+
+# List of modules that can be imported at any level, not just the top level
+# one.
+allow-any-import-level=
+
+# Allow wildcard imports from modules that define __all__.
+allow-wildcard-with-all=no
+
+# Allow explicit reexports by alias from a package __init__.
+allow-reexport-from-package=no
+
+# Analyse import fallback blocks. This can be used to support both Python 2 and
+# 3 compatible code, which means that the block might have code that exists
+# only in one or another interpreter, leading to false positives when analysed.
+analyse-fallback-blocks=no
+
+# Deprecated modules which should not be used, separated by a comma
+deprecated-modules=regsub,TERMIOS,Bastion,rexec
+
+# Create a graph of every (i.e. internal and external) dependencies in the
+# given file (report RP0402 must not be disabled)
+import-graph=
+
+# Create a graph of external dependencies in the given file (report RP0402 must
+# not be disabled)
+ext-import-graph=
+
+# Create a graph of internal dependencies in the given file (report RP0402 must
+# not be disabled)
+int-import-graph=
+
+# Force import order to recognize a module as part of the standard
+# compatibility libraries.
+known-standard-library=
+
+# Force import order to recognize a module as part of a third party library.
+known-third-party=enchant
+
+# Couples of modules and preferred modules, separated by a comma.
+preferred-modules=
+
+
+[CLASSES]
+
+# List of method names used to declare (i.e. assign) instance attributes.
+defining-attr-methods=__init__,__new__,setUp
+
+# List of valid names for the first argument in a class method.
+valid-classmethod-first-arg=cls
+
+# List of valid names for the first argument in a metaclass class method.
+valid-metaclass-classmethod-first-arg=mcs
+
+# List of member names, which should be excluded from the protected access
+# warning.
+exclude-protected=_asdict,_fields,_replace,_source,_make
+
+
+[DESIGN]
+
+# Maximum number of arguments for function / method
+max-args=10
+
+# Argument names that match this expression will be ignored. Default to name
+# with leading underscore
+ignored-argument-names=_.*
+
+# Maximum number of locals for function / method body
+max-locals=25
+
+# Maximum number of return / yield for function / method body
+max-returns=6
+
+# Maximum number of branch for function / method body
+max-branches=40
+
+# Maximum number of statements in function / method body
+max-statements=105
+
+# Maximum number of parents for a class (see R0901).
+max-parents=7
+
+# Maximum number of attributes for a class (see R0902).
+max-attributes=7
+
+# Minimum number of public methods for a class (see R0903).
+min-public-methods=2
+
+# Maximum number of public methods for a class (see R0904).
+max-public-methods=50
+
+
+[EXCEPTIONS]
+
+# Exceptions that will emit a warning when being caught. Defaults to
+# "Exception"
+overgeneral-exceptions=builtins.Exception
\ No newline at end of file
diff --git a/project/models/ganonymization/CITATION b/project/models/ganonymization/CITATION
new file mode 100644
index 0000000..3a6d90c
--- /dev/null
+++ b/project/models/ganonymization/CITATION
@@ -0,0 +1,15 @@
+@article{10.1145/3641107,
+ author = {Hellmann, Fabio and Mertes, Silvan and Benouis, Mohamed and Hustinx, Alexander and Hsieh, Tzung-Chien and Conati, Cristina and Krawitz, Peter and Andr\'{e}, Elisabeth},
+ title = {GANonymization: A GAN-based Face Anonymization Framework for Preserving Emotional Expressions},
+ year = {2024},
+ publisher = {Association for Computing Machinery},
+ address = {New York, NY, USA},
+ issn = {1551-6857},
+ url = {https://doi.org/10.1145/3641107},
+ doi = {10.1145/3641107},
+ abstract = {In recent years, the increasing availability of personal data has raised concerns regarding privacy and security. One of the critical processes to address these concerns is data anonymization, which aims to protect individual privacy and prevent the release of sensitive information. This research focuses on the importance of face anonymization. Therefore, we introduce GANonymization, a novel face anonymization framework with facial expression-preserving abilities. Our approach is based on a high-level representation of a face, which is synthesized into an anonymized version based on a generative adversarial network (GAN). The effectiveness of the approach was assessed by evaluating its performance in removing identifiable facial attributes to increase the anonymity of the given individual face. Additionally, the performance of preserving facial expressions was evaluated on several affect recognition datasets and outperformed the state-of-the-art methods in most categories. Finally, our approach was analyzed for its ability to remove various facial traits, such as jewelry, hair color, and multiple others. Here, it demonstrated reliable performance in removing these attributes. Our results suggest that GANonymization is a promising approach for anonymizing faces while preserving facial expressions.},
+ note = {Just Accepted},
+ journal = {ACM Trans. Multimedia Comput. Commun. Appl.},
+ month = {jan},
+ keywords = {face anonymization, emotion recognition, data privacy, emotion preserving, facial landmarks}
+}
diff --git a/project/models/ganonymization/LICENSE b/project/models/ganonymization/LICENSE
new file mode 100644
index 0000000..3089b8d
--- /dev/null
+++ b/project/models/ganonymization/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2023 Chair of Human-Centered Artificial Intelligence, University of Augsburg
+
+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.
\ No newline at end of file
diff --git a/project/models/ganonymization/README.md b/project/models/ganonymization/README.md
new file mode 100644
index 0000000..36aae60
--- /dev/null
+++ b/project/models/ganonymization/README.md
@@ -0,0 +1,105 @@
+
+
+______________________________________________________________________
+# GANonymization
+
+#### A GAN-based Face Anonymization Framework for Preserving Emotional Expressions
+______________________________________________________________________
+
+[](https://github.com/hcmlab/GANonymization/actions/workflows/pylint.yml)
+
+[**Paper**](https://dl.acm.org/doi/10.1145/3641107)
+|
+[**Demo**](https://hcmlab.github.io/GANonymization/)
+
+
+
+> We introduce GANonymization, a novel face anonymization framework with facial expression-preserving abilities. Our approach is based on a high-level representation of a face which is synthesized into an anonymized version based on a generative adversarial network (GAN). The effectiveness of the approach was assessed by evaluating its performance in removing identifiable facial attributes to increase the anonymity of the given individual face. Additionally, the performance of preserving facial expressions was evaluated on several affect recognition datasets and outperformed the state-of-the-art method in most categories. Finally, our approach was analyzed for its ability to remove various facial traits, such as jewelry, hair color, and multiple others. Here, it demonstrated reliable performance in removing these attributes.
+
+## Quick Start
+
+The project was tested only with python version 3.8. Newer versions might work as well.
+
+### Installation
+
+1. Clone repository: `git clone https://github.com/hcmlab/GANonymization`.
+2. Install using `setup.py`:
+
+```bash
+pip install -e .
+```
+
+or:
+
+```bash
+pip install git+https://github.com/hcmlab/GANonymization
+```
+
+### Training
+
+You can either download a pre-trained GANonymization model:
+
+* [Trained for 25 epochs](https://mediastore.rz.uni-augsburg.de/get/NsLjQYey65/) (publication version)
+* [Trained for 50 epochs](https://mediastore.rz.uni-augsburg.de/get/Sfle_etB1D/) (demo version)
+
+Or train the GANonymization model yourself:
+
+```bash
+python main.py train_pix2pix --data_dir --log_dir --models_dir --output_dir