diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..c7d9f3332a950355d5a77d85000f05e6f45435ea --- /dev/null +++ b/.gitattributes @@ -0,0 +1,34 @@ +*.7z filter=lfs diff=lfs merge=lfs -text +*.arrow filter=lfs diff=lfs merge=lfs -text +*.bin filter=lfs diff=lfs merge=lfs -text +*.bz2 filter=lfs diff=lfs merge=lfs -text +*.ckpt filter=lfs diff=lfs merge=lfs -text +*.ftz filter=lfs diff=lfs merge=lfs -text +*.gz filter=lfs diff=lfs merge=lfs -text +*.h5 filter=lfs diff=lfs merge=lfs -text +*.joblib filter=lfs diff=lfs merge=lfs -text +*.lfs.* filter=lfs diff=lfs merge=lfs -text +*.mlmodel filter=lfs diff=lfs merge=lfs -text +*.model filter=lfs diff=lfs merge=lfs -text +*.msgpack filter=lfs diff=lfs merge=lfs -text +*.npy filter=lfs diff=lfs merge=lfs -text +*.npz filter=lfs diff=lfs merge=lfs -text +*.onnx filter=lfs diff=lfs merge=lfs -text +*.ot filter=lfs diff=lfs merge=lfs -text +*.parquet filter=lfs diff=lfs merge=lfs -text +*.pb filter=lfs diff=lfs merge=lfs -text +*.pickle filter=lfs diff=lfs merge=lfs -text +*.pkl filter=lfs diff=lfs merge=lfs -text +*.pt filter=lfs diff=lfs merge=lfs -text +*.pth filter=lfs diff=lfs merge=lfs -text +*.rar filter=lfs diff=lfs merge=lfs -text +*.safetensors filter=lfs diff=lfs merge=lfs -text +saved_model/**/* filter=lfs diff=lfs merge=lfs -text +*.tar.* filter=lfs diff=lfs merge=lfs -text +*.tflite filter=lfs diff=lfs merge=lfs -text +*.tgz filter=lfs diff=lfs merge=lfs -text +*.wasm filter=lfs diff=lfs merge=lfs -text +*.xz filter=lfs diff=lfs merge=lfs -text +*.zip filter=lfs diff=lfs merge=lfs -text +*.zst filter=lfs diff=lfs merge=lfs -text +*tfevents* filter=lfs diff=lfs merge=lfs -text diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..f749f52bb167f13909db3ebedf880bbdb96dc755 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.DS_Store +__pycache__ \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..c1c3390e6960692f4fc2dfa21a8298916db6eb22 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,177 @@ +## creative commons + +# Attribution-NonCommercial-ShareAlike 4.0 International + +Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. + +### Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. + +* __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors). + +* __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees). + +## Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. + +### Section 1 – Definitions. + +a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. + +b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. + +c. __BY-NC-SA Compatible License__ means a license listed at [creativecommons.org/compatiblelicenses](http://creativecommons.org/compatiblelicenses), approved by Creative Commons as essentially the equivalent of this Public License. + +d. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. + +e. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. + +f. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. + +g. __License Elements__ means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution, NonCommercial, and ShareAlike. + +h. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License. + +i. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. + +h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License. + +i. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange. + +j. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. + +k. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. + +l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. + +### Section 2 – Scope. + +a. ___License grant.___ + + 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: + + A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and + + B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only. + + 2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. + + 3. __Term.__ The term of this Public License is specified in Section 6(a). + + 4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. + + 5. __Downstream recipients.__ + + A. __Offer from the Licensor – Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. + + B. __Additional offer from the Licensor – Adapted Material.__ Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter’s License You apply. + + C. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. + + 6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). + +b. ___Other rights.___ + + 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this Public License. + + 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes. + +### Section 3 – License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the following conditions. + +a. ___Attribution.___ + + 1. If You Share the Licensed Material (including in modified form), You must: + + A. retain the following if it is supplied by the Licensor with the Licensed Material: + + i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of warranties; + + v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; + + B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and + + C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. + + 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. + +b. ___ShareAlike.___ + +In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply. + + 1. The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-NC-SA Compatible License. + + 2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material. + + 3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply. + +### Section 4 – Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: + +a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only; + +b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and + +c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. + +### Section 5 – Disclaimer of Warranties and Limitation of Liability. + +a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__ + +b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__ + +c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. + +### Section 6 – Term and Termination. + +a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. + +b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or + + 2. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or + + For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. + +c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. + +d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. + +### Section 7 – Other Terms and Conditions. + +a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. + +b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. + +### Section 8 – Interpretation. + +a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. + +b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. + +c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. + +d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. + +``` +Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. + +Creative Commons may be contacted at [creativecommons.org](http://creativecommons.org/). +``` diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b7caf1b8fce64354fd2ec662c8a0efc922ad5684 --- /dev/null +++ b/README.md @@ -0,0 +1,13 @@ +--- +title: DiverseSemanticImageEditing +emoji: 🐢 +colorFrom: red +colorTo: pink +sdk: gradio +sdk_version: 3.29.0 +app_file: app.py +pinned: false +license: unknown +--- + +Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/app.py b/app.py new file mode 100644 index 0000000000000000000000000000000000000000..88ca61919f65ea4199d050f10d96f18bf339b443 --- /dev/null +++ b/app.py @@ -0,0 +1,60 @@ +import gradio as gr +from utils import AppUtils +from app_inference import AppInference + +inference = AppInference() + +def process_image(input_id, image, label): + return inference.inference(int(input_id), AppUtils.get_examples()[int(input_id)][1], image["mask"], label) + +def preview(input_id, image, label): + return inference.preview(int(input_id), AppUtils.get_examples()[int(input_id)][1], image["mask"], label) + +def update_label_dropdown(input_id): + choices = AppUtils.get_labels(int(input_id)) + return gr.Dropdown.update(choices=choices, value=choices[0]) + +with gr.Blocks() as demo: + gr.Markdown( + """ +

Diverse Semantic Image Editing with Style Codes

+
+
Website
+
+
In this work, we propose a novel framework that can encode visible and partially visible objects with a novel mechanism to achieve consistency in the style encoding. + Here, we show our results for different images and label editing options.
+

How to Try

+
1. Select an image from the example list at the bottom.
+
2. Draw a mask on the input image.
+
3. Select a label from the dropdown on the "Choose Label" section. This label is used
+
for editing masked area. If you don't want to change label of the masked area, you can choose None.
+
4. Click to Preview button to see the edited instance map.
+
5. Click to Submit button to see the inference result.
+
Note: Our demo currently does not support to get inference from an uploaded image. Please use example images.
+ """) + with gr.Row(): + image_input = gr.Image(type="pil", shape=(256,256), label='Input', tool="sketch", value=AppUtils.get_examples()[0][1], scale=5).style(height=256) + inst_map_output = gr.Image(type="pil", shape=(256,256), label='Instance Map', value=AppUtils.get_examples()[0][1].replace("images", "colored"), scale=4).style(height=256) + image_output = gr.Image(type="pil", shape=(256,256), label='Output Image',scale=4).style(height=256) + + with gr.Row(): + input_id = gr.Textbox(label="Image ID", value=AppUtils.get_examples()[0][0], interactive=False, visible=False) + with gr.Column(scale=1, min_width=50): + label_dropdown = gr.Dropdown(AppUtils.get_labels(0), label="Choose Label", value=AppUtils.get_labels(0)[0]) + with gr.Column(scale=2, min_width=50): + with gr.Row(): + preview_button = gr.Button(value="Preview") + with gr.Row(): + submit_button = gr.Button(value="Submit") + + gr.Examples( + examples=AppUtils.get_examples(), + inputs=[input_id, image_input, inst_map_output], + outputs=[image_output], + fn=process_image, + ) + input_id.change(update_label_dropdown, inputs=input_id, outputs=label_dropdown ) + submit_button.click(process_image, inputs=[input_id, image_input, label_dropdown], outputs=image_output) + preview_button.click(preview, inputs=[input_id, image_input, label_dropdown], outputs=[inst_map_output]) + +demo.launch() \ No newline at end of file diff --git a/app_inference.py b/app_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..e8ac6d0b88eecd29259c01ef3adcd7fbcd9720ff --- /dev/null +++ b/app_inference.py @@ -0,0 +1,90 @@ +from PIL import Image +import numpy as np +from utils import AppUtils +import cv2 +from inference import start_inference + +class AppInference: + def __init__(self): + self.COLOR_MAP = {} + + def inference(self, input_id, img_path, mask, label): + AppUtils.clear() + self._input_id = input_id + self._handle_preprocess(img_path, mask, label) + return self._handle_model_inference() + + def _handle_preprocess(self, img_path, mask, label): + items = self._read_files(img_path) + self._items = items + mask = self._save_mask(items, mask) + if label != "None": + self._edit_maps(items, mask, label, save=True) + + def _handle_model_inference(self): + return start_inference() + + def preview(self, input_id, img_path, mask, label): + AppUtils.clear() + self._input_id = input_id + items = self._read_files(img_path) + mask = self._save_mask(items, mask) + if label != "None": + self._edit_maps(items, mask, label) + return self.generate_colored_image(items["inst_map"]) + + def generate_colored_image(self, semantic_map): + np.random.seed(256) + if len(semantic_map.shape) == 3: + semantic_map = semantic_map[:,:,1] + color_image = np.zeros((semantic_map.shape[0], semantic_map.shape[1], 3), dtype=np.uint8) + for row in range(semantic_map.shape[0]): + for col in range(semantic_map.shape[1]): + inst_id = semantic_map[row, col] + if self.COLOR_MAP.get(inst_id, None) is None: + self.COLOR_MAP[inst_id] = np.random.randint(256, size=(3,)) + color_image[row, col, :] = self.COLOR_MAP[inst_id] + return Image.fromarray(color_image) + + def _read_files(self, img_path): + dataset = img_path.split("/")[2] + items = { + "img_path": img_path, + "label_path": img_path.replace("images", "labels").replace("jpg", "png"), + "inst_map_path": img_path.replace("images", "inst_map").replace("jpg", "png"), + } + for file_path in items.values(): + AppUtils.copy_file(file_path, file_path.replace(dataset, "test_processed")) + items["dataset"] = dataset + base_img = cv2.imread(img_path) + base_img = cv2.cvtColor(base_img, cv2.COLOR_BGR2RGB) + base_lab = cv2.imread(items["label_path"], 0) + base_inst_map = Image.open(items["inst_map_path"]) + base_inst_map = np.array(base_inst_map, dtype=np.int32) + items.update( + { + "img": base_img, + "label": base_lab, + "inst_map": base_inst_map, + } + ) + return items + + def _save_mask(self, items, mask): + mask = np.array(mask)[:,:,0] + mask = mask.reshape((1,) + mask.shape).astype(np.float32) + save_path = items["img_path"].replace(items["dataset"], "test_processed").replace("images", "predefined_masks/type_0").replace("jpg", "png") + cv2.imwrite(save_path, mask[0]* 255) + return mask[0].astype(np.uint8) + + def _edit_maps(self, items, mask, label, save=False): + mask_path = items["img_path"].replace(items["dataset"], "test_processed").replace("images", "predefined_masks/type_0").replace("jpg", "png") + mask = cv2.imread(mask_path, 0) / 255 + target_pixels = mask == 1 + target_inst_id = AppUtils.get_inst_id(self._input_id, label) + items["inst_map"][target_pixels] = target_inst_id + items["label"][target_pixels] = (target_inst_id % 120) + im = Image.fromarray(items["inst_map"]).convert("I") + if save: + im.save(items["inst_map_path"].replace(items["dataset"], "test_processed")) + cv2.imwrite(items["label_path"].replace(items["dataset"], "test_processed"), items["label"]) diff --git a/checkpoints/best.pth b/checkpoints/best.pth new file mode 100644 index 0000000000000000000000000000000000000000..a537ddacba4f02dcdfb5f00591de38901c104f44 --- /dev/null +++ b/checkpoints/best.pth @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:46015fa60a7a07b16810d63eaf1f9617f9c93999da161b602728f74aba5d78ba +size 1135064038 diff --git a/checkpoints/config.yaml b/checkpoints/config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e6a24b810d7f808222aef736fe5b5a7be955e61b --- /dev/null +++ b/checkpoints/config.yaml @@ -0,0 +1,54 @@ +# basic setting +is_train: True +worker: 1 + +# train +# basic +batch_size: 3 +shuffle: true +max_epoch: 500 +epoch_start: 1 # the starting epoch count + +# optimizer +beta1: 0.5 +beta2: 0.999 +weight_decay: 0.0001 +lr: 0.0001 + +# print +visual_img_freq: 8000 +print_loss_freq: 1000 +save_epoch_freq: 20 + +# test +test_batch_size: 1 # must be one +results_root: 'results/' +test_freq: 5 + +# dataset +input_nc: 3 +mask_nc: 1 +output_nc: 3 +crop_size: 256 +crop: True +flip: True + +# generator +ngf: 32 +G_norm_type: in + +# discriminator +ndf: 64 +D_norm_type: batch +gan_mode: hinge + +# loss +no_ganFeat_loss: False +no_vgg_loss: False +lambda_L1: 1 +lambda_feat: 10 +lambda_vgg: 10 +lambda_gan: 1 + +# SEAN +style_length: 128 diff --git a/checkpoints/style_codes.pt b/checkpoints/style_codes.pt new file mode 100644 index 0000000000000000000000000000000000000000..1c4a75aa67e1fac6e32161e63955c0caace37704 --- /dev/null +++ b/checkpoints/style_codes.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9c2bd3e07e2a322bc515d6b72aed7c3b6edc605f9b241bedf8b698b1c9c36a58 +size 4211090 diff --git a/gradio_files/samples/flickr-landscape/colored/3736-9818172074_156d4682f3_o.png b/gradio_files/samples/flickr-landscape/colored/3736-9818172074_156d4682f3_o.png new file mode 100644 index 0000000000000000000000000000000000000000..a5b057673d58ca4a0ca60af28a1380bcd7b39e46 Binary files /dev/null and b/gradio_files/samples/flickr-landscape/colored/3736-9818172074_156d4682f3_o.png differ diff --git a/gradio_files/samples/flickr-landscape/colored/7343-9965972016_a822e52102_o.png b/gradio_files/samples/flickr-landscape/colored/7343-9965972016_a822e52102_o.png new file mode 100644 index 0000000000000000000000000000000000000000..9f43c5e0ce2affeb7fa1ccc2f4d95e90e7cf0a7a Binary files /dev/null and b/gradio_files/samples/flickr-landscape/colored/7343-9965972016_a822e52102_o.png differ diff --git a/gradio_files/samples/flickr-landscape/colored/7503-16108428460_622fcdb3ca_o.png b/gradio_files/samples/flickr-landscape/colored/7503-16108428460_622fcdb3ca_o.png new file mode 100644 index 0000000000000000000000000000000000000000..f3c6b6c188c2dde53f167023eedba4990c703baa Binary files /dev/null and b/gradio_files/samples/flickr-landscape/colored/7503-16108428460_622fcdb3ca_o.png differ diff --git a/gradio_files/samples/flickr-landscape/colored/7921-47167099321_02f96ba4f6_o.png b/gradio_files/samples/flickr-landscape/colored/7921-47167099321_02f96ba4f6_o.png new file mode 100644 index 0000000000000000000000000000000000000000..6c3a7178ae4da83c1d642376c884ce41b5508932 Binary files /dev/null and b/gradio_files/samples/flickr-landscape/colored/7921-47167099321_02f96ba4f6_o.png differ diff --git a/gradio_files/samples/flickr-landscape/colored/8016-7167270731_b9843b1072_o.png b/gradio_files/samples/flickr-landscape/colored/8016-7167270731_b9843b1072_o.png new file mode 100644 index 0000000000000000000000000000000000000000..4726adb1677f80976a79ea78249c4d198854c1ad Binary files /dev/null and b/gradio_files/samples/flickr-landscape/colored/8016-7167270731_b9843b1072_o.png differ diff --git a/gradio_files/samples/flickr-landscape/colored/8042-7987076838_05973d5ee8_o.png b/gradio_files/samples/flickr-landscape/colored/8042-7987076838_05973d5ee8_o.png new file mode 100644 index 0000000000000000000000000000000000000000..a70899fd88916d6e520918fdf8f4021ddf2a58db Binary files /dev/null and b/gradio_files/samples/flickr-landscape/colored/8042-7987076838_05973d5ee8_o.png differ diff --git a/gradio_files/samples/flickr-landscape/colored/832-41253531765_83c1767ba9_o.png b/gradio_files/samples/flickr-landscape/colored/832-41253531765_83c1767ba9_o.png new file mode 100644 index 0000000000000000000000000000000000000000..e9ae22ef12ab16c4fb0767bb9cd71bd99684f7df Binary files /dev/null and b/gradio_files/samples/flickr-landscape/colored/832-41253531765_83c1767ba9_o.png differ diff --git a/gradio_files/samples/flickr-landscape/images/3736-9818172074_156d4682f3_o.png b/gradio_files/samples/flickr-landscape/images/3736-9818172074_156d4682f3_o.png new file mode 100644 index 0000000000000000000000000000000000000000..1b197f83ccf6ef7b9b60b8561c5d051e5bb613ac Binary files /dev/null and b/gradio_files/samples/flickr-landscape/images/3736-9818172074_156d4682f3_o.png differ diff --git a/gradio_files/samples/flickr-landscape/images/7343-9965972016_a822e52102_o.png b/gradio_files/samples/flickr-landscape/images/7343-9965972016_a822e52102_o.png new file mode 100644 index 0000000000000000000000000000000000000000..e4d7538f052b85a6b5fd4cc4bd0b0157a64aaa4e Binary files /dev/null and b/gradio_files/samples/flickr-landscape/images/7343-9965972016_a822e52102_o.png differ diff --git a/gradio_files/samples/flickr-landscape/images/7503-16108428460_622fcdb3ca_o.png b/gradio_files/samples/flickr-landscape/images/7503-16108428460_622fcdb3ca_o.png new file mode 100644 index 0000000000000000000000000000000000000000..a74ee4c13f034f0066c73ea56418bd913a30758d Binary files /dev/null and b/gradio_files/samples/flickr-landscape/images/7503-16108428460_622fcdb3ca_o.png differ diff --git a/gradio_files/samples/flickr-landscape/images/7921-47167099321_02f96ba4f6_o.png b/gradio_files/samples/flickr-landscape/images/7921-47167099321_02f96ba4f6_o.png new file mode 100644 index 0000000000000000000000000000000000000000..53a51504f07ee489248ce7c20ef5b8aaa067c0b8 Binary files /dev/null and b/gradio_files/samples/flickr-landscape/images/7921-47167099321_02f96ba4f6_o.png differ diff --git a/gradio_files/samples/flickr-landscape/images/8016-7167270731_b9843b1072_o.png b/gradio_files/samples/flickr-landscape/images/8016-7167270731_b9843b1072_o.png new file mode 100644 index 0000000000000000000000000000000000000000..792545d51d76178419ba41d51d9ec3c037f633e2 Binary files /dev/null and b/gradio_files/samples/flickr-landscape/images/8016-7167270731_b9843b1072_o.png differ diff --git a/gradio_files/samples/flickr-landscape/images/8042-7987076838_05973d5ee8_o.png b/gradio_files/samples/flickr-landscape/images/8042-7987076838_05973d5ee8_o.png new file mode 100644 index 0000000000000000000000000000000000000000..ffd1476fb440ce6acbdc9a32e30f865331da1153 Binary files /dev/null and b/gradio_files/samples/flickr-landscape/images/8042-7987076838_05973d5ee8_o.png differ diff --git a/gradio_files/samples/flickr-landscape/images/832-41253531765_83c1767ba9_o.png b/gradio_files/samples/flickr-landscape/images/832-41253531765_83c1767ba9_o.png new file mode 100644 index 0000000000000000000000000000000000000000..4126933a7229cbb02a55e898b1caff5fb0f5ebf0 Binary files /dev/null and b/gradio_files/samples/flickr-landscape/images/832-41253531765_83c1767ba9_o.png differ diff --git a/gradio_files/samples/flickr-landscape/inst_map/3736-9818172074_156d4682f3_o.png b/gradio_files/samples/flickr-landscape/inst_map/3736-9818172074_156d4682f3_o.png new file mode 100644 index 0000000000000000000000000000000000000000..316d34fff3d42143b0c818303b9306df2b6351fc Binary files /dev/null and b/gradio_files/samples/flickr-landscape/inst_map/3736-9818172074_156d4682f3_o.png differ diff --git a/gradio_files/samples/flickr-landscape/inst_map/7343-9965972016_a822e52102_o.png b/gradio_files/samples/flickr-landscape/inst_map/7343-9965972016_a822e52102_o.png new file mode 100644 index 0000000000000000000000000000000000000000..d5523b2535e0514d910df5d0716390c80440a8de Binary files /dev/null and b/gradio_files/samples/flickr-landscape/inst_map/7343-9965972016_a822e52102_o.png differ diff --git a/gradio_files/samples/flickr-landscape/inst_map/7503-16108428460_622fcdb3ca_o.png b/gradio_files/samples/flickr-landscape/inst_map/7503-16108428460_622fcdb3ca_o.png new file mode 100644 index 0000000000000000000000000000000000000000..c0102d9443767cc2644fff9ad4d818032456c8cc Binary files /dev/null and b/gradio_files/samples/flickr-landscape/inst_map/7503-16108428460_622fcdb3ca_o.png differ diff --git a/gradio_files/samples/flickr-landscape/inst_map/7921-47167099321_02f96ba4f6_o.png b/gradio_files/samples/flickr-landscape/inst_map/7921-47167099321_02f96ba4f6_o.png new file mode 100644 index 0000000000000000000000000000000000000000..45107b8965325f30373f25ce2c247c7d669aae39 Binary files /dev/null and b/gradio_files/samples/flickr-landscape/inst_map/7921-47167099321_02f96ba4f6_o.png differ diff --git a/gradio_files/samples/flickr-landscape/inst_map/8016-7167270731_b9843b1072_o.png b/gradio_files/samples/flickr-landscape/inst_map/8016-7167270731_b9843b1072_o.png new file mode 100644 index 0000000000000000000000000000000000000000..4b14f4f89b30ddc104a375daf9708d049b23bced Binary files /dev/null and b/gradio_files/samples/flickr-landscape/inst_map/8016-7167270731_b9843b1072_o.png differ diff --git a/gradio_files/samples/flickr-landscape/inst_map/8042-7987076838_05973d5ee8_o.png b/gradio_files/samples/flickr-landscape/inst_map/8042-7987076838_05973d5ee8_o.png new file mode 100644 index 0000000000000000000000000000000000000000..6c9e2fb2ca3afa758535b5e1a8bd38652ab3e76c Binary files /dev/null and b/gradio_files/samples/flickr-landscape/inst_map/8042-7987076838_05973d5ee8_o.png differ diff --git a/gradio_files/samples/flickr-landscape/inst_map/832-41253531765_83c1767ba9_o.png b/gradio_files/samples/flickr-landscape/inst_map/832-41253531765_83c1767ba9_o.png new file mode 100644 index 0000000000000000000000000000000000000000..38bb6fd7092419cc06e14fde99dc5d70c31fadf5 Binary files /dev/null and b/gradio_files/samples/flickr-landscape/inst_map/832-41253531765_83c1767ba9_o.png differ diff --git a/gradio_files/samples/flickr-landscape/labels/3736-9818172074_156d4682f3_o.png b/gradio_files/samples/flickr-landscape/labels/3736-9818172074_156d4682f3_o.png new file mode 100644 index 0000000000000000000000000000000000000000..9cf376a34bb725fd645e5ad9fd7d9e0008f282f6 Binary files /dev/null and b/gradio_files/samples/flickr-landscape/labels/3736-9818172074_156d4682f3_o.png differ diff --git a/gradio_files/samples/flickr-landscape/labels/7343-9965972016_a822e52102_o.png b/gradio_files/samples/flickr-landscape/labels/7343-9965972016_a822e52102_o.png new file mode 100644 index 0000000000000000000000000000000000000000..d4494602503733f9c45baca199075edef9b7db52 Binary files /dev/null and b/gradio_files/samples/flickr-landscape/labels/7343-9965972016_a822e52102_o.png differ diff --git a/gradio_files/samples/flickr-landscape/labels/7503-16108428460_622fcdb3ca_o.png b/gradio_files/samples/flickr-landscape/labels/7503-16108428460_622fcdb3ca_o.png new file mode 100644 index 0000000000000000000000000000000000000000..c5be008c552a9890a07ac50f56ca1bd97220eda7 Binary files /dev/null and b/gradio_files/samples/flickr-landscape/labels/7503-16108428460_622fcdb3ca_o.png differ diff --git a/gradio_files/samples/flickr-landscape/labels/7921-47167099321_02f96ba4f6_o.png b/gradio_files/samples/flickr-landscape/labels/7921-47167099321_02f96ba4f6_o.png new file mode 100644 index 0000000000000000000000000000000000000000..82752ee0f36b118f361d29e04519d0319e79d3eb Binary files /dev/null and b/gradio_files/samples/flickr-landscape/labels/7921-47167099321_02f96ba4f6_o.png differ diff --git a/gradio_files/samples/flickr-landscape/labels/8016-7167270731_b9843b1072_o.png b/gradio_files/samples/flickr-landscape/labels/8016-7167270731_b9843b1072_o.png new file mode 100644 index 0000000000000000000000000000000000000000..1de527b7f50f6649a2a5f2e784b1b48884378416 Binary files /dev/null and b/gradio_files/samples/flickr-landscape/labels/8016-7167270731_b9843b1072_o.png differ diff --git a/gradio_files/samples/flickr-landscape/labels/8042-7987076838_05973d5ee8_o.png b/gradio_files/samples/flickr-landscape/labels/8042-7987076838_05973d5ee8_o.png new file mode 100644 index 0000000000000000000000000000000000000000..8a62da634dca7b331e5020f0e4e691049389a426 Binary files /dev/null and b/gradio_files/samples/flickr-landscape/labels/8042-7987076838_05973d5ee8_o.png differ diff --git a/gradio_files/samples/flickr-landscape/labels/832-41253531765_83c1767ba9_o.png b/gradio_files/samples/flickr-landscape/labels/832-41253531765_83c1767ba9_o.png new file mode 100644 index 0000000000000000000000000000000000000000..2f23ebf9c0e2f931d3633fda8acbcca1ed4ba43b Binary files /dev/null and b/gradio_files/samples/flickr-landscape/labels/832-41253531765_83c1767ba9_o.png differ diff --git a/gradio_files/samples/synthesized_image/result.png b/gradio_files/samples/synthesized_image/result.png new file mode 100644 index 0000000000000000000000000000000000000000..e1c1cfe6b409f69ba38a9259e761d647dc50c841 Binary files /dev/null and b/gradio_files/samples/synthesized_image/result.png differ diff --git a/gradio_files/samples/test_processed/images/4-5475575_a688fdf668_o.png b/gradio_files/samples/test_processed/images/4-5475575_a688fdf668_o.png new file mode 100644 index 0000000000000000000000000000000000000000..cccfc4304bcba54638ad3a8897ebf5ac308478d7 Binary files /dev/null and b/gradio_files/samples/test_processed/images/4-5475575_a688fdf668_o.png differ diff --git a/gradio_files/samples/test_processed/inst_map/4-5475575_a688fdf668_o.png b/gradio_files/samples/test_processed/inst_map/4-5475575_a688fdf668_o.png new file mode 100644 index 0000000000000000000000000000000000000000..e9908f199a1b5120be2f9ed9e0e247080c011ec4 Binary files /dev/null and b/gradio_files/samples/test_processed/inst_map/4-5475575_a688fdf668_o.png differ diff --git a/gradio_files/samples/test_processed/labels/4-5475575_a688fdf668_o.png b/gradio_files/samples/test_processed/labels/4-5475575_a688fdf668_o.png new file mode 100644 index 0000000000000000000000000000000000000000..2f7ba1fc61de0ae79a84b81f4193961e6d249d97 Binary files /dev/null and b/gradio_files/samples/test_processed/labels/4-5475575_a688fdf668_o.png differ diff --git a/gradio_files/samples/test_processed/predefined_masks/type_0/4-5475575_a688fdf668_o.png b/gradio_files/samples/test_processed/predefined_masks/type_0/4-5475575_a688fdf668_o.png new file mode 100644 index 0000000000000000000000000000000000000000..8ee866d976ea0e95a960ea405dc94d6e077760fc Binary files /dev/null and b/gradio_files/samples/test_processed/predefined_masks/type_0/4-5475575_a688fdf668_o.png differ diff --git a/inference.py b/inference.py new file mode 100644 index 0000000000000000000000000000000000000000..7262cd2e411a0e22fa684510bd73a86f668e9125 --- /dev/null +++ b/inference.py @@ -0,0 +1,48 @@ +from model.utils import get_config, tensor2im +from model.inference_handler import InferenceHandler +from model.dataset import Image_Editing_Dataset + +import torch +import cv2 + +from torch.utils.data import DataLoader + +def get_cfg(): + cfg = get_config("checkpoints/config.yaml") + + cfg['lab_dim'] = 151 + cfg['max_epoch'] = 500 + cfg['test_freq'] = 20 + + cfg["is_train"] = False + cfg["dataset_name"] = "flickr-landscape" + return cfg + +def get_inference_handler(cfg): + inference_handler = InferenceHandler(cfg) + inference_handler.eval() + inference_handler.load_checkpoint(ckpt_filename="checkpoints/best.pth") + return inference_handler + +def get_dataloader(cfg): + dataset_root = "gradio_files/samples" + dataset = Image_Editing_Dataset(cfg, dataset_root, split='test', dataset_name="flickr-landscape") + return DataLoader(dataset=dataset, batch_size=1, shuffle=False) + +def start_inference(): + cfg = get_cfg() + inference_handler = get_inference_handler(cfg) + dataloader = get_dataloader(cfg) + cached_codes = torch.load("checkpoints/style_codes.pt", map_location=torch.device("cpu")) + save_path = 'gradio_files/samples/synthesized_image/result.png' + with torch.no_grad(): + cfg['mask_type'] = '0' + for i, data in enumerate(dataloader): + inference_handler.set_input(data) + inference_handler.forward(cached_codes) + result = inference_handler.get_results() + cv2.imwrite(save_path, tensor2im(result)) + return save_path + +if __name__ == "__main__": + start_inference() diff --git a/model/dataset.py b/model/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..68575d3555a7277ed3f3e6c6f2fbc11a9d4ed8d0 --- /dev/null +++ b/model/dataset.py @@ -0,0 +1,65 @@ +import os +import cv2 +import math +import numpy as np +from torch.utils.data import Dataset +import os.path +import random +import torchvision.transforms as transforms +import torch +from PIL import Image, ImageDraw + + +class Image_Editing_Dataset(Dataset): + def __init__(self, cfg, dataset_root, split='test', dataset_name=''): + self.split = split + self.cfg = cfg + self.dataset_name = dataset_name + self.img_format = '.png' + + self.dir_img = os.path.join(dataset_root, 'test_processed', 'images') + self.dir_lab = os.path.join(dataset_root, 'test_processed', 'labels') + self.dir_ins = os.path.join(dataset_root, 'test_processed', 'inst_map') + name_list = os.listdir(self.dir_img) + self.name_list = [n[:-4] for n in name_list if n.endswith(self.img_format)] + self.name_list.sort() + self.predefined_mask_path = os.path.join(dataset_root, f'test_processed', 'predefined_masks') + + def __getitem__(self, index): + name = self.name_list[index] + # input data + img = cv2.imread(os.path.join(self.dir_img, name + '.png')) + lab = cv2.imread(os.path.join(self.dir_lab, name + '.png'), 0) + inst_map = Image.open(os.path.join(self.dir_ins, name + '.png')) + inst_map = np.array(inst_map, dtype=np.int32) + + assert len(inst_map.shape) == 2 + + img = get_transform(img) + lab = get_transform(lab, normalize=False) + lab = lab * 255.0 + + mask = cv2.imread(os.path.join(self.predefined_mask_path, 'type_0', name + '.png'), 0) / 255 + mask = mask.reshape((1,) + mask.shape).astype(np.float32) + + mask = torch.from_numpy(mask) + masked_img = img * (1. - mask) + + inst_map = inst_map.reshape((1,) + inst_map.shape).astype(np.float32) + inst_map = torch.from_numpy(inst_map) + + return {'img': img, 'masked_img': masked_img, 'lab': lab, 'mask': mask, 'inst_map': inst_map, 'name': name} + # 'mask_seam': mask_seam, + + def __len__(self): + """Return the total number of images in the dataset.""" + return len(self.name_list) + + +def get_transform(img, normalize=True): + transform_list = [] + + transform_list += [transforms.ToTensor()] + if normalize: + transform_list += [transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))] + return transforms.Compose(transform_list)(img) diff --git a/model/inference_handler.py b/model/inference_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..1b098117e91b9beebc474e507b6408bb1ab8b9f4 --- /dev/null +++ b/model/inference_handler.py @@ -0,0 +1,81 @@ +from model.networks.generator import Generator +from model.utils import weights_init +import torch +import torch.nn as nn +import torch.nn.functional as F +import os + +class InferenceHandler(nn.Module): + def __init__(self, cfg): + super().__init__() + # setting basic params + self.cfg = cfg + self.model_names = ['netG'] + + # Initiate the submodules and initialization params + self.netG = Generator(self.cfg) + + self.netG.apply(weights_init('gaussian')) + + self.FloatTensor = torch.cuda.FloatTensor if torch.cuda.is_available() \ + else torch.FloatTensor + self.ByteTensor = torch.cuda.ByteTensor if torch.cuda.is_available() \ + else torch.ByteTensor + + def set_input(self, input): + # scatter_ require .long() type + input['lab'] = input['lab'].long() + self.masked_img = input['masked_img'] # mask image + self.gt = input['img'] # real image + # self.img_know = input['img_know'].cuda() + self.mask = input['mask'] # mask image + self.lab = input['lab'] # label image + + self.name = input['name'] + + # create one-hot label map + lab_map = self.lab + bs, _, h, w = lab_map.size() + nc = self.cfg['lab_dim'] + input_label = self.FloatTensor(bs, nc, h, w).zero_() + self.segmap = input_label.scatter_(1, lab_map, 1.0) + # print(' segmap ',self.lab.shape) + + self.segmap = self.segmap * self.mask + + self.inst_map = input['inst_map'] + self.edge_map = self.get_edges(self.inst_map) + self.edge_map = self.edge_map * self.mask + + self.segmap_edge = torch.cat((self.segmap, self.edge_map), dim=1) + + self.segmap_G1 = F.interpolate(self.segmap, size=(64, 64), mode='nearest') + self.segmap_G2 = F.interpolate(self.segmap, size=(128, 128), mode='nearest') + self.segmap_G3 = self.segmap + + + def get_edges(self, t): + edge = torch.ByteTensor(t.size()).zero_() + edge[:,:,:,1:] = edge[:,:,:,1:] | (t[:,:,:,1:] != t[:,:,:,:-1]) + edge[:,:,:,:-1] = edge[:,:,:,:-1] | (t[:,:,:,1:] != t[:,:,:,:-1]) + edge[:,:,1:,:] = edge[:,:,1:,:] | (t[:,:,1:,:] != t[:,:,:-1,:]) + edge[:,:,:-1,:] = edge[:,:,:-1,:] | (t[:,:,1:,:] != t[:,:,:-1,:]) + + return edge.float() + + def forward(self, cached_codes): + gt_list, input_list, mask_fake_list, fake_list = self.netG(self.gt, self.masked_img, self.segmap_edge, self.inst_map, self.mask, cached_codes=cached_codes) + + self.gt_G1, self.gt_G2, self.gt_G3 = gt_list + self.input_G1, self.input_G2, self.input_G3 = input_list + self.mask_fake_G1, self.mask_fake_G2, self.mask_fake_G3 = mask_fake_list + self.fake_G1, self.fake_G2, self.fake_G3 = fake_list + + def get_results(self): + return self.mask_fake_G3 + + def load_checkpoint(self, ckpt_filename): + ckpt = torch.load(os.path.join(ckpt_filename), map_location=torch.device("cpu")) + for name in self.model_names: + net = getattr(self, name) + net.load_state_dict(ckpt[name]) diff --git a/model/networks/G1.py b/model/networks/G1.py new file mode 100644 index 0000000000000000000000000000000000000000..5698492936f349f8ad24aa82e938a84b2638dd1a --- /dev/null +++ b/model/networks/G1.py @@ -0,0 +1,60 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np +import functools +from .blocks import CondGatedConv2d, CondTransposeGatedConv2d, Conv2dBlock + +########################################## +class G1(nn.Module): + def __init__(self, cfg): + super(G1, self).__init__() + + input_nc = cfg['input_nc'] + ngf = cfg['ngf'] + output_nc = cfg['output_nc'] + lab_nc = cfg['lab_dim'] + 1 + g_norm = cfg['G_norm_type'] + + # Encoder layers + self.enc1 = CondGatedConv2d(input_nc, ngf, lab_nc, kernel_size=3, stride=1, padding=1, norm=g_norm, activation='lrelu') + self.enc2 = CondGatedConv2d(ngf, ngf * 2, lab_nc, kernel_size=3, stride=2, padding=1, norm=g_norm, activation='lrelu') + self.enc3 = CondGatedConv2d(ngf * 2, ngf * 4, lab_nc, kernel_size=3, stride=2, padding=1, norm=g_norm, activation='lrelu') + self.enc4 = CondGatedConv2d(ngf * 4, ngf * 4, lab_nc, kernel_size=3, stride=2, padding=1, norm=g_norm, activation='lrelu') + self.enc5 = CondGatedConv2d(ngf * 4, ngf * 8, lab_nc, kernel_size=3, stride=2, padding=1, norm=g_norm, activation='lrelu') + self.enc6 = CondGatedConv2d(ngf * 8, ngf * 8, lab_nc, kernel_size=3, stride=2, padding=1, norm=g_norm, activation='lrelu') + self.enc7 = CondGatedConv2d(ngf * 8, ngf * 16, lab_nc, kernel_size=3, stride=1, padding=1, dilation=1, + norm=g_norm, activation='lrelu') + + # Decoder layers + self.dec6 = CondTransposeGatedConv2d(ngf * 16 + ngf * 8, ngf * 8, lab_nc, kernel_size=3, stride=1, padding=1, norm=g_norm, + activation='lrelu', spade_norm=True, cfg=cfg) + self.dec5 = CondTransposeGatedConv2d(ngf * 8 + ngf * 4, ngf * 4, lab_nc, kernel_size=3, stride=1, padding=1, norm=g_norm, + activation='lrelu', spade_norm=True, cfg=cfg) + self.dec4 = CondTransposeGatedConv2d(ngf * 4 + ngf * 4, ngf * 2, lab_nc, kernel_size=3, stride=1, padding=1, norm=g_norm, + activation='lrelu', spade_norm=True, cfg=cfg) + self.dec3 = CondTransposeGatedConv2d(ngf * 2 + ngf * 2, ngf, lab_nc, kernel_size=3, stride=1, padding=1, norm=g_norm, + activation='lrelu', spade_norm=True, cfg=cfg) + self.dec2 = CondTransposeGatedConv2d(ngf, ngf, lab_nc, kernel_size=3, stride=1, padding=1, norm=g_norm, + activation='lrelu', spade_norm=True, cfg=cfg) + self.dec1 = Conv2dBlock(ngf, output_nc, kernel_size=3, stride=1, padding=1, norm='none', activation='tanh') + + # In this case, we have very flexible unet construction mode. + def forward(self, input, segmap, mask, style_codes): + # Encoder + e1 = self.enc1(input, segmap, mask) + e2 = self.enc2(e1, segmap, mask) + e3 = self.enc3(e2, segmap, mask) + e4 = self.enc4(e3, segmap, mask) + e5 = self.enc5(e4, segmap, mask) + e6 = self.enc6(e5, segmap, mask) + e7 = self.enc7(e6, segmap, mask) + + d6 = self.dec6(e7, segmap, mask, skip=e5, style_codes=style_codes) + d5 = self.dec5(d6, segmap, mask, skip=e4, style_codes=style_codes) + d4 = self.dec4(d5, segmap, mask, skip=e3, style_codes=style_codes) + d3 = self.dec3(d4, segmap, mask, skip=e2, style_codes=style_codes) + d2 = self.dec2(d3, segmap, mask, style_codes=style_codes) + d1 = self.dec1(d2) + + return d1 \ No newline at end of file diff --git a/model/networks/G2.py b/model/networks/G2.py new file mode 100644 index 0000000000000000000000000000000000000000..32e5547d050b1459ba104b92eb1c152a3d81f1f3 --- /dev/null +++ b/model/networks/G2.py @@ -0,0 +1,65 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np +import functools +from .blocks import CondGatedConv2d, CondTransposeGatedConv2d, Conv2dBlock + +########################################## +class G2(nn.Module): + def __init__(self, cfg): + super(G2, self).__init__() + + input_nc = cfg['input_nc'] + ngf = cfg['ngf'] + output_nc = cfg['output_nc'] + lab_nc = cfg['lab_dim'] + 1 + g_norm = cfg['G_norm_type'] + + # Encoder layers + self.enc1 = CondGatedConv2d(input_nc, ngf, lab_nc, kernel_size=3, stride=1, padding=1, norm=g_norm, activation='lrelu') + self.enc2 = CondGatedConv2d(ngf, ngf * 2, lab_nc, kernel_size=3, stride=2, padding=1, norm=g_norm, activation='lrelu') + self.enc3 = CondGatedConv2d(ngf * 2, ngf * 4, lab_nc, kernel_size=3, stride=2, padding=1, norm=g_norm, activation='lrelu') + self.enc4 = CondGatedConv2d(ngf * 4, ngf * 4, lab_nc, kernel_size=3, stride=2, padding=1, norm=g_norm, activation='lrelu') + self.enc5 = CondGatedConv2d(ngf * 4, ngf * 8, lab_nc, kernel_size=3, stride=2, padding=1, norm=g_norm, activation='lrelu') + self.enc6 = CondGatedConv2d(ngf * 8, ngf * 8, lab_nc, kernel_size=3, stride=2, padding=1, norm=g_norm, activation='lrelu') + self.enc7 = CondGatedConv2d(ngf * 8, ngf * 16, lab_nc, kernel_size=3, stride=2, padding=1, norm=g_norm, activation='lrelu') + self.enc8 = CondGatedConv2d(ngf * 16, ngf * 16, lab_nc, kernel_size=3, stride=1, padding=1, dilation=1, + norm=g_norm, activation='lrelu') + + # Decoder layers + self.dec7 = CondTransposeGatedConv2d(ngf * 16 + ngf * 8, ngf * 16, lab_nc, kernel_size=3, stride=1, padding=1, norm=g_norm, + activation='lrelu', spade_norm=True, cfg=cfg) + self.dec6 = CondTransposeGatedConv2d(ngf * 16 + ngf * 8, ngf * 8, lab_nc, kernel_size=3, stride=1, padding=1, norm=g_norm, + activation='lrelu', spade_norm=True, cfg=cfg) + self.dec5 = CondTransposeGatedConv2d(ngf * 8 + ngf * 4, ngf * 4, lab_nc, kernel_size=3, stride=1, padding=1, norm=g_norm, + activation='lrelu', spade_norm=True, cfg=cfg) + self.dec4 = CondTransposeGatedConv2d(ngf * 4 + ngf * 4, ngf * 2, lab_nc, kernel_size=3, stride=1, padding=1, norm=g_norm, + activation='lrelu', spade_norm=True, cfg=cfg) + self.dec3 = CondTransposeGatedConv2d(ngf * 2 + ngf * 2, ngf, lab_nc, kernel_size=3, stride=1, padding=1, norm=g_norm, + activation='lrelu', spade_norm=True, cfg=cfg) + self.dec2 = CondTransposeGatedConv2d(ngf, ngf, lab_nc, kernel_size=3, stride=1, padding=1, norm=g_norm, + activation='lrelu', spade_norm=True, cfg=cfg) + self.dec1 = Conv2dBlock(ngf, output_nc, kernel_size=3, stride=1, padding=1, norm='none', activation='tanh') + + # In this case, we have very flexible unet construction mode. + def forward(self, input, segmap, mask, style_codes): + # Encoder + e1 = self.enc1(input, segmap, mask) + e2 = self.enc2(e1, segmap, mask) + e3 = self.enc3(e2, segmap, mask) + e4 = self.enc4(e3, segmap, mask) + e5 = self.enc5(e4, segmap, mask) + e6 = self.enc6(e5, segmap, mask) + e7 = self.enc7(e6, segmap, mask) + e8 = self.enc8(e7, segmap, mask) + + d7 = self.dec7(e8, segmap, mask, skip=e6, style_codes=style_codes) + d6 = self.dec6(d7, segmap, mask, skip=e5, style_codes=style_codes) + d5 = self.dec5(d6, segmap, mask, skip=e4, style_codes=style_codes) + d4 = self.dec4(d5, segmap, mask, skip=e3, style_codes=style_codes) + d3 = self.dec3(d4, segmap, mask, skip=e2, style_codes=style_codes) + d2 = self.dec2(d3, segmap, mask, style_codes=style_codes) + d1 = self.dec1(d2) + + return d1 \ No newline at end of file diff --git a/model/networks/G3.py b/model/networks/G3.py new file mode 100644 index 0000000000000000000000000000000000000000..77e13bed4ef088ad3f60856b37c7b6f619ffc190 --- /dev/null +++ b/model/networks/G3.py @@ -0,0 +1,70 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np +import functools +from .blocks import CondGatedConv2d, CondTransposeGatedConv2d, Conv2dBlock + +########################################## +class G3(nn.Module): + def __init__(self, cfg): + super(G3, self).__init__() + + input_nc = cfg['input_nc'] + ngf = cfg['ngf'] + output_nc = cfg['output_nc'] + lab_nc = cfg['lab_dim'] + 1 + g_norm = cfg['G_norm_type'] + + # Encoder layers + self.enc1 = CondGatedConv2d(input_nc, ngf, lab_nc, kernel_size=3, stride=1, padding=1, norm=g_norm, activation='lrelu') + self.enc2 = CondGatedConv2d(ngf, ngf * 2, lab_nc, kernel_size=3, stride=2, padding=1, norm=g_norm, activation='lrelu') + self.enc3 = CondGatedConv2d(ngf * 2, ngf * 4, lab_nc, kernel_size=3, stride=2, padding=1, norm=g_norm, activation='lrelu') + self.enc4 = CondGatedConv2d(ngf * 4, ngf * 4, lab_nc, kernel_size=3, stride=2, padding=1, norm=g_norm, activation='lrelu') + self.enc5 = CondGatedConv2d(ngf * 4, ngf * 8, lab_nc, kernel_size=3, stride=2, padding=1, norm=g_norm, activation='lrelu') + self.enc6 = CondGatedConv2d(ngf * 8, ngf * 8, lab_nc, kernel_size=3, stride=2, padding=1, norm=g_norm, activation='lrelu') + self.enc7 = CondGatedConv2d(ngf * 8, ngf * 16, lab_nc, kernel_size=3, stride=2, padding=1, norm=g_norm, activation='lrelu') + self.enc8 = CondGatedConv2d(ngf * 16, ngf * 16, lab_nc, kernel_size=3, stride=2, padding=1, norm=g_norm, activation='lrelu') + self.enc9 = CondGatedConv2d(ngf * 16, ngf * 32, lab_nc, kernel_size=3, stride=1, padding=1, dilation=1, norm=g_norm, + activation='lrelu') + + # Decoder layers + self.dec8 = CondTransposeGatedConv2d(ngf * 32 + ngf * 16, ngf * 16, lab_nc, kernel_size=3, stride=1, padding=1, norm=g_norm, + activation='lrelu', spade_norm=True, cfg=cfg) + self.dec7 = CondTransposeGatedConv2d(ngf * 16 + ngf * 8, ngf * 8, lab_nc, kernel_size=3, stride=1, padding=1, norm=g_norm, + activation='lrelu', spade_norm=True, cfg=cfg) + self.dec6 = CondTransposeGatedConv2d(ngf * 8 + ngf * 8, ngf * 8, lab_nc, kernel_size=3, stride=1, padding=1, norm=g_norm, + activation='lrelu', spade_norm=True, cfg=cfg) + self.dec5 = CondTransposeGatedConv2d(ngf * 8 + ngf * 4, ngf * 4, lab_nc, kernel_size=3, stride=1, padding=1, norm=g_norm, + activation='lrelu', spade_norm=True, cfg=cfg) + self.dec4 = CondTransposeGatedConv2d(ngf * 4 + ngf * 4, ngf * 2, lab_nc, kernel_size=3, stride=1, padding=1, norm=g_norm, + activation='lrelu', spade_norm=True, cfg=cfg) + self.dec3 = CondTransposeGatedConv2d(ngf * 2 + ngf * 2, ngf, lab_nc, kernel_size=3, stride=1, padding=1, norm=g_norm, + activation='lrelu', spade_norm=True, cfg=cfg) + self.dec2 = CondTransposeGatedConv2d(ngf, ngf, lab_nc, kernel_size=3, stride=1, padding=1, norm=g_norm, + activation='lrelu', spade_norm=True, cfg=cfg) + self.dec1 = Conv2dBlock(ngf, output_nc, kernel_size=3, stride=1, padding=1, norm='none', activation='tanh') + + # In this case, we have very flexible unet construction mode. + def forward(self, input, segmap, mask, style_codes): + # Encoder + e1 = self.enc1(input, segmap, mask) + e2 = self.enc2(e1, segmap, mask) + e3 = self.enc3(e2, segmap, mask) + e4 = self.enc4(e3, segmap, mask) + e5 = self.enc5(e4, segmap, mask) + e6 = self.enc6(e5, segmap, mask) + e7 = self.enc7(e6, segmap, mask) + e8 = self.enc8(e7, segmap, mask) + e9 = self.enc9(e8, segmap, mask) + + d8 = self.dec8(e9, segmap, mask, skip=e7, style_codes=style_codes) + d7 = self.dec7(d8, segmap, mask, skip=e6, style_codes=style_codes) + d6 = self.dec6(d7, segmap, mask, skip=e5, style_codes=style_codes) + d5 = self.dec5(d6, segmap, mask, skip=e4, style_codes=style_codes) + d4 = self.dec4(d5, segmap, mask, skip=e3, style_codes=style_codes) + d3 = self.dec3(d4, segmap, mask, skip=e2, style_codes=style_codes) + d2 = self.dec2(d3, segmap, mask, style_codes=style_codes) + d1 = self.dec1(d2) + + return d1 \ No newline at end of file diff --git a/model/networks/__init__.py b/model/networks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/model/networks/base_network.py b/model/networks/base_network.py new file mode 100644 index 0000000000000000000000000000000000000000..f79189f3c4c9b0032ea5e8ec28c8915a9112a754 --- /dev/null +++ b/model/networks/base_network.py @@ -0,0 +1,59 @@ +""" +Copyright (C) 2019 NVIDIA Corporation. All rights reserved. +Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode). +""" + +import torch.nn as nn +from torch.nn import init + + +class BaseNetwork(nn.Module): + def __init__(self): + super(BaseNetwork, self).__init__() + + @staticmethod + def modify_commandline_options(parser, is_train): + return parser + + def print_network(self): + if isinstance(self, list): + self = self[0] + num_params = 0 + for param in self.parameters(): + num_params += param.numel() + print('Network [%s] was created. Total number of parameters: %.1f million. ' + 'To see the architecture, do print(network).' + % (type(self).__name__, num_params / 1000000)) + + def init_weights(self, init_type='normal', gain=0.02): + def init_func(m): + classname = m.__class__.__name__ + if classname.find('BatchNorm2d') != -1: + if hasattr(m, 'weight') and m.weight is not None: + init.normal_(m.weight.data, 1.0, gain) + if hasattr(m, 'bias') and m.bias is not None: + init.constant_(m.bias.data, 0.0) + elif hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1): + if init_type == 'normal': + init.normal_(m.weight.data, 0.0, gain) + elif init_type == 'xavier': + init.xavier_normal_(m.weight.data, gain=gain) + elif init_type == 'xavier_uniform': + init.xavier_uniform_(m.weight.data, gain=1.0) + elif init_type == 'kaiming': + init.kaiming_normal_(m.weight.data, a=0, mode='fan_in') + elif init_type == 'orthogonal': + init.orthogonal_(m.weight.data, gain=gain) + elif init_type == 'none': # uses pytorch's default init method + m.reset_parameters() + else: + raise NotImplementedError('initialization method [%s] is not implemented' % init_type) + if hasattr(m, 'bias') and m.bias is not None: + init.constant_(m.bias.data, 0.0) + + self.apply(init_func) + + # propagate to children + for m in self.children(): + if hasattr(m, 'init_weights'): + m.init_weights(init_type, gain) diff --git a/model/networks/blocks.py b/model/networks/blocks.py new file mode 100644 index 0000000000000000000000000000000000000000..d3cc7a6c4f7eef1693fae5b5598aec0082a6fbc3 --- /dev/null +++ b/model/networks/blocks.py @@ -0,0 +1,321 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.nn.utils.spectral_norm as spectral_norm +import torchvision + +class Conv2dBlock(nn.Module): + def __init__(self, input_dim, output_dim, kernel_size, stride, + padding=0, dilation=1, norm='in', activation='relu', pad_type='replicate'): + super(Conv2dBlock, self).__init__() + + self.use_bias = False + if norm == 'in': + self.use_bias = True + + # initialize padding + if pad_type == 'reflect': + self.pad = nn.ReflectionPad2d(padding) + elif pad_type == 'replicate': + self.pad = nn.ReplicationPad2d(padding) + elif pad_type == 'zero': + self.pad = nn.ZeroPad2d(padding) + else: + assert 0, "Unsupported padding type: {}".format(pad_type) + + # initialize normalization + norm_dim = output_dim + if norm == 'bn': + self.norm = nn.BatchNorm2d(norm_dim) + elif norm == 'in': + #self.norm = nn.InstanceNorm2d(norm_dim, track_running_stats=True) + self.norm = nn.InstanceNorm2d(norm_dim) + elif norm == 'none' or norm == 'sn': + self.norm = None + else: + assert 0, "Unsupported normalization: {}".format(norm) + + # initialize activation + if activation == 'relu': + self.activation = nn.ReLU(inplace=True) + elif activation == 'lrelu': + self.activation = nn.LeakyReLU(0.2, inplace=True) + elif activation == 'prelu': + self.activation = nn.PReLU() + elif activation == 'selu': + self.activation = nn.SELU(inplace=True) + elif activation == 'elu': + self.activation = nn.ELU() + elif activation == 'tanh': + self.activation = nn.Tanh() + elif activation == 'none': + self.activation = None + else: + assert 0, "Unsupported activation: {}".format(activation) + + # initialize convolution + if norm == 'sn': + self.conv = spectral_norm(nn.Conv2d(input_dim, output_dim, kernel_size, stride, padding=0, dilation=dilation, bias=self.use_bias)) + else: + self.conv = nn.Conv2d(input_dim, output_dim, kernel_size, stride, padding=0, dilation=dilation, bias=self.use_bias) + + def forward(self, x): + x = self.conv(self.pad(x)) + if self.norm: + x = self.norm(x) + if self.activation: + x = self.activation(x) + return x + + +class UpConv2dBlock(nn.Module): + def __init__(self, input_dim, output_dim, kernel_size, stride, + padding=0, norm='in', activation='relu', pad_type='replicate', up_mode='nearest'): + super(UpConv2dBlock, self).__init__() + + self.use_bias = False + if norm == 'IN': + self.use_bias = True + + self.up = nn.Upsample(scale_factor=2, mode=up_mode) + + # initialize padding + if pad_type == 'reflect': + self.pad = nn.ReflectionPad2d(padding) + elif pad_type == 'replicate': + self.pad = nn.ReplicationPad2d(padding) + elif pad_type == 'zero': + self.pad = nn.ZeroPad2d(padding) + else: + assert 0, "Unsupported padding type: {}".format(pad_type) + + # initialize normalization + norm_dim = output_dim + if norm == 'bn': + self.norm = nn.BatchNorm2d(norm_dim) + elif norm == 'in': + #self.norm = nn.InstanceNorm2d(norm_dim, track_running_stats=True) + self.norm = nn.InstanceNorm2d(norm_dim) + elif norm == 'none' or norm == 'sn': + self.norm = None + else: + assert 0, "Unsupported normalization: {}".format(norm) + + # initialize activation + if activation == 'relu': + self.activation = nn.ReLU(inplace=True) + elif activation == 'lrelu': + self.activation = nn.LeakyReLU(0.2, inplace=True) + elif activation == 'prelu': + self.activation = nn.PReLU() + elif activation == 'selu': + self.activation = nn.SELU(inplace=True) + elif activation == 'elu': + self.activation = nn.ELU() + elif activation == 'tanh': + self.activation = nn.Tanh() + elif activation == 'none': + self.activation = None + else: + assert 0, "Unsupported activation: {}".format(activation) + + # initialize convolution + if norm == 'sn': + self.conv = spectral_norm(nn.Conv2d(input_dim, output_dim, kernel_size, stride, bias=self.use_bias)) + else: + self.conv = nn.Conv2d(input_dim, output_dim, kernel_size, stride, bias=self.use_bias) + + def forward(self, x, skip=None): + x = self.up(x) + if skip is not None: + x = torch.cat((x, skip), dim=1) + x = self.conv(self.pad(x)) + if self.norm: + x = self.norm(x) + if self.activation: + x = self.activation(x) + return x + + +# VGG architecter, used for the perceptual loss using a pretrained VGG network +class VGG19(torch.nn.Module): + def __init__(self, requires_grad=False): + super().__init__() + vgg_pretrained_features = torchvision.models.vgg19(pretrained=True).features + self.slice1 = torch.nn.Sequential() + self.slice2 = torch.nn.Sequential() + self.slice3 = torch.nn.Sequential() + self.slice4 = torch.nn.Sequential() + self.slice5 = torch.nn.Sequential() + for x in range(2): + self.slice1.add_module(str(x), vgg_pretrained_features[x]) + for x in range(2, 7): + self.slice2.add_module(str(x), vgg_pretrained_features[x]) + for x in range(7, 12): + self.slice3.add_module(str(x), vgg_pretrained_features[x]) + for x in range(12, 21): + self.slice4.add_module(str(x), vgg_pretrained_features[x]) + for x in range(21, 30): + self.slice5.add_module(str(x), vgg_pretrained_features[x]) + if not requires_grad: + for param in self.parameters(): + param.requires_grad = False + + def forward(self, X): + h_relu1 = self.slice1(X) + h_relu2 = self.slice2(h_relu1) + h_relu3 = self.slice3(h_relu2) + h_relu4 = self.slice4(h_relu3) + h_relu5 = self.slice5(h_relu4) + out = [h_relu1, h_relu2, h_relu3, h_relu4, h_relu5] + return out + + + +#################################################################################################################### +class CondGatedConv2d(nn.Module): + def __init__(self, in_channels, out_channels, label_nc, kernel_size, stride=1, padding=0, dilation=1, pad_type='zero', + activation='elu', norm='none', sn=False, cfg=None, spade_norm=False): + super(CondGatedConv2d, self).__init__() + + self.out_channels = out_channels + self.spade_norm = spade_norm + # Initialize the padding scheme + if pad_type == 'reflect': + self.pad = nn.ReflectionPad2d(padding) + elif pad_type == 'replicate': + self.pad = nn.ReplicationPad2d(padding) + elif pad_type == 'zero': + self.pad = nn.ZeroPad2d(padding) + else: + assert 0, "Unsupported padding type: {}".format(pad_type) + + # Initialize the normalization type + if norm == 'bn': + self.norm = nn.BatchNorm2d(out_channels) + elif norm == 'in': + self.norm = nn.InstanceNorm2d(out_channels) + elif norm == 'ln': + self.norm = nn.LayerNorm(out_channels) + elif norm == 'none': + self.norm = None + else: + assert 0, "Unsupported normalization: {}".format(norm) + + # Initialize the activation funtion + if activation == 'relu': + self.activation = nn.ReLU(inplace=True) + elif activation == 'lrelu': + self.activation = nn.LeakyReLU(0.2, inplace=True) + elif activation == 'prelu': + self.activation = nn.PReLU() + elif activation == 'selu': + self.activation = nn.SELU(inplace=True) + elif activation == 'tanh': + self.activation = nn.Tanh() + elif activation == 'sigmoid': + self.activation = nn.Sigmoid() + elif activation == 'elu': + self.activation = nn.ELU(inplace=True) + elif activation == 'none': + self.activation = None + else: + assert 0, "Unsupported activation: {}".format(activation) + + # Initialize the convolution layers + if sn: + self.conv2d = spectral_norm( + nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding=0, dilation=dilation)) + # self.mask_conv2d = spectral_norm( + # nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding=0, dilation=dilation)) + else: + self.conv2d = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding=0, dilation=dilation) + # self.mask_conv2d = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding=0, dilation=dilation) + self.sigmoid = torch.nn.Sigmoid() + + ####### mod 1 ######## + # nhidden = out_channels // 2 + # nhidden = 128 + nhidden = 64 + self.mlp_shared = nn.Sequential( + nn.Conv2d(in_channels, nhidden, kernel_size=3, stride=stride, padding=1), + nn.ReLU() + ) + self.mlp_gamma = nn.Conv2d(nhidden, out_channels, kernel_size=3, padding=1) + self.mlp_beta = nn.Conv2d(nhidden, out_channels, kernel_size=3, padding=1) + + ####### mod 2 ######## + mlp_shared_in = label_nc + 1 + if self.spade_norm: + mlp_shared_in += cfg["style_length"] + self.mlp_shared_2 = nn.Sequential( + nn.Conv2d(mlp_shared_in, nhidden, kernel_size=3, stride=1, padding=1), + nn.ReLU() + ) + self.mlp_gamma_ctx_gamma = nn.Conv2d(nhidden, out_channels, kernel_size=3, padding=1) + self.mlp_beta_ctx_gamma = nn.Conv2d(nhidden, out_channels, kernel_size=3, padding=1) + + self.mlp_gamma_ctx_beta = nn.Conv2d(nhidden, out_channels, kernel_size=3, padding=1) + self.mlp_beta_ctx_beta = nn.Conv2d(nhidden, out_channels, kernel_size=3, padding=1) + + # self.conv_x = nn.Conv2d(in_channels, in_channels, kernel_size=1, padding=0) + + def forward(self, x, seg, mask, style_codes=None): + x_pad = self.pad(x) + + conv = self.conv2d(x_pad) + + if self.out_channels == 3: + return conv + + if self.norm: + normalized = self.norm(conv) + + ####### mod 2 ######## + seg = F.interpolate(seg, size=normalized.size()[2:], mode='nearest') + mask = F.interpolate(mask, size=normalized.size()[2:], mode='nearest') + concatted = torch.cat((seg, mask), dim=1) + if style_codes is not None: + style_codes = F.interpolate(style_codes, size=normalized.size()[2:], mode='nearest') + concatted = torch.cat((style_codes, concatted), dim=1) + ctx = self.mlp_shared_2(concatted) + gamma_ctx_gamma = self.mlp_gamma_ctx_gamma(ctx) + beta_ctx_gamma = self.mlp_beta_ctx_gamma(ctx) + gamma_ctx_beta = self.mlp_gamma_ctx_beta(ctx) + beta_ctx_beta = self.mlp_beta_ctx_beta(ctx) + + ####### mod 1 ######## + # x_conv = self.conv_x(x) + actv = self.mlp_shared(x) + gamma = self.mlp_gamma(actv) + beta = self.mlp_beta(actv) + # print(gamma_ctx_gamma.size()) + # print(beta_ctx_gamma.size()) + # print(gamma.size()) + + gamma = gamma * (1. + gamma_ctx_gamma) + beta_ctx_gamma + beta = beta * (1. + gamma_ctx_beta) + beta_ctx_beta + out_norm = normalized * (1. + gamma) + beta + + if self.activation: + out = self.activation(out_norm) + + return out + + +class CondTransposeGatedConv2d(nn.Module): + def __init__(self, in_channels, out_channels, label_nc, kernel_size, stride=1, padding=0, dilation=1, pad_type='zero', + activation='lrelu', norm='none', sn=True, scale_factor=2, spade_norm=False, cfg=None): + super(CondTransposeGatedConv2d, self).__init__() + # Initialize the conv scheme + self.scale_factor = scale_factor + self.gated_conv2d = CondGatedConv2d(in_channels, out_channels, label_nc, kernel_size, stride, padding, dilation, pad_type, + activation, norm, sn, cfg=cfg, spade_norm=spade_norm) + + def forward(self, x, seg, mask, skip=None, style_codes=None): + x = F.interpolate(x, scale_factor=self.scale_factor, mode='bilinear') + if skip is not None: + x = torch.cat((x, skip), dim=1) + x = self.gated_conv2d(x, seg, mask, style_codes=style_codes) + return x + diff --git a/model/networks/generator.py b/model/networks/generator.py new file mode 100644 index 0000000000000000000000000000000000000000..67abc7e84ef55773245c3456b1a73a0814db145f --- /dev/null +++ b/model/networks/generator.py @@ -0,0 +1,56 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np +import functools +from .G1 import G1 +from .G2 import G2 +from .G3 import G3 +from .zencoder import DeeperZencoder + +########################################## +class Generator(nn.Module): + def __init__(self, cfg): + super(Generator, self).__init__() + + self.G1 = G1(cfg) + self.G2 = G2(cfg) + self.G3 = G3(cfg) + self.zencoder = DeeperZencoder(cfg) + self.up = nn.Upsample(scale_factor=2, mode='bilinear') # 'nearest', 'bilinear' + + def forward(self, gt, input, segmap, inst_map, mask, cached_codes=None): + gt_G1 = F.interpolate(gt, size=(64, 64), mode='bilinear') + gt_G2 = F.interpolate(gt, size=(128, 128), mode='bilinear') + gt_G3 = F.interpolate(gt, size=(256, 256), mode='bilinear') + + style_codes = self.zencoder(input, segmap, 1.0 - mask, inst_map, cached_codes=cached_codes) + + input_G1 = F.interpolate(input, size=(64, 64), mode='bilinear') + fake_G1 = self.G1(input_G1, segmap, mask, style_codes) + mask_fake_G1 = self.masked_fake(gt_G1, fake_G1, mask) + input_G2 = self.next_img(gt_G2, fake_G1, mask) + + fake_G2 = self.G2(input_G2, segmap, mask, style_codes) + mask_fake_G2 = self.masked_fake(gt_G2, fake_G2, mask) + input_G3 = self.next_img(gt_G3, fake_G2, mask) + + fake_G3 = self.G3(input_G3, segmap, mask, style_codes) + mask_fake_G3 = self.masked_fake(gt_G3, fake_G3, mask) + + return [gt_G1, gt_G2, gt_G3], [input_G1, input_G2, input_G3], [mask_fake_G1, mask_fake_G2, mask_fake_G3], [fake_G1, fake_G2, fake_G3] + + def get_style_codes(self, input, segmap, inst_map, mask): + return self.zencoder.generate_style_codes(input, segmap, 1.0 - mask, inst_map) + + def masked_fake(self, img, fake, mask): + mask = F.interpolate(mask, size=fake.size()[2:], mode='nearest') + combined = mask * fake + (1. - mask) * img + return combined + + def next_img(self, img, prev_fake, mask): + fake = self.up(prev_fake) + mask = F.interpolate(mask, size=fake.size()[2:], mode='nearest') + combined = mask * fake + (1. - mask) * img + + return combined \ No newline at end of file diff --git a/model/networks/sync_batchnorm/__init__.py b/model/networks/sync_batchnorm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..84ef0a02ec3d1649a62052c65ef1c75e2eaeb5bb --- /dev/null +++ b/model/networks/sync_batchnorm/__init__.py @@ -0,0 +1,13 @@ +# -*- coding: utf-8 -*- +# File : __init__.py +# Author : Jiayuan Mao +# Email : maojiayuan@gmail.com +# Date : 27/01/2018 +# +# This file is part of Synchronized-BatchNorm-PyTorch. +# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch +# Distributed under MIT License. + +from .batchnorm import SynchronizedBatchNorm1d, SynchronizedBatchNorm2d, SynchronizedBatchNorm3d +from .batchnorm import convert_model +from .replicate import DataParallelWithCallback, patch_replication_callback diff --git a/model/networks/sync_batchnorm/batchnorm.py b/model/networks/sync_batchnorm/batchnorm.py new file mode 100644 index 0000000000000000000000000000000000000000..3e516aa6464211632d89862a6c57c520875c006c --- /dev/null +++ b/model/networks/sync_batchnorm/batchnorm.py @@ -0,0 +1,361 @@ +# -*- coding: utf-8 -*- +# File : batchnorm.py +# Author : Jiayuan Mao +# Email : maojiayuan@gmail.com +# Date : 27/01/2018 +# +# This file is part of Synchronized-BatchNorm-PyTorch. +# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch +# Distributed under MIT License. + +import collections + +import torch +import torch.nn.functional as F + +from torch.nn.modules.batchnorm import _BatchNorm +from torch.nn.parallel._functions import ReduceAddCoalesced, Broadcast + +from .comm import SyncMaster +from .replicate import DataParallelWithCallback + +__all__ = ['SynchronizedBatchNorm1d', 'SynchronizedBatchNorm2d', + 'SynchronizedBatchNorm3d', 'convert_model'] + + +def _sum_ft(tensor): + """sum over the first and last dimention""" + return tensor.sum(dim=0).sum(dim=-1) + + +def _unsqueeze_ft(tensor): + """add new dementions at the front and the tail""" + return tensor.unsqueeze(0).unsqueeze(-1) + + +_ChildMessage = collections.namedtuple('_ChildMessage', ['sum', 'ssum', 'sum_size']) +_MasterMessage = collections.namedtuple('_MasterMessage', ['sum', 'inv_std']) + + +class _SynchronizedBatchNorm(_BatchNorm): + def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True): + super(_SynchronizedBatchNorm, self).__init__(num_features, eps=eps, momentum=momentum, affine=affine) + + self._sync_master = SyncMaster(self._data_parallel_master) + + self._is_parallel = False + self._parallel_id = None + self._slave_pipe = None + + def forward(self, input): + # If it is not parallel computation or is in evaluation mode, use PyTorch's implementation. + if not (self._is_parallel and self.training): + return F.batch_norm( + input, self.running_mean, self.running_var, self.weight, self.bias, + self.training, self.momentum, self.eps) + + # Resize the input to (B, C, -1). + input_shape = input.size() + input = input.view(input.size(0), self.num_features, -1) + + # Compute the sum and square-sum. + sum_size = input.size(0) * input.size(2) + input_sum = _sum_ft(input) + input_ssum = _sum_ft(input ** 2) + + # Reduce-and-broadcast the statistics. + if self._parallel_id == 0: + mean, inv_std = self._sync_master.run_master(_ChildMessage(input_sum, input_ssum, sum_size)) + else: + mean, inv_std = self._slave_pipe.run_slave(_ChildMessage(input_sum, input_ssum, sum_size)) + + # Compute the output. + if self.affine: + # MJY:: Fuse the multiplication for speed. + output = (input - _unsqueeze_ft(mean)) * _unsqueeze_ft(inv_std * self.weight) + _unsqueeze_ft(self.bias) + else: + output = (input - _unsqueeze_ft(mean)) * _unsqueeze_ft(inv_std) + + # Reshape it. + return output.view(input_shape) + + def __data_parallel_replicate__(self, ctx, copy_id): + self._is_parallel = True + self._parallel_id = copy_id + + # parallel_id == 0 means master device. + if self._parallel_id == 0: + ctx.sync_master = self._sync_master + else: + self._slave_pipe = ctx.sync_master.register_slave(copy_id) + + def _data_parallel_master(self, intermediates): + """Reduce the sum and square-sum, compute the statistics, and broadcast it.""" + + # Always using same "device order" makes the ReduceAdd operation faster. + # Thanks to:: Tete Xiao (http://tetexiao.com/) + intermediates = sorted(intermediates, key=lambda i: i[1].sum.get_device()) + + to_reduce = [i[1][:2] for i in intermediates] + to_reduce = [j for i in to_reduce for j in i] # flatten + target_gpus = [i[1].sum.get_device() for i in intermediates] + + sum_size = sum([i[1].sum_size for i in intermediates]) + sum_, ssum = ReduceAddCoalesced.apply(target_gpus[0], 2, *to_reduce) + mean, inv_std = self._compute_mean_std(sum_, ssum, sum_size) + + broadcasted = Broadcast.apply(target_gpus, mean, inv_std) + + outputs = [] + for i, rec in enumerate(intermediates): + outputs.append((rec[0], _MasterMessage(*broadcasted[i*2:i*2+2]))) + + return outputs + + def _compute_mean_std(self, sum_, ssum, size): + """Compute the mean and standard-deviation with sum and square-sum. This method + also maintains the moving average on the master device.""" + assert size > 1, 'BatchNorm computes unbiased standard-deviation, which requires size > 1.' + mean = sum_ / size + sumvar = ssum - sum_ * mean + unbias_var = sumvar / (size - 1) + bias_var = sumvar / size + + self.running_mean = (1 - self.momentum) * self.running_mean + self.momentum * mean.data + self.running_var = (1 - self.momentum) * self.running_var + self.momentum * unbias_var.data + + return mean, bias_var.clamp(self.eps) ** -0.5 + + +class SynchronizedBatchNorm1d(_SynchronizedBatchNorm): + r"""Applies Synchronized Batch Normalization over a 2d or 3d input that is seen as a + mini-batch. + + .. math:: + + y = \frac{x - mean[x]}{ \sqrt{Var[x] + \epsilon}} * gamma + beta + + This module differs from the built-in PyTorch BatchNorm1d as the mean and + standard-deviation are reduced across all devices during training. + + For example, when one uses `nn.DataParallel` to wrap the network during + training, PyTorch's implementation normalize the tensor on each device using + the statistics only on that device, which accelerated the computation and + is also easy to implement, but the statistics might be inaccurate. + Instead, in this synchronized version, the statistics will be computed + over all training samples distributed on multiple devices. + + Note that, for one-GPU or CPU-only case, this module behaves exactly same + as the built-in PyTorch implementation. + + The mean and standard-deviation are calculated per-dimension over + the mini-batches and gamma and beta are learnable parameter vectors + of size C (where C is the input size). + + During training, this layer keeps a running estimate of its computed mean + and variance. The running sum is kept with a default momentum of 0.1. + + During evaluation, this running mean/variance is used for normalization. + + Because the BatchNorm is done over the `C` dimension, computing statistics + on `(N, L)` slices, it's common terminology to call this Temporal BatchNorm + + Args: + num_features: num_features from an expected input of size + `batch_size x num_features [x width]` + eps: a value added to the denominator for numerical stability. + Default: 1e-5 + momentum: the value used for the running_mean and running_var + computation. Default: 0.1 + affine: a boolean value that when set to ``True``, gives the layer learnable + affine parameters. Default: ``True`` + + Shape: + - Input: :math:`(N, C)` or :math:`(N, C, L)` + - Output: :math:`(N, C)` or :math:`(N, C, L)` (same shape as input) + + Examples: + >>> # With Learnable Parameters + >>> m = SynchronizedBatchNorm1d(100) + >>> # Without Learnable Parameters + >>> m = SynchronizedBatchNorm1d(100, affine=False) + >>> input = torch.autograd.Variable(torch.randn(20, 100)) + >>> output = m(input) + """ + + def _check_input_dim(self, input): + if input.dim() != 2 and input.dim() != 3: + raise ValueError('expected 2D or 3D input (got {}D input)' + .format(input.dim())) + super(SynchronizedBatchNorm1d, self)._check_input_dim(input) + + +class SynchronizedBatchNorm2d(_SynchronizedBatchNorm): + r"""Applies Batch Normalization over a 4d input that is seen as a mini-batch + of 3d inputs + + .. math:: + + y = \frac{x - mean[x]}{ \sqrt{Var[x] + \epsilon}} * gamma + beta + + This module differs from the built-in PyTorch BatchNorm2d as the mean and + standard-deviation are reduced across all devices during training. + + For example, when one uses `nn.DataParallel` to wrap the network during + training, PyTorch's implementation normalize the tensor on each device using + the statistics only on that device, which accelerated the computation and + is also easy to implement, but the statistics might be inaccurate. + Instead, in this synchronized version, the statistics will be computed + over all training samples distributed on multiple devices. + + Note that, for one-GPU or CPU-only case, this module behaves exactly same + as the built-in PyTorch implementation. + + The mean and standard-deviation are calculated per-dimension over + the mini-batches and gamma and beta are learnable parameter vectors + of size C (where C is the input size). + + During training, this layer keeps a running estimate of its computed mean + and variance. The running sum is kept with a default momentum of 0.1. + + During evaluation, this running mean/variance is used for normalization. + + Because the BatchNorm is done over the `C` dimension, computing statistics + on `(N, H, W)` slices, it's common terminology to call this Spatial BatchNorm + + Args: + num_features: num_features from an expected input of + size batch_size x num_features x height x width + eps: a value added to the denominator for numerical stability. + Default: 1e-5 + momentum: the value used for the running_mean and running_var + computation. Default: 0.1 + affine: a boolean value that when set to ``True``, gives the layer learnable + affine parameters. Default: ``True`` + + Shape: + - Input: :math:`(N, C, H, W)` + - Output: :math:`(N, C, H, W)` (same shape as input) + + Examples: + >>> # With Learnable Parameters + >>> m = SynchronizedBatchNorm2d(100) + >>> # Without Learnable Parameters + >>> m = SynchronizedBatchNorm2d(100, affine=False) + >>> input = torch.autograd.Variable(torch.randn(20, 100, 35, 45)) + >>> output = m(input) + """ + + def _check_input_dim(self, input): + if input.dim() != 4: + raise ValueError('expected 4D input (got {}D input)' + .format(input.dim())) + super(SynchronizedBatchNorm2d, self)._check_input_dim(input) + + +class SynchronizedBatchNorm3d(_SynchronizedBatchNorm): + r"""Applies Batch Normalization over a 5d input that is seen as a mini-batch + of 4d inputs + + .. math:: + + y = \frac{x - mean[x]}{ \sqrt{Var[x] + \epsilon}} * gamma + beta + + This module differs from the built-in PyTorch BatchNorm3d as the mean and + standard-deviation are reduced across all devices during training. + + For example, when one uses `nn.DataParallel` to wrap the network during + training, PyTorch's implementation normalize the tensor on each device using + the statistics only on that device, which accelerated the computation and + is also easy to implement, but the statistics might be inaccurate. + Instead, in this synchronized version, the statistics will be computed + over all training samples distributed on multiple devices. + + Note that, for one-GPU or CPU-only case, this module behaves exactly same + as the built-in PyTorch implementation. + + The mean and standard-deviation are calculated per-dimension over + the mini-batches and gamma and beta are learnable parameter vectors + of size C (where C is the input size). + + During training, this layer keeps a running estimate of its computed mean + and variance. The running sum is kept with a default momentum of 0.1. + + During evaluation, this running mean/variance is used for normalization. + + Because the BatchNorm is done over the `C` dimension, computing statistics + on `(N, D, H, W)` slices, it's common terminology to call this Volumetric BatchNorm + or Spatio-temporal BatchNorm + + Args: + num_features: num_features from an expected input of + size batch_size x num_features x depth x height x width + eps: a value added to the denominator for numerical stability. + Default: 1e-5 + momentum: the value used for the running_mean and running_var + computation. Default: 0.1 + affine: a boolean value that when set to ``True``, gives the layer learnable + affine parameters. Default: ``True`` + + Shape: + - Input: :math:`(N, C, D, H, W)` + - Output: :math:`(N, C, D, H, W)` (same shape as input) + + Examples: + >>> # With Learnable Parameters + >>> m = SynchronizedBatchNorm3d(100) + >>> # Without Learnable Parameters + >>> m = SynchronizedBatchNorm3d(100, affine=False) + >>> input = torch.autograd.Variable(torch.randn(20, 100, 35, 45, 10)) + >>> output = m(input) + """ + + def _check_input_dim(self, input): + if input.dim() != 5: + raise ValueError('expected 5D input (got {}D input)' + .format(input.dim())) + super(SynchronizedBatchNorm3d, self)._check_input_dim(input) + + +def convert_model(module): + """Traverse the input module and its child recursively + and replace all instance of torch.nn.modules.batchnorm.BatchNorm*N*d + to SynchronizedBatchNorm*N*d + + Args: + module: the input module needs to be convert to SyncBN model + + Examples: + >>> import torch.nn as nn + >>> import torchvision + >>> # m is a standard pytorch model + >>> m = torchvision.models.resnet18(True) + >>> m = nn.DataParallel(m) + >>> # after convert, m is using SyncBN + >>> m = convert_model(m) + """ + if isinstance(module, torch.nn.DataParallel): + mod = module.module + mod = convert_model(mod) + mod = DataParallelWithCallback(mod) + return mod + + mod = module + for pth_module, sync_module in zip([torch.nn.modules.batchnorm.BatchNorm1d, + torch.nn.modules.batchnorm.BatchNorm2d, + torch.nn.modules.batchnorm.BatchNorm3d], + [SynchronizedBatchNorm1d, + SynchronizedBatchNorm2d, + SynchronizedBatchNorm3d]): + if isinstance(module, pth_module): + mod = sync_module(module.num_features, module.eps, module.momentum, module.affine) + mod.running_mean = module.running_mean + mod.running_var = module.running_var + if module.affine: + mod.weight.data = module.weight.data.clone().detach() + mod.bias.data = module.bias.data.clone().detach() + + for name, child in module.named_children(): + mod.add_module(name, convert_model(child)) + + return mod diff --git a/model/networks/sync_batchnorm/batchnorm_reimpl.py b/model/networks/sync_batchnorm/batchnorm_reimpl.py new file mode 100644 index 0000000000000000000000000000000000000000..7afcdaff9c56d7ac9c487f2dbe61fe6cb9c353a0 --- /dev/null +++ b/model/networks/sync_batchnorm/batchnorm_reimpl.py @@ -0,0 +1,74 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# File : batchnorm_reimpl.py +# Author : acgtyrant +# Date : 11/01/2018 +# +# This file is part of Synchronized-BatchNorm-PyTorch. +# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch +# Distributed under MIT License. + +import torch +import torch.nn as nn +import torch.nn.init as init + +__all__ = ['BatchNormReimpl'] + + +class BatchNorm2dReimpl(nn.Module): + """ + A re-implementation of batch normalization, used for testing the numerical + stability. + + Author: acgtyrant + See also: + https://github.com/vacancy/Synchronized-BatchNorm-PyTorch/issues/14 + """ + def __init__(self, num_features, eps=1e-5, momentum=0.1): + super().__init__() + + self.num_features = num_features + self.eps = eps + self.momentum = momentum + self.weight = nn.Parameter(torch.empty(num_features)) + self.bias = nn.Parameter(torch.empty(num_features)) + self.register_buffer('running_mean', torch.zeros(num_features)) + self.register_buffer('running_var', torch.ones(num_features)) + self.reset_parameters() + + def reset_running_stats(self): + self.running_mean.zero_() + self.running_var.fill_(1) + + def reset_parameters(self): + self.reset_running_stats() + init.uniform_(self.weight) + init.zeros_(self.bias) + + def forward(self, input_): + batchsize, channels, height, width = input_.size() + numel = batchsize * height * width + input_ = input_.permute(1, 0, 2, 3).contiguous().view(channels, numel) + sum_ = input_.sum(1) + sum_of_square = input_.pow(2).sum(1) + mean = sum_ / numel + sumvar = sum_of_square - sum_ * mean + + self.running_mean = ( + (1 - self.momentum) * self.running_mean + + self.momentum * mean.detach() + ) + unbias_var = sumvar / (numel - 1) + self.running_var = ( + (1 - self.momentum) * self.running_var + + self.momentum * unbias_var.detach() + ) + + bias_var = sumvar / numel + inv_std = 1 / (bias_var + self.eps).pow(0.5) + output = ( + (input_ - mean.unsqueeze(1)) * inv_std.unsqueeze(1) * + self.weight.unsqueeze(1) + self.bias.unsqueeze(1)) + + return output.view(channels, batchsize, height, width).permute(1, 0, 2, 3).contiguous() + diff --git a/model/networks/sync_batchnorm/comm.py b/model/networks/sync_batchnorm/comm.py new file mode 100644 index 0000000000000000000000000000000000000000..922f8c4a3adaa9b32fdcaef09583be03b0d7eb2b --- /dev/null +++ b/model/networks/sync_batchnorm/comm.py @@ -0,0 +1,137 @@ +# -*- coding: utf-8 -*- +# File : comm.py +# Author : Jiayuan Mao +# Email : maojiayuan@gmail.com +# Date : 27/01/2018 +# +# This file is part of Synchronized-BatchNorm-PyTorch. +# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch +# Distributed under MIT License. + +import queue +import collections +import threading + +__all__ = ['FutureResult', 'SlavePipe', 'SyncMaster'] + + +class FutureResult(object): + """A thread-safe future implementation. Used only as one-to-one pipe.""" + + def __init__(self): + self._result = None + self._lock = threading.Lock() + self._cond = threading.Condition(self._lock) + + def put(self, result): + with self._lock: + assert self._result is None, 'Previous result has\'t been fetched.' + self._result = result + self._cond.notify() + + def get(self): + with self._lock: + if self._result is None: + self._cond.wait() + + res = self._result + self._result = None + return res + + +_MasterRegistry = collections.namedtuple('MasterRegistry', ['result']) +_SlavePipeBase = collections.namedtuple('_SlavePipeBase', ['identifier', 'queue', 'result']) + + +class SlavePipe(_SlavePipeBase): + """Pipe for master-slave communication.""" + + def run_slave(self, msg): + self.queue.put((self.identifier, msg)) + ret = self.result.get() + self.queue.put(True) + return ret + + +class SyncMaster(object): + """An abstract `SyncMaster` object. + + - During the replication, as the data parallel will trigger an callback of each module, all slave devices should + call `register(id)` and obtain an `SlavePipe` to communicate with the master. + - During the forward pass, master device invokes `run_master`, all messages from slave devices will be collected, + and passed to a registered callback. + - After receiving the messages, the master device should gather the information and determine to message passed + back to each slave devices. + """ + + def __init__(self, master_callback): + """ + + Args: + master_callback: a callback to be invoked after having collected messages from slave devices. + """ + self._master_callback = master_callback + self._queue = queue.Queue() + self._registry = collections.OrderedDict() + self._activated = False + + def __getstate__(self): + return {'master_callback': self._master_callback} + + def __setstate__(self, state): + self.__init__(state['master_callback']) + + def register_slave(self, identifier): + """ + Register an slave device. + + Args: + identifier: an identifier, usually is the device id. + + Returns: a `SlavePipe` object which can be used to communicate with the master device. + + """ + if self._activated: + assert self._queue.empty(), 'Queue is not clean before next initialization.' + self._activated = False + self._registry.clear() + future = FutureResult() + self._registry[identifier] = _MasterRegistry(future) + return SlavePipe(identifier, self._queue, future) + + def run_master(self, master_msg): + """ + Main entry for the master device in each forward pass. + The messages were first collected from each devices (including the master device), and then + an callback will be invoked to compute the message to be sent back to each devices + (including the master device). + + Args: + master_msg: the message that the master want to send to itself. This will be placed as the first + message when calling `master_callback`. For detailed usage, see `_SynchronizedBatchNorm` for an example. + + Returns: the message to be sent back to the master device. + + """ + self._activated = True + + intermediates = [(0, master_msg)] + for i in range(self.nr_slaves): + intermediates.append(self._queue.get()) + + results = self._master_callback(intermediates) + assert results[0][0] == 0, 'The first result should belongs to the master.' + + for i, res in results: + if i == 0: + continue + self._registry[i].result.put(res) + + for i in range(self.nr_slaves): + assert self._queue.get() is True + + return results[0][1] + + @property + def nr_slaves(self): + return len(self._registry) diff --git a/model/networks/sync_batchnorm/replicate.py b/model/networks/sync_batchnorm/replicate.py new file mode 100644 index 0000000000000000000000000000000000000000..b71c7b8ed51a1d6c55b1f753bdd8d90bad79bd06 --- /dev/null +++ b/model/networks/sync_batchnorm/replicate.py @@ -0,0 +1,94 @@ +# -*- coding: utf-8 -*- +# File : replicate.py +# Author : Jiayuan Mao +# Email : maojiayuan@gmail.com +# Date : 27/01/2018 +# +# This file is part of Synchronized-BatchNorm-PyTorch. +# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch +# Distributed under MIT License. + +import functools + +from torch.nn.parallel.data_parallel import DataParallel + +__all__ = [ + 'CallbackContext', + 'execute_replication_callbacks', + 'DataParallelWithCallback', + 'patch_replication_callback' +] + + +class CallbackContext(object): + pass + + +def execute_replication_callbacks(modules): + """ + Execute an replication callback `__data_parallel_replicate__` on each module created by original replication. + + The callback will be invoked with arguments `__data_parallel_replicate__(ctx, copy_id)` + + Note that, as all modules are isomorphism, we assign each sub-module with a context + (shared among multiple copies of this module on different devices). + Through this context, different copies can share some information. + + We guarantee that the callback on the master copy (the first copy) will be called ahead of calling the callback + of any slave copies. + """ + master_copy = modules[0] + nr_modules = len(list(master_copy.modules())) + ctxs = [CallbackContext() for _ in range(nr_modules)] + + for i, module in enumerate(modules): + for j, m in enumerate(module.modules()): + if hasattr(m, '__data_parallel_replicate__'): + m.__data_parallel_replicate__(ctxs[j], i) + + +class DataParallelWithCallback(DataParallel): + """ + Data Parallel with a replication callback. + + An replication callback `__data_parallel_replicate__` of each module will be invoked after being created by + original `replicate` function. + The callback will be invoked with arguments `__data_parallel_replicate__(ctx, copy_id)` + + Examples: + > sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False) + > sync_bn = DataParallelWithCallback(sync_bn, device_ids=[0, 1]) + # sync_bn.__data_parallel_replicate__ will be invoked. + """ + + def replicate(self, module, device_ids): + modules = super(DataParallelWithCallback, self).replicate(module, device_ids) + execute_replication_callbacks(modules) + return modules + + +def patch_replication_callback(data_parallel): + """ + Monkey-patch an existing `DataParallel` object. Add the replication callback. + Useful when you have customized `DataParallel` implementation. + + Examples: + > sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False) + > sync_bn = DataParallel(sync_bn, device_ids=[0, 1]) + > patch_replication_callback(sync_bn) + # this is equivalent to + > sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False) + > sync_bn = DataParallelWithCallback(sync_bn, device_ids=[0, 1]) + """ + + assert isinstance(data_parallel, DataParallel) + + old_replicate = data_parallel.replicate + + @functools.wraps(old_replicate) + def new_replicate(module, device_ids): + modules = old_replicate(module, device_ids) + execute_replication_callbacks(modules) + return modules + + data_parallel.replicate = new_replicate diff --git a/model/networks/sync_batchnorm/unittest.py b/model/networks/sync_batchnorm/unittest.py new file mode 100644 index 0000000000000000000000000000000000000000..bed56f1caa929ac3e9a57c583f8d3e42624f58be --- /dev/null +++ b/model/networks/sync_batchnorm/unittest.py @@ -0,0 +1,29 @@ +# -*- coding: utf-8 -*- +# File : unittest.py +# Author : Jiayuan Mao +# Email : maojiayuan@gmail.com +# Date : 27/01/2018 +# +# This file is part of Synchronized-BatchNorm-PyTorch. +# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch +# Distributed under MIT License. + +import unittest +import torch + + +class TorchTestCase(unittest.TestCase): + def assertTensorClose(self, x, y): + adiff = float((x - y).abs().max()) + if (y == 0).all(): + rdiff = 'NaN' + else: + rdiff = float((adiff / y).abs().max()) + + message = ( + 'Tensor close check failed\n' + 'adiff={}\n' + 'rdiff={}\n' + ).format(adiff, rdiff) + self.assertTrue(torch.allclose(x, y), message) + diff --git a/model/networks/zencoder.py b/model/networks/zencoder.py new file mode 100644 index 0000000000000000000000000000000000000000..43b656139872e1a3b75e77219dc6a73b1b0d1758 --- /dev/null +++ b/model/networks/zencoder.py @@ -0,0 +1,114 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +from .base_network import BaseNetwork +import random +from .blocks import Conv2dBlock + +def inst_id_to_label_id(inst_id: int) -> int: + return int(inst_id) % 120 + +class DeeperZencoder(BaseNetwork): + def __init__(self,cfg, input_nc = 3, output_nc = 512, ngf=32, n_downsampling=2, norm_layer=nn.InstanceNorm2d): + super().__init__() + self.cfg = cfg + self.n_downsampling = 6 + self.non_spade_norm_layer = norm_layer + self.output_nc = cfg["style_length"] + input_nc = input_nc +1 #RGB + Valid + + self.gamma = nn.Linear(1, 1) + self.beta = nn.Linear(1, 1) + ### downsample + input_nc = cfg['input_nc'] + ngf = cfg['ngf'] + output_nc = cfg['style_length'] + lab_nc = cfg['lab_dim'] + 1 + g_norm = cfg['G_norm_type'] + self.enc1 = Conv2dBlock(4, 16, kernel_size=3, stride=1, padding=1, norm=g_norm, activation='lrelu') # 16, 256, 256 + self.enc2 = Conv2dBlock(16, 32, kernel_size=3, stride=2, padding=1, norm=g_norm, activation='lrelu') # 32, 128, 128 + self.enc3 = Conv2dBlock(32, 64, kernel_size=3, stride=2, padding=1, norm=g_norm, activation='lrelu') # 64, 64, 64 + self.enc4 = Conv2dBlock(64, 128, kernel_size=3, stride=2, padding=1, norm=g_norm, activation='lrelu') # 128, 32, 32 + self.enc5 = Conv2dBlock(128, 256, kernel_size=3, stride=2, padding=1, norm=g_norm, activation='lrelu') # 256, 16, 16 + self.enc6 = Conv2dBlock(256, 512, kernel_size=3, stride=1, padding=1, dilation=1, norm=g_norm, activation='lrelu') # 512, 16, 16 + + # Decoder layers + self.dec5 = Conv2dBlock(512+128, 512, kernel_size=3, stride=1, padding=1, norm=g_norm, + activation='lrelu') + self.dec4 = Conv2dBlock(512+64, 256, kernel_size=3, stride=1, padding=1, norm=g_norm, + activation='lrelu') + self.dec3 = Conv2dBlock(256+32, 256, kernel_size=3, stride=1, padding=1, norm=g_norm, + activation='lrelu') + self.dec2 = Conv2dBlock(256+16, 256, kernel_size=3, stride=1, padding=1, norm=g_norm, + activation='lrelu') + self.dec1 = Conv2dBlock(256, output_nc, kernel_size=3, stride=1, padding=1, norm='none', activation='tanh') + + def forward(self, input, segmap, valids, instance_map=None, cached_codes=None): + masked_input = input*valids + masked_input = torch.cat((masked_input, valids), 1) + codes = self._forward_layers(masked_input) + + original_input = torch.cat((input, torch.ones(valids.shape, device=valids.device, dtype=valids.dtype)), 1) + unmasked_codes = self._forward_layers(original_input) + + if instance_map is None: + styles_map = segmap + else: + styles_map = instance_map + styles_map = F.interpolate(styles_map, size=codes.size()[2:], mode='nearest') + valids = F.interpolate(valids, size=codes.size()[2:], mode='nearest') + # instance-wise average pooling + style_codes = codes.clone() + for b in range(input.size()[0]): + inst_list = torch.unique(styles_map[b]).to(torch.long) + for i in inst_list: + indices = (styles_map[b:b+1] == int(i)).nonzero() # n x 4 + valid_ins = valids[indices[:,0] + b, :, indices[:,2], indices[:,3]] + if valid_ins.sum() > 0: + output_ins = codes[indices[:,0] + b, :, indices[:,2], indices[:,3]] + mean_feat = output_ins.mean(dim=0).expand_as(output_ins) + valid_ratio = valid_ins.mean().unsqueeze(0) + mean_feat = mean_feat * torch.sigmoid(self.gamma(valid_ratio)) + torch.sigmoid(self.beta(valid_ratio)) + elif self.cfg["is_train"]: + unmasked_output_ins = unmasked_codes[indices[:,0] + b, :, indices[:,2], indices[:,3]] + mean_feat = unmasked_output_ins.mean(dim=0).expand_as(unmasked_output_ins) + valid_ratio = torch.ones((1,)) + mean_feat = mean_feat * torch.sigmoid(self.gamma(valid_ratio)) + torch.sigmoid(self.beta(valid_ratio)) + else: + code_list = cached_codes[inst_id_to_label_id(i)] + random_code = random.choice(code_list) + mean_feat = random_code.expand_as(codes[indices[:,0] + b, :, indices[:,2], indices[:,3]]) + valid_ratio = torch.ones((1,)) + mean_feat = mean_feat * torch.sigmoid(self.gamma(valid_ratio)) + torch.sigmoid(self.beta(valid_ratio)) + style_codes[indices[:,0] + b, :, indices[:,2], indices[:,3]] = mean_feat + return style_codes + + def _forward_layers(self, input): + # Encoder + e1 = self.enc1(input) + e2 = self.enc2(e1) + e3 = self.enc3(e2) + e4 = self.enc4(e3) + e5 = self.enc5(e4) + x = self.enc6(e5) + + x = F.interpolate(x, scale_factor=2, mode='bilinear') + x = torch.cat((x, e4), dim=1) + x = self.dec5(x) + + x = F.interpolate(x, scale_factor=2, mode='bilinear') + x = torch.cat((x, e3), dim=1) + x = self.dec4(x) + + x = F.interpolate(x, scale_factor=2, mode='bilinear') + x = torch.cat((x, e2), dim=1) + x = self.dec3(x) + + x = F.interpolate(x, scale_factor=2, mode='bilinear') + x = torch.cat((x, e1), dim=1) + x = self.dec2(x) + + x = self.dec1(x) + + return x + diff --git a/model/utils.py b/model/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..eb80fd1f267b69679323b246e61f41a71ae3fd37 --- /dev/null +++ b/model/utils.py @@ -0,0 +1,54 @@ +import math +import yaml +import torch.nn.init as init +import torch +import numpy as np + +def get_config(config): + with open(config, 'r') as stream: + return yaml.load(stream, Loader=yaml.Loader) + +def weights_init(init_type='gaussian'): + def init_fun(m): + classname = m.__class__.__name__ + if (classname.find('Conv') == 0 or classname.find('Linear') == 0) and hasattr(m, 'weight'): + # print m.__class__.__name__ + if init_type == 'gaussian': + init.normal_(m.weight.data, 0.0, 0.02) + elif init_type == 'xavier': + init.xavier_normal_(m.weight.data, gain=math.sqrt(2)) + elif init_type == 'kaiming': + init.kaiming_normal_(m.weight.data, a=0, mode='fan_in') + elif init_type == 'orthogonal': + init.orthogonal_(m.weight.data, gain=math.sqrt(2)) + elif init_type == 'default': + pass + else: + assert 0, "Unsupported initialization: {}".format(init_type) + if hasattr(m, 'bias') and m.bias is not None: + init.constant_(m.bias.data, 0.0) + + return init_fun + +def tensor2im(input_image, imtype=np.uint8, no_fg=True): + """"Converts a Tensor array into a numpy image array. + + Parameters: + input_image (tensor) -- the input image tensor array + imtype (type) -- the desired type of the converted numpy array + no_fg: binary image and don't transform + """ + if not isinstance(input_image, np.ndarray): + if isinstance(input_image, torch.Tensor): # get the data from a variable + image_tensor = input_image.data + else: + return input_image + image_numpy = image_tensor[0].cpu().float().numpy() # convert it into a numpy array, only take the first output + if no_fg: + image_numpy = (np.transpose(image_numpy, (1, 2, 0)) + 1) / 2.0 * 255.0 # post-processing: tranpose and scaling + else: + image_numpy = (np.transpose(image_numpy, (1, 2, 0))) * 255.0 + image_numpy = np.clip(image_numpy, 0, 255) + else: # if it is a numpy array, do nothing + image_numpy = input_image + return image_numpy.astype(imtype) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..18b08df91998b30250afa85b1a0f6eea5c177905 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +torch==1.12.0 +torchvision==0.13.0 +opencv-python +scikit-image \ No newline at end of file diff --git a/utils.py b/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..54fb081728b230f3d33f3d2b50b1b7cbf687ead8 --- /dev/null +++ b/utils.py @@ -0,0 +1,126 @@ +import os + +# Utility class for the demo +class AppUtils(): + _label_id_map = { + 0: { + "Sky": 2, + "Tree": 4, + "Road": 52, + }, + 1: { + "Sky": 2, + "Tree": 4, + "Mountain": 16, + "Water": 21, + }, + 2: { + "Sky": 2, + "Mountain": 16, + }, + 3: { + "Sky": 2, + "Ground": 13, + "Mountain": 16, + }, + 4: { + "Sky": 2, + "Mountain": 16, + }, + 5: { + "Sky": 2, + "Mountain": 16, + }, + 6: { + "Sky": 2, + "Tree": 4, + "Mountain": 16, + }, + } + _inst_id_map = { + 0: { + "Sky": 362, + "Tree": 604, + "Cim": 2056, + "Road": 6412, + }, + 1: { + "Sky": 362, + "Tree": 604, + "Mountain": 2056, + "Water": 2661, + }, + 2: { + "Sky": 362, + "Mountain": 2056, + }, + 3: { + "Sky": 362, + "Ground": 1693, + "Mountain": 2056, + }, + 4: { + "Sky": 362, + "Mountain": 2056, + }, + 5: { + "Sky": 362, + "Mountain": 2056, + }, + 6: { + "Sky": 362, + "Tree": 604, + "Mountain": 2056, + }, + } + + _save_paths = { + "image": "gradio_files/samples/test_processed/images", + "labels": "gradio_files/samples/test_processed/labels", + "inst_map": "gradio_files/samples/test_processed/inst_map", + "predefined_masks": "gradio_files/samples/test_processed/predefined_masks/type_0", + "synthesized_image": "gradio_files/samples/synthesized_image" + } + + @staticmethod + def clear(): + for save_path in AppUtils._save_paths.values(): + AppUtils._create_folder(save_path) + + os.system("rm -rf gradio_files/samples/test_processed/images/*") + os.system("rm -rf gradio_files/samples/test_processed/labels/*") + os.system("rm -rf gradio_files/samples/test_processed/inst_map/*") + os.system("rm -rf gradio_files/samples/test_processed/predefined_masks/type_0/*") + + @staticmethod + def get_examples(): + return [ + [0, "gradio_files/samples/flickr-landscape/images/832-41253531765_83c1767ba9_o.png", "gradio_files/samples/flickr-landscape/colored/832-41253531765_83c1767ba9_o.png"], + [1, "gradio_files/samples/flickr-landscape/images/3736-9818172074_156d4682f3_o.png", "gradio_files/samples/flickr-landscape/colored/3736-9818172074_156d4682f3_o.png"], + [2, "gradio_files/samples/flickr-landscape/images/7343-9965972016_a822e52102_o.png", "gradio_files/samples/flickr-landscape/colored/7343-9965972016_a822e52102_o.png"], + [3, "gradio_files/samples/flickr-landscape/images/7503-16108428460_622fcdb3ca_o.png", "gradio_files/samples/flickr-landscape/colored/7503-16108428460_622fcdb3ca_o.png"], + [4, "gradio_files/samples/flickr-landscape/images/7921-47167099321_02f96ba4f6_o.png", "gradio_files/samples/flickr-landscape/colored/7921-47167099321_02f96ba4f6_o.png"], + [5, "gradio_files/samples/flickr-landscape/images/8016-7167270731_b9843b1072_o.png", "gradio_files/samples/flickr-landscape/colored/8016-7167270731_b9843b1072_o.png"], + [6, "gradio_files/samples/flickr-landscape/images/8042-7987076838_05973d5ee8_o.png", "gradio_files/samples/flickr-landscape/colored/8042-7987076838_05973d5ee8_o.png"], + ] + + @staticmethod + def get_labels(input_id): + return ["None"] + list(AppUtils._label_id_map[input_id].keys()) + + @staticmethod + def get_inst_id(input_id, label): + return AppUtils._inst_id_map[input_id][label] + + @staticmethod + def get_label_id(input_id, label): + return AppUtils._label_id_map[input_id][label] + + @staticmethod + def _create_folder(directory): + if not os.path.exists(directory): + os.makedirs(directory) + + @staticmethod + def copy_file(src_path, dest_path): + os.system(f"cp {src_path} {dest_path}") \ No newline at end of file