qic999 commited on
Commit
2b4b0d7
·
verified ·
1 Parent(s): 74ecfd7

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +36 -0
  2. instruct-pix2pix-BioMedCLIP-concat-newdata/LICENSE +9 -0
  3. instruct-pix2pix-BioMedCLIP-concat-newdata/README.md +255 -0
  4. instruct-pix2pix-BioMedCLIP-concat-newdata/__pycache__/main.cpython-310.pyc +0 -0
  5. instruct-pix2pix-BioMedCLIP-concat-newdata/__pycache__/main.cpython-311.pyc +0 -0
  6. instruct-pix2pix-BioMedCLIP-concat-newdata/__pycache__/main.cpython-39.pyc +0 -0
  7. instruct-pix2pix-BioMedCLIP-concat-newdata/checkpoints/instruct-pix2pix-00-22000.ckpt +3 -0
  8. instruct-pix2pix-BioMedCLIP-concat-newdata/config.sh +5 -0
  9. instruct-pix2pix-BioMedCLIP-concat-newdata/configs/generate.yaml +99 -0
  10. instruct-pix2pix-BioMedCLIP-concat-newdata/configs/train.yaml +113 -0
  11. instruct-pix2pix-BioMedCLIP-concat-newdata/configs/train_3d.yaml +109 -0
  12. instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/disease_mask_json/disease_train_single_prompt_checked_label.json +0 -0
  13. instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/disease_mask_json/disease_valid_single_prompt_checked_label.json +0 -0
  14. instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/metadata/Metadata_Attributes.xlsx +0 -0
  15. instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/metadata/all_metadata.csv +3 -0
  16. instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/metadata/clip_-1000_1000.py +73 -0
  17. instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/metadata/no_chest_train.txt +752 -0
  18. instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/metadata/no_chest_valid.txt +37 -0
  19. instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/metadata/train_metadata.csv +3 -0
  20. instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/metadata/validation_metadata.csv +0 -0
  21. instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/multi_abnormality_labels/train_predicted_labels.csv +0 -0
  22. instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/multi_abnormality_labels/train_predicted_labels_100.csv +101 -0
  23. instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/multi_abnormality_labels/valid_predicted_labels.csv +0 -0
  24. instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/multi_abnormality_labels/valid_predicted_labels_100.csv +101 -0
  25. instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/radiology_text_reports/train_reports.csv +3 -0
  26. instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/radiology_text_reports/valid_reports.csv +0 -0
  27. instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/train_no_disease_2_checked.json +0 -0
  28. instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/valid_no_disease_2_checked.json +0 -0
  29. instruct-pix2pix-BioMedCLIP-concat-newdata/dataset_creation/generate_img_dataset.py +315 -0
  30. instruct-pix2pix-BioMedCLIP-concat-newdata/dataset_creation/generate_txt_dataset.py +113 -0
  31. instruct-pix2pix-BioMedCLIP-concat-newdata/dataset_creation/prepare_dataset.py +29 -0
  32. instruct-pix2pix-BioMedCLIP-concat-newdata/dataset_creation/prepare_for_gpt.py +25 -0
  33. instruct-pix2pix-BioMedCLIP-concat-newdata/edit_app.py +268 -0
  34. instruct-pix2pix-BioMedCLIP-concat-newdata/edit_cli.py +128 -0
  35. instruct-pix2pix-BioMedCLIP-concat-newdata/edit_dataset.py +121 -0
  36. instruct-pix2pix-BioMedCLIP-concat-newdata/environment.yaml +38 -0
  37. instruct-pix2pix-BioMedCLIP-concat-newdata/imgs/dataset.jpg +3 -0
  38. instruct-pix2pix-BioMedCLIP-concat-newdata/imgs/edit_app.jpg +3 -0
  39. instruct-pix2pix-BioMedCLIP-concat-newdata/imgs/example.jpg +0 -0
  40. instruct-pix2pix-BioMedCLIP-concat-newdata/imgs/prompt_app.jpg +0 -0
  41. instruct-pix2pix-BioMedCLIP-concat-newdata/inference_full_ct_2d_with_body_mask.py +141 -0
  42. instruct-pix2pix-BioMedCLIP-concat-newdata/main.py +829 -0
  43. instruct-pix2pix-BioMedCLIP-concat-newdata/metrics/clip_similarity.py +47 -0
  44. instruct-pix2pix-BioMedCLIP-concat-newdata/metrics/compute_metrics.py +235 -0
  45. instruct-pix2pix-BioMedCLIP-concat-newdata/prompt_app.py +55 -0
  46. instruct-pix2pix-BioMedCLIP-concat-newdata/requirements.txt +101 -0
  47. instruct-pix2pix-BioMedCLIP-concat-newdata/scripts/download_checkpoints.sh +7 -0
  48. instruct-pix2pix-BioMedCLIP-concat-newdata/scripts/download_data.sh +27 -0
  49. instruct-pix2pix-BioMedCLIP-concat-newdata/scripts/download_pretrained_sd.sh +7 -0
  50. instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/LICENSE +82 -0
.gitattributes CHANGED
@@ -102,3 +102,39 @@ instruct-pix2pix-BioMedCLIP-concat-newdata-data1/stable_diffusion/data/inpaintin
102
  instruct-pix2pix-BioMedCLIP-concat-newdata-data1/stable_diffusion/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png filter=lfs diff=lfs merge=lfs -text
103
  instruct-pix2pix-BioMedCLIP-concat-newdata-data1/stable_diffusion/data/inpainting_examples/photo-1583445095369-9c651e7e5d34.png filter=lfs diff=lfs merge=lfs -text
104
  instruct-pix2pix-BioMedCLIP-concat-newdata-data1/stable_diffusion/ldm/modules/image_degradation/utils/test.png filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  instruct-pix2pix-BioMedCLIP-concat-newdata-data1/stable_diffusion/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png filter=lfs diff=lfs merge=lfs -text
103
  instruct-pix2pix-BioMedCLIP-concat-newdata-data1/stable_diffusion/data/inpainting_examples/photo-1583445095369-9c651e7e5d34.png filter=lfs diff=lfs merge=lfs -text
104
  instruct-pix2pix-BioMedCLIP-concat-newdata-data1/stable_diffusion/ldm/modules/image_degradation/utils/test.png filter=lfs diff=lfs merge=lfs -text
105
+ instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/metadata/all_metadata.csv filter=lfs diff=lfs merge=lfs -text
106
+ instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/metadata/train_metadata.csv filter=lfs diff=lfs merge=lfs -text
107
+ instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/radiology_text_reports/train_reports.csv filter=lfs diff=lfs merge=lfs -text
108
+ instruct-pix2pix-BioMedCLIP-concat-newdata/imgs/dataset.jpg filter=lfs diff=lfs merge=lfs -text
109
+ instruct-pix2pix-BioMedCLIP-concat-newdata/imgs/edit_app.jpg filter=lfs diff=lfs merge=lfs -text
110
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/assets/a-painting-of-a-fire.png filter=lfs diff=lfs merge=lfs -text
111
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/assets/a-photograph-of-a-fire.png filter=lfs diff=lfs merge=lfs -text
112
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/assets/a-shirt-with-a-fire-printed-on-it.png filter=lfs diff=lfs merge=lfs -text
113
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/assets/a-shirt-with-the-inscription-'fire'.png filter=lfs diff=lfs merge=lfs -text
114
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/assets/a-watercolor-painting-of-a-fire.png filter=lfs diff=lfs merge=lfs -text
115
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/assets/birdhouse.png filter=lfs diff=lfs merge=lfs -text
116
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/assets/fire.png filter=lfs diff=lfs merge=lfs -text
117
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/assets/inpainting.png filter=lfs diff=lfs merge=lfs -text
118
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/assets/rdm-preview.jpg filter=lfs diff=lfs merge=lfs -text
119
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/assets/reconstruction1.png filter=lfs diff=lfs merge=lfs -text
120
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/assets/reconstruction2.png filter=lfs diff=lfs merge=lfs -text
121
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/assets/rick.jpeg filter=lfs diff=lfs merge=lfs -text
122
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/assets/stable-samples/img2img/mountains-1.png filter=lfs diff=lfs merge=lfs -text
123
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/assets/stable-samples/img2img/mountains-2.png filter=lfs diff=lfs merge=lfs -text
124
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/assets/stable-samples/img2img/mountains-3.png filter=lfs diff=lfs merge=lfs -text
125
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/assets/stable-samples/img2img/sketch-mountains-input.jpg filter=lfs diff=lfs merge=lfs -text
126
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/assets/stable-samples/txt2img/000002025.png filter=lfs diff=lfs merge=lfs -text
127
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/assets/stable-samples/txt2img/000002035.png filter=lfs diff=lfs merge=lfs -text
128
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/assets/the-earth-is-on-fire,-oil-on-canvas.png filter=lfs diff=lfs merge=lfs -text
129
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/assets/txt2img-convsample.png filter=lfs diff=lfs merge=lfs -text
130
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/data/DejaVuSans.ttf filter=lfs diff=lfs merge=lfs -text
131
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/data/imagenet_val_hr_indices.p filter=lfs diff=lfs merge=lfs -text
132
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/data/inpainting_examples/6458524847_2f4c361183_k.png filter=lfs diff=lfs merge=lfs -text
133
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/data/inpainting_examples/8399166846_f6fb4e4b8e_k.png filter=lfs diff=lfs merge=lfs -text
134
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/data/inpainting_examples/alex-iby-G_Pk4D9rMLs.png filter=lfs diff=lfs merge=lfs -text
135
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/data/inpainting_examples/bench2.png filter=lfs diff=lfs merge=lfs -text
136
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/data/inpainting_examples/bertrand-gabioud-CpuFzIsHYJ0.png filter=lfs diff=lfs merge=lfs -text
137
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/data/inpainting_examples/billow926-12-Wc-Zgx6Y.png filter=lfs diff=lfs merge=lfs -text
138
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png filter=lfs diff=lfs merge=lfs -text
139
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/data/inpainting_examples/photo-1583445095369-9c651e7e5d34.png filter=lfs diff=lfs merge=lfs -text
140
+ instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/ldm/modules/image_degradation/utils/test.png filter=lfs diff=lfs merge=lfs -text
instruct-pix2pix-BioMedCLIP-concat-newdata/LICENSE ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2023 Timothy Brooks, Aleksander Holynski, Alexei A. Efros
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
8
+
9
+ Portions of code and models (such as pretrained checkpoints, which are fine-tuned starting from released Stable Diffusion checkpoints) are derived from the Stable Diffusion codebase (https://github.com/CompVis/stable-diffusion). Further restrictions may apply. Please consult the Stable Diffusion license `stable_diffusion/LICENSE`. Modified code is denoted as such in comments at the start of each file.
instruct-pix2pix-BioMedCLIP-concat-newdata/README.md ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # InstructPix2Pix: Learning to Follow Image Editing Instructions
2
+ ### [Project Page](https://www.timothybrooks.com/instruct-pix2pix/) | [Paper](https://arxiv.org/abs/2211.09800) | [Data](http://instruct-pix2pix.eecs.berkeley.edu/)
3
+ PyTorch implementation of InstructPix2Pix, an instruction-based image editing model, based on the original [CompVis/stable_diffusion](https://github.com/CompVis/stable-diffusion) repo. <br>
4
+
5
+ [InstructPix2Pix: Learning to Follow Image Editing Instructions](https://www.timothybrooks.com/instruct-pix2pix/)
6
+ [Tim Brooks](https://www.timothybrooks.com/)\*,
7
+ [Aleksander Holynski](https://holynski.org/)\*,
8
+ [Alexei A. Efros](https://people.eecs.berkeley.edu/~efros/) <br>
9
+ UC Berkeley <br>
10
+ \*denotes equal contribution
11
+
12
+ <img src='https://instruct-pix2pix.timothybrooks.com/teaser.jpg'/>
13
+
14
+ ## TL;DR: quickstart
15
+
16
+ Follow the instructions below to download and run InstructPix2Pix on your own images. These instructions have been tested on a GPU with >18GB VRAM. If you don't have a GPU, you may need to change the default configuration, or check out [other ways of using the model](https://github.com/timothybrooks/instruct-pix2pix#other-ways-of-using-instructpix2pix).
17
+
18
+ ### Set up a conda environment, and download a pretrained model:
19
+ ```
20
+ conda env create -f environment.yaml
21
+ conda activate ip2p
22
+ bash scripts/download_checkpoints.sh
23
+ ```
24
+
25
+ ### Edit a single image:
26
+ ```
27
+ python edit_cli.py --input imgs/example.jpg --output imgs/output.jpg --edit "turn him into a cyborg"
28
+
29
+ # Optionally, you can specify parameters to tune your result:
30
+ # python edit_cli.py --steps 100 --resolution 512 --seed 1371 --cfg-text 7.5 --cfg-image 1.2 --input imgs/example.jpg --output imgs/output.jpg --edit "turn him into a cyborg"
31
+ ```
32
+
33
+ ### Or launch your own interactive editing Gradio app:
34
+ ```
35
+ python edit_app.py
36
+ ```
37
+ ![Edit app](https://github.com/timothybrooks/instruct-pix2pix/blob/main/imgs/edit_app.jpg?raw=true)
38
+
39
+ _(For advice on how to get the best results by tuning parameters, see the [Tips](https://github.com/timothybrooks/instruct-pix2pix#tips) section)._
40
+
41
+ ## Setup
42
+
43
+ Install all dependencies with:
44
+ ```
45
+ conda env create -f environment.yaml
46
+ ```
47
+
48
+ Download the pretrained models by running:
49
+ ```
50
+ bash scripts/download_checkpoints.sh
51
+ ```
52
+
53
+ ## Generated Dataset
54
+
55
+ Our image editing model is trained on a generated dataset consisting of 454,445 examples. Each example contains (1) an input image, (2) an editing instruction, and (3) an output edited image. We provide two versions of the dataset, one in which each pair of edited images is generated 100 times, and the best examples are chosen based on CLIP metrics (Section 3.1.2 in the paper) (`clip-filtered-dataset`), and one in which examples are randomly chosen (`random-sample-dataset`).
56
+
57
+ For the released version of this dataset, we've additionally filtered prompts and images for NSFW content. After NSFW filtering, the GPT-3 generated dataset contains 451,990 examples. The final image-pair datasets contain:
58
+
59
+ | | # of image editing examples | Dataset size |
60
+ |--|-----------------------|----------------------- |
61
+ | `random-sample-dataset` |451990|727GB|
62
+ | `clip-filtered-dataset` |313010|436GB|
63
+
64
+ To download one of these datasets, along with the entire NSFW-filtered text data, run the following command with the appropriate dataset name:
65
+
66
+ ```
67
+ bash scripts/download_data.sh clip-filtered-dataset
68
+ ```
69
+
70
+
71
+ ## Training InstructPix2Pix
72
+
73
+ InstructPix2Pix is trained by fine-tuning from an initial StableDiffusion checkpoint. The first step is to download a Stable Diffusion checkpoint. For our trained models, we used the v1.5 checkpoint as the starting point. To download the same ones we used, you can run the following script:
74
+ ```
75
+ bash scripts/download_pretrained_sd.sh
76
+ ```
77
+ If you'd like to use a different checkpoint, point to it in the config file `configs/train.yaml`, on line 8, after `ckpt_path:`.
78
+
79
+ Next, we need to change the config to point to our downloaded (or generated) dataset. If you're using the `clip-filtered-dataset` from above, you can skip this. Otherwise, you may need to edit lines 85 and 94 of the config (`data.params.train.params.path`, `data.params.validation.params.path`).
80
+
81
+ Finally, start a training job with the following command:
82
+
83
+ ```
84
+ python main.py --name default --base configs/train.yaml --train --gpus 0,1,2,3,4,5,6,7
85
+ ```
86
+
87
+
88
+ ## Creating your own dataset
89
+
90
+ Our generated dataset of paired images and editing instructions is made in two phases: First, we use GPT-3 to generate text triplets: (a) a caption describing an image, (b) an edit instruction, (c) a caption describing the image after the edit. Then, we turn pairs of captions (before/after the edit) into pairs of images using Stable Diffusion and Prompt-to-Prompt.
91
+
92
+ ### (1) Generate a dataset of captions and instructions
93
+
94
+ We provide our generated dataset of captions and edit instructions [here](https://instruct-pix2pix.eecs.berkeley.edu/gpt-generated-prompts.jsonl). If you plan to use our captions+instructions, skip to step (2). Otherwise, if you would like to create your own text dataset, please follow steps (1.1-1.3) below. Note that generating very large datasets using GPT-3 can be expensive.
95
+
96
+ #### (1.1) Manually write a dataset of instructions and captions
97
+
98
+ The first step of the process is fine-tuning GPT-3. To do this, we made a dataset of 700 examples broadly covering of edits that we might want our model to be able to perform. Our examples are available [here](https://instruct-pix2pix.eecs.berkeley.edu/human-written-prompts.jsonl). These should be diverse and cover a wide range of possible captions and types of edits. Ideally, they should avoid duplication or significant overlap of captions and instructions. It is also important to be mindful of limitations of Stable Diffusion and Prompt-to-Prompt in writing these examples, such as inability to perform large spatial transformations (e.g., moving the camera, zooming in, swapping object locations).
99
+
100
+ Input prompts should closely match the distribution of input prompts used to generate the larger dataset. We sampled the 700 input prompts from the _LAION Improved Aesthetics 6.5+_ dataset and also use this dataset for generating examples. We found this dataset is quite noisy (many of the captions are overly long and contain irrelevant text). For this reason, we also considered MSCOCO and LAION-COCO datasets, but ultimately chose _LAION Improved Aesthetics 6.5+_ due to its diversity of content, proper nouns, and artistic mediums. If you choose to use another dataset or combination of datasets as input to GPT-3 when generating examples, we recommend you sample the input prompts from the same distribution when manually writing training examples.
101
+
102
+ #### (1.2) Finetune GPT-3
103
+
104
+ The next step is to finetune a large language model on the manually written instructions/outputs to generate edit instructions and edited caption from a new input caption. For this, we finetune GPT-3's Davinci model via the OpenAI API, although other language models could be used.
105
+
106
+ To prepare training data for GPT-3, one must first create an OpenAI developer account to access the needed APIs, and [set up the API keys on your local device](https://beta.openai.com/docs/api-reference/introduction). Also, run the `prompts/prepare_for_gpt.py` script, which forms the prompts into the correct format by concatenating instructions and captions and adding delimiters and stop sequences.
107
+
108
+ ```bash
109
+ python dataset_creation/prepare_for_gpt.py --input-path data/human-written-prompts.jsonl --output-path data/human-written-prompts-for-gpt.jsonl
110
+ ```
111
+
112
+ Next, finetune GPT-3 via the OpenAI CLI. We provide an example below, although please refer to OpenAI's official documentation for this, as best practices may change. We trained the Davinci model for a single epoch. You can experiment with smaller less expensive GPT-3 variants or with open source language models, although this may negatively affect performance.
113
+
114
+ ```bash
115
+ openai api fine_tunes.create -t data/human-written-prompts-for-gpt.jsonl -m davinci --n_epochs 1 --suffix "instruct-pix2pix"
116
+ ```
117
+
118
+ You can test out the finetuned GPT-3 model by launching the provided Gradio app:
119
+
120
+ ```bash
121
+ python prompt_app.py --openai-api-key OPENAI_KEY --openai-model OPENAI_MODEL_NAME
122
+ ```
123
+
124
+ ![Prompt app](https://github.com/timothybrooks/instruct-pix2pix/blob/main/imgs/prompt_app.jpg?raw=true)
125
+
126
+ #### (1.3) Generate a large dataset of captions and instructions
127
+
128
+ We now use the finetuned GPT-3 model to generate a large dataset. Our dataset cost thousands of dollars to create. See `prompts/gen_instructions_and_captions.py` for the script which generates these examples. We recommend first generating a small number of examples (by setting a low value of `--num-samples`) and gradually increasing the scale to ensure the results are working as desired before increasing scale.
129
+
130
+ ```bash
131
+ python dataset_creation/generate_txt_dataset.py --openai-api-key OPENAI_KEY --openai-model OPENAI_MODEL_NAME
132
+ ```
133
+
134
+ If you are generating at a very large scale (e.g., 100K+), it will be noteably faster to generate the dataset with multiple processes running in parallel. This can be accomplished by setting `--partitions=N` to a higher number and running multiple processes, setting each `--partition` to the corresponding value.
135
+
136
+ ```bash
137
+ python dataset_creation/generate_txt_dataset.py --openai-api-key OPENAI_KEY --openai-model OPENAI_MODEL_NAME --partitions=10 --partition=0
138
+ ```
139
+
140
+ ### (2) Turn paired captions into paired images
141
+
142
+ The next step is to turn pairs of text captions into pairs of images. For this, we need to copy some pre-trained Stable Diffusion checkpoints to `stable_diffusion/models/ldm/stable-diffusion-v1/`. You may have already done this if you followed the instructions above for training with our provided data, but if not, you can do this by running:
143
+
144
+ ```bash
145
+ bash scripts/download_pretrained_sd.sh
146
+ ```
147
+
148
+ For our model, we used [checkpoint v1.5](https://huggingface.co/runwayml/stable-diffusion-v1-5/blob/main/v1-5-pruned.ckpt), and the [new autoencoder](https://huggingface.co/stabilityai/sd-vae-ft-mse-original/resolve/main/vae-ft-mse-840000-ema-pruned.ckpt), but other models may work as well. If you choose to use other models, make sure to change point to the corresponding checkpoints by passing in the `--ckpt` and `--vae-ckpt` arguments. Once all checkpoints have been downloaded, we can generate the dataset with the following command:
149
+
150
+ ```
151
+ python dataset_creation/generate_img_dataset.py --out_dir data/instruct-pix2pix-dataset-000 --prompts_file path/to/generated_prompts.jsonl
152
+ ```
153
+
154
+ This command operates on a single GPU (typically a V100 or A100). To parallelize over many GPUs/machines, set `--n-partitions` to the total number of parallel jobs and `--partition` to the index of each job.
155
+
156
+ ```
157
+ python dataset_creation/generate_img_dataset.py --out_dir data/instruct-pix2pix-dataset-000 --prompts_file path/to/generated_prompts.jsonl --n-partitions 100 --partition 0
158
+ ```
159
+
160
+ The default parameters match that of our dataset, although in practice you can use a smaller number of steps (e.g., `--steps=25`) to generate high quality data faster. By default, we generate 100 samples per prompt and use CLIP filtering to keep a max of 4 per prompt. You can experiment with fewer samples by setting `--n-samples`. The command below turns off CLIP filtering entirely and is therefore faster:
161
+
162
+ ```
163
+ python dataset_creation/generate_img_dataset.py --out_dir data/instruct-pix2pix-dataset-000 --prompts_file path/to/generated_prompts.jsonl --n-samples 4 --clip-threshold 0 --clip-dir-threshold 0 --clip-img-threshold 0 --n-partitions 100 --partition 0
164
+ ```
165
+
166
+ After generating all of the dataset examples, run the following command below to create a list of the examples. This is needed for the dataset onject to efficiently be able to sample examples without needing to iterate over the entire dataset directory at the start of each training run.
167
+
168
+ ```
169
+ python dataset_creation/prepare_dataset.py data/instruct-pix2pix-dataset-000
170
+ ```
171
+
172
+ ## Evaluation
173
+
174
+ To generate plots like the ones in Figures 8 and 10 in the paper, run the following command:
175
+
176
+ ```
177
+ python metrics/compute_metrics.py --ckpt /path/to/your/model.ckpt
178
+ ```
179
+
180
+ ## Tips
181
+
182
+ If you're not getting the quality result you want, there may be a few reasons:
183
+ 1. **Is the image not changing enough?** Your Image CFG weight may be too high. This value dictates how similar the output should be to the input. It's possible your edit requires larger changes from the original image, and your Image CFG weight isn't allowing that. Alternatively, your Text CFG weight may be too low. This value dictates how much to listen to the text instruction. The default Image CFG of 1.5 and Text CFG of 7.5 are a good starting point, but aren't necessarily optimal for each edit. Try:
184
+ * Decreasing the Image CFG weight, or
185
+ * Increasing the Text CFG weight, or
186
+ 2. Conversely, **is the image changing too much**, such that the details in the original image aren't preserved? Try:
187
+ * Increasing the Image CFG weight, or
188
+ * Decreasing the Text CFG weight
189
+ 3. Try generating results with different random seeds by setting "Randomize Seed" and running generation multiple times. You can also try setting "Randomize CFG" to sample new Text CFG and Image CFG values each time.
190
+ 4. Rephrasing the instruction sometimes improves results (e.g., "turn him into a dog" vs. "make him a dog" vs. "as a dog").
191
+ 5. Increasing the number of steps sometimes improves results.
192
+ 6. Do faces look weird? The Stable Diffusion autoencoder has a hard time with faces that are small in the image. Try cropping the image so the face takes up a larger portion of the frame.
193
+
194
+ ## Comments
195
+
196
+ - Our codebase is based on the [Stable Diffusion codebase](https://github.com/CompVis/stable-diffusion).
197
+
198
+ ## BibTeX
199
+
200
+ ```
201
+ @article{brooks2022instructpix2pix,
202
+ title={InstructPix2Pix: Learning to Follow Image Editing Instructions},
203
+ author={Brooks, Tim and Holynski, Aleksander and Efros, Alexei A},
204
+ journal={arXiv preprint arXiv:2211.09800},
205
+ year={2022}
206
+ }
207
+ ```
208
+ ## Other ways of using InstructPix2Pix
209
+
210
+ ### InstructPix2Pix on [HuggingFace](https://huggingface.co/spaces/timbrooks/instruct-pix2pix):
211
+ > A browser-based version of the demo is available as a [HuggingFace space](https://huggingface.co/spaces/timbrooks/instruct-pix2pix). For this version, you only need a browser, a picture you want to edit, and an instruction! Note that this is a shared online demo, and processing time may be slower during peak utilization.
212
+
213
+ ### InstructPix2Pix on [Replicate](https://replicate.com/timothybrooks/instruct-pix2pix):
214
+ > Replicate provides a production-ready cloud API for running the InstructPix2Pix model. You can run the model from any environment using a simple API call with cURL, Python, JavaScript, or your language of choice. Replicate also provides a web interface for running the model and sharing predictions.
215
+
216
+ ### InstructPix2Pix in [Imaginairy](https://github.com/brycedrennan/imaginAIry#-edit-images-with-instructions-alone-by-instructpix2pix):
217
+ > Imaginairy offers another way of easily installing InstructPix2Pix with a single command. It can run on devices without GPUs (like a Macbook!).
218
+ > ```bash
219
+ > pip install imaginairy --upgrade
220
+ > aimg edit any-image.jpg --gif "turn him into a cyborg"
221
+ > ```
222
+ > It also offers an easy way to perform a bunch of edits on an image, and can save edits out to an animated GIF:
223
+ > ```
224
+ > aimg edit --gif --surprise-me pearl-earring.jpg
225
+ > ```
226
+ > <img src="https://raw.githubusercontent.com/brycedrennan/imaginAIry/7c05c3aae2740278978c5e84962b826e58201bac/assets/girl_with_a_pearl_earring_suprise.gif" width="512">
227
+
228
+ ### InstructPix2Pix in [🧨 Diffusers](https://github.com/huggingface/diffusers):
229
+
230
+ > InstructPix2Pix in Diffusers is a bit more optimized, so it may be faster and more suitable for GPUs with less memory. Below are instructions for installing the library and editing an image:
231
+ > 1. Install diffusers and relevant dependencies:
232
+ >
233
+ > ```bash
234
+ > pip install transformers accelerate torch
235
+ >
236
+ > pip install git+https://github.com/huggingface/diffusers.git
237
+ > ```
238
+ >
239
+ > 2. Load the model and edit the image:
240
+ >
241
+ > ```python
242
+ >
243
+ > import torch
244
+ > from diffusers import StableDiffusionInstructPix2PixPipeline, EulerAncestralDiscreteScheduler
245
+ >
246
+ > model_id = "timbrooks/instruct-pix2pix"
247
+ > pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained(model_id, torch_dtype=torch.float16, safety_checker=None)
248
+ > pipe.to("cuda")
249
+ > pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
250
+ > # `image` is an RGB PIL.Image
251
+ > images = pipe("turn him into cyborg", image=image).images
252
+ > images[0]
253
+ > ```
254
+ >
255
+ > For more information, check the docs [here](https://huggingface.co/docs/diffusers/main/en/api/pipelines/stable_diffusion/pix2pix).
instruct-pix2pix-BioMedCLIP-concat-newdata/__pycache__/main.cpython-310.pyc ADDED
Binary file (20.7 kB). View file
 
instruct-pix2pix-BioMedCLIP-concat-newdata/__pycache__/main.cpython-311.pyc ADDED
Binary file (40.5 kB). View file
 
instruct-pix2pix-BioMedCLIP-concat-newdata/__pycache__/main.cpython-39.pyc ADDED
Binary file (20.6 kB). View file
 
instruct-pix2pix-BioMedCLIP-concat-newdata/checkpoints/instruct-pix2pix-00-22000.ckpt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ffd280ddcfc8234e4d28b93641cb83169cebcb4d70998df9ee2eabb4d705374a
3
+ size 7703927910
instruct-pix2pix-BioMedCLIP-concat-newdata/config.sh ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+
2
+
3
+
4
+ python main.py --name debug --base configs/train.yaml --train --gpus 0,
5
+
instruct-pix2pix-BioMedCLIP-concat-newdata/configs/generate.yaml ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File modified by authors of InstructPix2Pix from original (https://github.com/CompVis/stable-diffusion).
2
+ # See more details in LICENSE.
3
+
4
+ model:
5
+ base_learning_rate: 1.0e-04
6
+ target: ldm.models.diffusion.ddpm_edit.LatentDiffusion
7
+ params:
8
+ linear_start: 0.00085
9
+ linear_end: 0.0120
10
+ num_timesteps_cond: 1
11
+ log_every_t: 200
12
+ timesteps: 1000
13
+ first_stage_key: edited
14
+ cond_stage_key: edit
15
+ # image_size: 64
16
+ # image_size: 32
17
+ image_size: 16
18
+ channels: 4
19
+ cond_stage_trainable: false # Note: different from the one we trained before
20
+ conditioning_key: hybrid
21
+ monitor: val/loss_simple_ema
22
+ scale_factor: 0.18215
23
+ use_ema: true
24
+ load_ema: true
25
+
26
+ scheduler_config: # 10000 warmup steps
27
+ target: ldm.lr_scheduler.LambdaLinearScheduler
28
+ params:
29
+ warm_up_steps: [ 0 ]
30
+ cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases
31
+ f_start: [ 1.e-6 ]
32
+ f_max: [ 1. ]
33
+ f_min: [ 1. ]
34
+
35
+ unet_config:
36
+ target: ldm.modules.diffusionmodules.openaimodel.UNetModel
37
+ params:
38
+ image_size: 32 # unused
39
+ in_channels: 8
40
+ out_channels: 4
41
+ model_channels: 320
42
+ attention_resolutions: [ 4, 2, 1 ]
43
+ num_res_blocks: 2
44
+ channel_mult: [ 1, 2, 4, 4 ]
45
+ num_heads: 8
46
+ use_spatial_transformer: True
47
+ transformer_depth: 1
48
+ context_dim: 768
49
+ use_checkpoint: True
50
+ legacy: False
51
+
52
+ first_stage_config:
53
+ target: ldm.models.autoencoder.AutoencoderKL
54
+ params:
55
+ embed_dim: 4
56
+ monitor: val/rec_loss
57
+ ddconfig:
58
+ double_z: true
59
+ z_channels: 4
60
+ resolution: 256
61
+ in_channels: 3
62
+ out_ch: 3
63
+ ch: 128
64
+ ch_mult:
65
+ - 1
66
+ - 2
67
+ - 4
68
+ - 4
69
+ num_res_blocks: 2
70
+ attn_resolutions: []
71
+ dropout: 0.0
72
+ lossconfig:
73
+ target: torch.nn.Identity
74
+
75
+ cond_stage_config:
76
+ target: ldm.modules.encoders.modules.FrozenCLIPEmbedder
77
+
78
+ data:
79
+ target: main.DataModuleFromConfig
80
+ params:
81
+ batch_size: 128
82
+ num_workers: 1
83
+ wrap: false
84
+ validation:
85
+ target: edit_dataset.EditDataset
86
+ params:
87
+ path: data/clip-filtered-dataset
88
+ cache_dir: data/
89
+ cache_name: data_10k
90
+ split: val
91
+ min_text_sim: 0.2
92
+ min_image_sim: 0.75
93
+ min_direction_sim: 0.2
94
+ max_samples_per_prompt: 1
95
+ min_resize_res: 512
96
+ max_resize_res: 512
97
+ crop_res: 512
98
+ output_as_edit: False
99
+ real_input: True
instruct-pix2pix-BioMedCLIP-concat-newdata/configs/train.yaml ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File modified by authors of InstructPix2Pix from original (https://github.com/CompVis/stable-diffusion).
2
+ # See more details in LICENSE.
3
+
4
+ model:
5
+ base_learning_rate: 1.0e-04
6
+ target: ldm.models.diffusion.ddpm_edit.LatentDiffusion
7
+ params:
8
+ ckpt_path: stable_diffusion/models/ldm/stable-diffusion-v1/v1-5-pruned-emaonly.ckpt
9
+ linear_start: 0.00085
10
+ linear_end: 0.0120
11
+ num_timesteps_cond: 1
12
+ log_every_t: 200
13
+ timesteps: 1000
14
+ first_stage_key: edited
15
+ cond_stage_key: edit
16
+ image_size: 64
17
+ channels: 4
18
+ cond_stage_trainable: false # Note: different from the one we trained before
19
+ conditioning_key: hybrid
20
+ monitor: val/loss_simple_ema
21
+ scale_factor: 0.18215
22
+ use_ema: true
23
+ load_ema: false
24
+
25
+ scheduler_config: # 10000 warmup steps
26
+ target: ldm.lr_scheduler.LambdaLinearScheduler
27
+ params:
28
+ warm_up_steps: [ 0 ]
29
+ cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases
30
+ f_start: [ 1.e-6 ]
31
+ f_max: [ 1. ]
32
+ f_min: [ 1. ]
33
+
34
+ unet_config:
35
+ target: ldm.modules.diffusionmodules.openaimodel.UNetModel
36
+ params:
37
+ image_size: 32 # unused
38
+ in_channels: 8
39
+ out_channels: 4
40
+ model_channels: 320
41
+ attention_resolutions: [ 4, 2, 1 ]
42
+ num_res_blocks: 2
43
+ channel_mult: [ 1, 2, 4, 4 ]
44
+ num_heads: 8
45
+ use_spatial_transformer: True
46
+ transformer_depth: 1
47
+ context_dim: 768
48
+ use_checkpoint: True
49
+ legacy: False
50
+
51
+ first_stage_config:
52
+ target: ldm.models.autoencoder.AutoencoderKL
53
+ params:
54
+ embed_dim: 4
55
+ monitor: val/rec_loss
56
+ ddconfig:
57
+ double_z: true
58
+ z_channels: 4
59
+ resolution: 256
60
+ in_channels: 3
61
+ out_ch: 3
62
+ ch: 128
63
+ ch_mult:
64
+ - 1
65
+ - 2
66
+ - 4
67
+ - 4
68
+ num_res_blocks: 2
69
+ attn_resolutions: []
70
+ dropout: 0.0
71
+ lossconfig:
72
+ target: torch.nn.Identity
73
+
74
+ cond_stage_config:
75
+ target: ldm.modules.encoders.modules.FrozenBioMedCLIPEmbedder
76
+
77
+ data:
78
+ target: main.DataModuleFromConfig
79
+ params:
80
+ batch_size: 64
81
+ num_workers: 8
82
+ train:
83
+ target: ldm.data.ct_clip_data_train.CTReportDataset
84
+ params:
85
+ # data_folder: '/sd/shuhan/CT-RATE/dataset/train_fixed'
86
+ # csv_file: '/sd/shuhan/CT-RATE/radiology_text_reports/train_reports.csv'
87
+ data_folder: '/workspace/jifu/data/dataset/train_fixed'
88
+ csv_file: '/workspace/jifu/data/data_json/radiology_text_reports/train_reports.csv'
89
+
90
+ validation:
91
+ target: ldm.data.ct_clip_data_inference.CTReportDatasetinfer
92
+ params:
93
+ # data_folder: '/sd/shuhan/CT-RATE/dataset/valid_fixed'
94
+ # csv_file: '/sd/shuhan/CT-RATE/radiology_text_reports/valid_reports.csv'
95
+ # labels: '/sd/shuhan/CT-RATE/multi_abnormality_labels/valid_predicted_labels.csv'
96
+ data_folder: '/workspace/jifu/data/dataset/valid_fixed'
97
+ csv_file: '/workspace/jifu/data/data_json/radiology_text_reports/valid_reports.csv'
98
+ labels: '/workspace/jifu/data/data_json/multi_abnormality_labels/valid_predicted_labels.csv'
99
+
100
+ lightning:
101
+ callbacks:
102
+ image_logger:
103
+ target: main.ImageLogger
104
+ params:
105
+ batch_frequency: 200000000
106
+ max_images: 2
107
+ increase_log_steps: False
108
+
109
+ trainer:
110
+ max_epochs: 2000
111
+ benchmark: True
112
+ accumulate_grad_batches: 4
113
+ check_val_every_n_epoch: 100000
instruct-pix2pix-BioMedCLIP-concat-newdata/configs/train_3d.yaml ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File modified by authors of InstructPix2Pix from original (https://github.com/CompVis/stable-diffusion).
2
+ # See more details in LICENSE.
3
+
4
+ model:
5
+ base_learning_rate: 1.0e-04
6
+ target: ldm.models.diffusion.ddpm_edit_3d.LatentDiffusion
7
+ params:
8
+ linear_start: 0.00085
9
+ linear_end: 0.0120
10
+ num_timesteps_cond: 1
11
+ log_every_t: 200
12
+ timesteps: 1000
13
+ first_stage_key: edited
14
+ cond_stage_key: edit
15
+ image_size: 64
16
+ channels: 4
17
+ cond_stage_trainable: false # Note: different from the one we trained before
18
+ conditioning_key: hybrid
19
+ monitor: val/loss_simple_ema
20
+ scale_factor: 0.18215
21
+ use_ema: true
22
+ load_ema: false
23
+ ckpt_path: /sd/qichen/full_ct_gen/instruct-pix2pix-BioMedCLIP-concat/logs/train_instructpix2pix/checkpoints/epoch=000820.ckpt
24
+ load_only_unet: True
25
+
26
+ scheduler_config: # 10000 warmup steps
27
+ target: ldm.lr_scheduler.LambdaLinearScheduler
28
+ params:
29
+ warm_up_steps: [ 0 ]
30
+ cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases
31
+ f_start: [ 1.e-6 ]
32
+ f_max: [ 1. ]
33
+ f_min: [ 1. ]
34
+
35
+ unet_config:
36
+ target: ldm.modules.diffusionmodules.openaimodel_pseudo3D.UNetModel
37
+ params:
38
+ image_size: 32 # unused
39
+ in_channels: 8
40
+ out_channels: 4
41
+ model_channels: 320
42
+ attention_resolutions: [ 4, 2, 1 ]
43
+ num_res_blocks: 2
44
+ channel_mult: [ 1, 2, 4, 4 ]
45
+ num_heads: 8
46
+ use_spatial_transformer: True
47
+ transformer_depth: 1
48
+ context_dim: 768
49
+ use_checkpoint: True
50
+ legacy: False
51
+
52
+ first_stage_config:
53
+ target: ldm.models.autoencoder.AutoencoderKL
54
+ params:
55
+ embed_dim: 4
56
+ monitor: val/rec_loss
57
+ ddconfig:
58
+ double_z: true
59
+ z_channels: 4
60
+ resolution: 256
61
+ in_channels: 3
62
+ out_ch: 3
63
+ ch: 128
64
+ ch_mult:
65
+ - 1
66
+ - 2
67
+ - 4
68
+ - 4
69
+ num_res_blocks: 2
70
+ attn_resolutions: []
71
+ dropout: 0.0
72
+ lossconfig:
73
+ target: torch.nn.Identity
74
+
75
+ cond_stage_config:
76
+ target: ldm.modules.encoders.modules.FrozenBioMedCLIPEmbedder
77
+
78
+ data:
79
+ target: main.DataModuleFromConfig
80
+ params:
81
+ batch_size: 1
82
+ num_workers: 8
83
+ train:
84
+ target: ldm.data.ct_clip_data_train_3d.CTReportDataset
85
+ params:
86
+ data_folder: '/sd/shuhan/CT-RATE/dataset/train_fixed'
87
+ csv_file: '/sd/shuhan/CT-RATE/radiology_text_reports/train_reports.csv'
88
+
89
+ validation:
90
+ target: ldm.data.ct_clip_data_inference_3d.CTReportDatasetinfer
91
+ params:
92
+ data_folder: '/sd/shuhan/CT-RATE/dataset/valid_fixed'
93
+ csv_file: '/sd/shuhan/CT-RATE/radiology_text_reports/valid_reports.csv'
94
+ labels: '/sd/shuhan/CT-RATE/multi_abnormality_labels/valid_predicted_labels.csv'
95
+
96
+ lightning:
97
+ callbacks:
98
+ image_logger:
99
+ target: main.ImageLogger
100
+ params:
101
+ batch_frequency: 200000000000
102
+ max_images: 2
103
+ increase_log_steps: False
104
+
105
+ trainer:
106
+ max_epochs: 2000
107
+ benchmark: True
108
+ accumulate_grad_batches: 4
109
+ check_val_every_n_epoch: 4
instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/disease_mask_json/disease_train_single_prompt_checked_label.json ADDED
The diff for this file is too large to render. See raw diff
 
instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/disease_mask_json/disease_valid_single_prompt_checked_label.json ADDED
The diff for this file is too large to render. See raw diff
 
instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/metadata/Metadata_Attributes.xlsx ADDED
Binary file (11.9 kB). View file
 
instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/metadata/all_metadata.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:900be913106c93dc1e62dd7826af2a013f1b16a5e77a604592915ec5a6fd1213
3
+ size 15872544
instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/metadata/clip_-1000_1000.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import nibabel as nib
3
+ import pandas as pd
4
+ import numpy as np
5
+ from tqdm import tqdm
6
+ from concurrent.futures import ProcessPoolExecutor, as_completed
7
+
8
+
9
+ # ===== 路径 =====
10
+ DATA_ROOT = "/home/shuhan/blobdata/CT-RATE/dataset/"
11
+ TRAIN_META = "/home/shuhan/blobdata/CT-RATE/metadata/train_metadata.csv"
12
+ VALID_META = "/home/shuhan/blobdata/CT-RATE/metadata/validation_metadata.csv"
13
+
14
+ CLIP_RANGE = (-1000, 1000)
15
+ NUM_WORKERS = max(1, (os.cpu_count() or 8) - 1)
16
+
17
+ def build_full_path(basename):
18
+ """根据basename构造完整路径"""
19
+ # e.g. train_1661_b_1.nii.gz
20
+ stem = basename.replace(".nii.gz", "")
21
+ parts = stem.split("_") # ['train','1661','b','1']
22
+ if len(parts) < 3:
23
+ raise ValueError(f"basename格式异常: {basename}")
24
+ # train_fixed
25
+ folder0 = f"{parts[0]}_fixed"
26
+ # train_1661
27
+ folder1 = f"{parts[0]}_{parts[1]}"
28
+ # train_1661_b
29
+ folder2 = f"{parts[0]}_{parts[1]}_{parts[2]}"
30
+ return os.path.join(DATA_ROOT, folder0, folder1, folder2, basename)
31
+
32
+
33
+ def process_one(row):
34
+ """处理单个volume"""
35
+ basename = row["VolumeName"]
36
+ nii_path = build_full_path(basename)
37
+ if not os.path.exists(nii_path):
38
+ return f"[WARN] 文件不存在: {nii_path}"
39
+
40
+ try:
41
+ nii = nib.load(nii_path)
42
+ arr = nii.get_fdata().astype(np.float32)
43
+ vmin, vmax = float(arr.min()), float(arr.max())
44
+
45
+ # 如果已经在范围内,跳过
46
+ if vmin >= CLIP_RANGE[0] and vmax <= CLIP_RANGE[1]:
47
+ return f"[SKIP] {basename} 已在范围内 ({vmin:.1f},{vmax:.1f})"
48
+
49
+ # Clip 并保存覆盖
50
+ hu = np.clip(arr, CLIP_RANGE[0], CLIP_RANGE[1])
51
+ new_img = nib.Nifti1Image(hu, nii.affine, nii.header)
52
+ nib.save(new_img, nii_path)
53
+ return f"[OK] {basename} -> ({vmin:.1f},{vmax:.1f}) clipped"
54
+ except Exception as e:
55
+ return f"[ERROR] {nii_path}: {e}"
56
+
57
+ def process_meta(meta_csv):
58
+ df = pd.read_csv(meta_csv)
59
+ results = []
60
+ with ProcessPoolExecutor(max_workers=NUM_WORKERS) as ex:
61
+ futures = {ex.submit(process_one, row): row for _, row in df.iterrows()}
62
+ for fut in tqdm(as_completed(futures), total=len(futures), desc=f"Processing {os.path.basename(meta_csv)}"):
63
+ results.append(fut.result())
64
+ return results
65
+
66
+ if __name__ == "__main__":
67
+ # res_train = process_meta(TRAIN_META)
68
+ res_valid = process_meta(VALID_META)
69
+
70
+ # # 保存日志
71
+ # with open("clip_log.txt", "w") as f:
72
+ # f.write("\n".join(res_train + res_valid))
73
+ # print("完成。日志已保存 clip_log.txt")
instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/metadata/no_chest_train.txt ADDED
@@ -0,0 +1,752 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ train/train_10100/train_10100_a/train_10100_a_1.nii.gz
2
+ train/train_10100/train_10100_a/train_10100_a_2.nii.gz
3
+ train/train_10100/train_10100_a/train_10100_a_4.nii.gz
4
+ train/train_10303/train_10303_a/train_10303_a_1.nii.gz
5
+ train/train_10303/train_10303_a/train_10303_a_2.nii.gz
6
+ train/train_10303/train_10303_a/train_10303_a_4.nii.gz
7
+ train/train_10409/train_10409_a/train_10409_a_1.nii.gz
8
+ train/train_10409/train_10409_a/train_10409_a_2.nii.gz
9
+ train/train_10409/train_10409_a/train_10409_a_4.nii.gz
10
+ train/train_10487/train_10487_a/train_10487_a_1.nii.gz
11
+ train/train_10487/train_10487_a/train_10487_a_2.nii.gz
12
+ train/train_10487/train_10487_a/train_10487_a_4.nii.gz
13
+ train/train_10495/train_10495_a/train_10495_a_1.nii.gz
14
+ train/train_10495/train_10495_a/train_10495_a_2.nii.gz
15
+ train/train_10495/train_10495_a/train_10495_a_4.nii.gz
16
+ train/train_10712/train_10712_a/train_10712_a_1.nii.gz
17
+ train/train_10712/train_10712_a/train_10712_a_2.nii.gz
18
+ train/train_10712/train_10712_a/train_10712_a_4.nii.gz
19
+ train/train_10759/train_10759_a/train_10759_a_1.nii.gz
20
+ train/train_10759/train_10759_a/train_10759_a_2.nii.gz
21
+ train/train_10759/train_10759_a/train_10759_a_4.nii.gz
22
+ train/train_10791/train_10791_a/train_10791_a_1.nii.gz
23
+ train/train_10791/train_10791_a/train_10791_a_2.nii.gz
24
+ train/train_10791/train_10791_a/train_10791_a_4.nii.gz
25
+ train/train_10847/train_10847_a/train_10847_a_2.nii.gz
26
+ train/train_10877/train_10877_a/train_10877_a_2.nii.gz
27
+ train/train_11175/train_11175_a/train_11175_a_1.nii.gz
28
+ train/train_11175/train_11175_a/train_11175_a_2.nii.gz
29
+ train/train_11175/train_11175_a/train_11175_a_4.nii.gz
30
+ train/train_11279/train_11279_a/train_11279_a_1.nii.gz
31
+ train/train_11279/train_11279_a/train_11279_a_2.nii.gz
32
+ train/train_11279/train_11279_a/train_11279_a_4.nii.gz
33
+ train/train_11285/train_11285_a/train_11285_a_1.nii.gz
34
+ train/train_11285/train_11285_a/train_11285_a_2.nii.gz
35
+ train/train_11285/train_11285_a/train_11285_a_4.nii.gz
36
+ train/train_11306/train_11306_a/train_11306_a_1.nii.gz
37
+ train/train_11306/train_11306_a/train_11306_a_2.nii.gz
38
+ train/train_11306/train_11306_a/train_11306_a_4.nii.gz
39
+ train/train_1133/train_1133_a/train_1133_a_1.nii.gz
40
+ train/train_1133/train_1133_a/train_1133_a_2.nii.gz
41
+ train/train_1133/train_1133_a/train_1133_a_4.nii.gz
42
+ train/train_11401/train_11401_a/train_11401_a_1.nii.gz
43
+ train/train_11401/train_11401_a/train_11401_a_2.nii.gz
44
+ train/train_11401/train_11401_a/train_11401_a_3.nii.gz
45
+ train/train_11401/train_11401_a/train_11401_a_5.nii.gz
46
+ train/train_11466/train_11466_a/train_11466_a_1.nii.gz
47
+ train/train_11466/train_11466_a/train_11466_a_2.nii.gz
48
+ train/train_11466/train_11466_a/train_11466_a_4.nii.gz
49
+ train/train_11608/train_11608_a/train_11608_a_1.nii.gz
50
+ train/train_11608/train_11608_a/train_11608_a_2.nii.gz
51
+ train/train_11608/train_11608_a/train_11608_a_4.nii.gz
52
+ train/train_1162/train_1162_a/train_1162_a_1.nii.gz
53
+ train/train_1162/train_1162_a/train_1162_a_2.nii.gz
54
+ train/train_1162/train_1162_a/train_1162_a_4.nii.gz
55
+ train/train_11624/train_11624_a/train_11624_a_1.nii.gz
56
+ train/train_11624/train_11624_a/train_11624_a_2.nii.gz
57
+ train/train_11624/train_11624_a/train_11624_a_4.nii.gz
58
+ train/train_11657/train_11657_a/train_11657_a_1.nii.gz
59
+ train/train_11657/train_11657_a/train_11657_a_2.nii.gz
60
+ train/train_11657/train_11657_a/train_11657_a_4.nii.gz
61
+ train/train_11680/train_11680_a/train_11680_a_1.nii.gz
62
+ train/train_11880/train_11880_a/train_11880_a_1.nii.gz
63
+ train/train_11880/train_11880_a/train_11880_a_2.nii.gz
64
+ train/train_11880/train_11880_a/train_11880_a_4.nii.gz
65
+ train/train_11898/train_11898_a/train_11898_a_1.nii.gz
66
+ train/train_11898/train_11898_a/train_11898_a_2.nii.gz
67
+ train/train_11898/train_11898_a/train_11898_a_4.nii.gz
68
+ train/train_11983/train_11983_a/train_11983_a_1.nii.gz
69
+ train/train_11983/train_11983_a/train_11983_a_2.nii.gz
70
+ train/train_11983/train_11983_a/train_11983_a_4.nii.gz
71
+ train/train_12038/train_12038_a/train_12038_a_1.nii.gz
72
+ train/train_12038/train_12038_a/train_12038_a_2.nii.gz
73
+ train/train_12038/train_12038_a/train_12038_a_4.nii.gz
74
+ train/train_12048/train_12048_a/train_12048_a_2.nii.gz
75
+ train/train_12201/train_12201_a/train_12201_a_1.nii.gz
76
+ train/train_12201/train_12201_a/train_12201_a_2.nii.gz
77
+ train/train_12201/train_12201_a/train_12201_a_4.nii.gz
78
+ train/train_12226/train_12226_a/train_12226_a_1.nii.gz
79
+ train/train_12226/train_12226_a/train_12226_a_2.nii.gz
80
+ train/train_12226/train_12226_a/train_12226_a_4.nii.gz
81
+ train/train_12281/train_12281_a/train_12281_a_1.nii.gz
82
+ train/train_12281/train_12281_a/train_12281_a_2.nii.gz
83
+ train/train_12281/train_12281_a/train_12281_a_4.nii.gz
84
+ train/train_12302/train_12302_a/train_12302_a_1.nii.gz
85
+ train/train_12302/train_12302_a/train_12302_a_2.nii.gz
86
+ train/train_12302/train_12302_a/train_12302_a_4.nii.gz
87
+ train/train_12331/train_12331_a/train_12331_a_1.nii.gz
88
+ train/train_12331/train_12331_a/train_12331_a_2.nii.gz
89
+ train/train_12331/train_12331_a/train_12331_a_4.nii.gz
90
+ train/train_12373/train_12373_a/train_12373_a_1.nii.gz
91
+ train/train_12373/train_12373_a/train_12373_a_2.nii.gz
92
+ train/train_12373/train_12373_a/train_12373_a_4.nii.gz
93
+ train/train_12392/train_12392_d/train_12392_d_1.nii.gz
94
+ train/train_12392/train_12392_d/train_12392_d_2.nii.gz
95
+ train/train_12392/train_12392_d/train_12392_d_4.nii.gz
96
+ train/train_12402/train_12402_a/train_12402_a_1.nii.gz
97
+ train/train_12402/train_12402_a/train_12402_a_2.nii.gz
98
+ train/train_12402/train_12402_a/train_12402_a_4.nii.gz
99
+ train/train_12428/train_12428_a/train_12428_a_1.nii.gz
100
+ train/train_12428/train_12428_a/train_12428_a_2.nii.gz
101
+ train/train_12428/train_12428_a/train_12428_a_4.nii.gz
102
+ train/train_12467/train_12467_a/train_12467_a_1.nii.gz
103
+ train/train_12467/train_12467_a/train_12467_a_2.nii.gz
104
+ train/train_12467/train_12467_a/train_12467_a_4.nii.gz
105
+ train/train_12500/train_12500_a/train_12500_a_1.nii.gz
106
+ train/train_12500/train_12500_a/train_12500_a_2.nii.gz
107
+ train/train_12500/train_12500_a/train_12500_a_4.nii.gz
108
+ train/train_12525/train_12525_a/train_12525_a_1.nii.gz
109
+ train/train_12525/train_12525_a/train_12525_a_2.nii.gz
110
+ train/train_12525/train_12525_a/train_12525_a_4.nii.gz
111
+ train/train_12563/train_12563_a/train_12563_a_1.nii.gz
112
+ train/train_12563/train_12563_a/train_12563_a_2.nii.gz
113
+ train/train_12563/train_12563_a/train_12563_a_4.nii.gz
114
+ train/train_12573/train_12573_a/train_12573_a_1.nii.gz
115
+ train/train_12573/train_12573_a/train_12573_a_2.nii.gz
116
+ train/train_12573/train_12573_a/train_12573_a_4.nii.gz
117
+ train/train_12625/train_12625_b/train_12625_b_1.nii.gz
118
+ train/train_12625/train_12625_b/train_12625_b_2.nii.gz
119
+ train/train_12625/train_12625_b/train_12625_b_4.nii.gz
120
+ train/train_1304/train_1304_b/train_1304_b_1.nii.gz
121
+ train/train_1304/train_1304_b/train_1304_b_2.nii.gz
122
+ train/train_1304/train_1304_b/train_1304_b_4.nii.gz
123
+ train/train_13063/train_13063_a/train_13063_a_1.nii.gz
124
+ train/train_13063/train_13063_a/train_13063_a_2.nii.gz
125
+ train/train_13063/train_13063_a/train_13063_a_4.nii.gz
126
+ train/train_13067/train_13067_a/train_13067_a_1.nii.gz
127
+ train/train_13067/train_13067_a/train_13067_a_2.nii.gz
128
+ train/train_13067/train_13067_a/train_13067_a_4.nii.gz
129
+ train/train_13286/train_13286_a/train_13286_a_1.nii.gz
130
+ train/train_13286/train_13286_a/train_13286_a_2.nii.gz
131
+ train/train_13286/train_13286_a/train_13286_a_4.nii.gz
132
+ train/train_13320/train_13320_a/train_13320_a_1.nii.gz
133
+ train/train_13320/train_13320_a/train_13320_a_2.nii.gz
134
+ train/train_13320/train_13320_a/train_13320_a_4.nii.gz
135
+ train/train_13334/train_13334_a/train_13334_a_1.nii.gz
136
+ train/train_13334/train_13334_a/train_13334_a_2.nii.gz
137
+ train/train_13334/train_13334_a/train_13334_a_4.nii.gz
138
+ train/train_13442/train_13442_a/train_13442_a_3.nii.gz
139
+ train/train_13455/train_13455_a/train_13455_a_1.nii.gz
140
+ train/train_13455/train_13455_a/train_13455_a_2.nii.gz
141
+ train/train_13455/train_13455_a/train_13455_a_4.nii.gz
142
+ train/train_13457/train_13457_a/train_13457_a_1.nii.gz
143
+ train/train_13457/train_13457_a/train_13457_a_2.nii.gz
144
+ train/train_13457/train_13457_a/train_13457_a_4.nii.gz
145
+ train/train_13556/train_13556_d/train_13556_d_1.nii.gz
146
+ train/train_13556/train_13556_d/train_13556_d_4.nii.gz
147
+ train/train_13596/train_13596_a/train_13596_a_3.nii.gz
148
+ train/train_13732/train_13732_a/train_13732_a_1.nii.gz
149
+ train/train_13732/train_13732_a/train_13732_a_2.nii.gz
150
+ train/train_13732/train_13732_a/train_13732_a_4.nii.gz
151
+ train/train_13739/train_13739_a/train_13739_a_1.nii.gz
152
+ train/train_13739/train_13739_a/train_13739_a_2.nii.gz
153
+ train/train_13739/train_13739_a/train_13739_a_4.nii.gz
154
+ train/train_13739/train_13739_a/train_13739_a_5.nii.gz
155
+ train/train_13905/train_13905_a/train_13905_a_1.nii.gz
156
+ train/train_13905/train_13905_a/train_13905_a_2.nii.gz
157
+ train/train_13905/train_13905_a/train_13905_a_4.nii.gz
158
+ train/train_13934/train_13934_a/train_13934_a_1.nii.gz
159
+ train/train_13934/train_13934_a/train_13934_a_2.nii.gz
160
+ train/train_13934/train_13934_a/train_13934_a_4.nii.gz
161
+ train/train_14077/train_14077_a/train_14077_a_1.nii.gz
162
+ train/train_14077/train_14077_a/train_14077_a_2.nii.gz
163
+ train/train_14077/train_14077_a/train_14077_a_4.nii.gz
164
+ train/train_14096/train_14096_a/train_14096_a_1.nii.gz
165
+ train/train_14096/train_14096_a/train_14096_a_2.nii.gz
166
+ train/train_14096/train_14096_a/train_14096_a_4.nii.gz
167
+ train/train_1413/train_1413_a/train_1413_a_1.nii.gz
168
+ train/train_1413/train_1413_a/train_1413_a_2.nii.gz
169
+ train/train_1413/train_1413_a/train_1413_a_4.nii.gz
170
+ train/train_14156/train_14156_a/train_14156_a_1.nii.gz
171
+ train/train_14156/train_14156_a/train_14156_a_2.nii.gz
172
+ train/train_14156/train_14156_a/train_14156_a_4.nii.gz
173
+ train/train_14174/train_14174_a/train_14174_a_1.nii.gz
174
+ train/train_14174/train_14174_a/train_14174_a_2.nii.gz
175
+ train/train_14174/train_14174_a/train_14174_a_4.nii.gz
176
+ train/train_14197/train_14197_a/train_14197_a_1.nii.gz
177
+ train/train_14197/train_14197_a/train_14197_a_2.nii.gz
178
+ train/train_14197/train_14197_a/train_14197_a_4.nii.gz
179
+ train/train_14255/train_14255_a/train_14255_a_1.nii.gz
180
+ train/train_14255/train_14255_a/train_14255_a_2.nii.gz
181
+ train/train_14255/train_14255_a/train_14255_a_4.nii.gz
182
+ train/train_14359/train_14359_b/train_14359_b_1.nii.gz
183
+ train/train_14359/train_14359_b/train_14359_b_2.nii.gz
184
+ train/train_14359/train_14359_b/train_14359_b_4.nii.gz
185
+ train/train_144/train_144_a/train_144_a_1.nii.gz
186
+ train/train_144/train_144_a/train_144_a_2.nii.gz
187
+ train/train_144/train_144_a/train_144_a_4.nii.gz
188
+ train/train_14481/train_14481_a/train_14481_a_1.nii.gz
189
+ train/train_14481/train_14481_a/train_14481_a_2.nii.gz
190
+ train/train_14481/train_14481_a/train_14481_a_4.nii.gz
191
+ train/train_14572/train_14572_a/train_14572_a_1.nii.gz
192
+ train/train_14572/train_14572_a/train_14572_a_2.nii.gz
193
+ train/train_14572/train_14572_a/train_14572_a_4.nii.gz
194
+ train/train_1458/train_1458_a/train_1458_a_1.nii.gz
195
+ train/train_1458/train_1458_a/train_1458_a_3.nii.gz
196
+ train/train_14597/train_14597_a/train_14597_a_1.nii.gz
197
+ train/train_14597/train_14597_a/train_14597_a_2.nii.gz
198
+ train/train_14597/train_14597_a/train_14597_a_4.nii.gz
199
+ train/train_1471/train_1471_b/train_1471_b_1.nii.gz
200
+ train/train_1471/train_1471_b/train_1471_b_2.nii.gz
201
+ train/train_1471/train_1471_b/train_1471_b_4.nii.gz
202
+ train/train_14879/train_14879_a/train_14879_a_2.nii.gz
203
+ train/train_14879/train_14879_a/train_14879_a_4.nii.gz
204
+ train/train_15187/train_15187_a/train_15187_a_1.nii.gz
205
+ train/train_15187/train_15187_a/train_15187_a_2.nii.gz
206
+ train/train_15187/train_15187_a/train_15187_a_4.nii.gz
207
+ train/train_15285/train_15285_d/train_15285_d_1.nii.gz
208
+ train/train_15285/train_15285_d/train_15285_d_2.nii.gz
209
+ train/train_15285/train_15285_d/train_15285_d_4.nii.gz
210
+ train/train_15379/train_15379_a/train_15379_a_1.nii.gz
211
+ train/train_15379/train_15379_a/train_15379_a_2.nii.gz
212
+ train/train_15379/train_15379_a/train_15379_a_4.nii.gz
213
+ train/train_1539/train_1539_a/train_1539_a_1.nii.gz
214
+ train/train_1539/train_1539_a/train_1539_a_2.nii.gz
215
+ train/train_1539/train_1539_a/train_1539_a_4.nii.gz
216
+ train/train_1556/train_1556_a/train_1556_a_1.nii.gz
217
+ train/train_1556/train_1556_a/train_1556_a_2.nii.gz
218
+ train/train_1556/train_1556_a/train_1556_a_4.nii.gz
219
+ train/train_15637/train_15637_a/train_15637_a_3.nii.gz
220
+ train/train_15671/train_15671_a/train_15671_a_1.nii.gz
221
+ train/train_15671/train_15671_a/train_15671_a_2.nii.gz
222
+ train/train_15671/train_15671_a/train_15671_a_4.nii.gz
223
+ train/train_15989/train_15989_a/train_15989_a_1.nii.gz
224
+ train/train_15989/train_15989_a/train_15989_a_2.nii.gz
225
+ train/train_15989/train_15989_a/train_15989_a_4.nii.gz
226
+ train/train_16069/train_16069_a/train_16069_a_1.nii.gz
227
+ train/train_16069/train_16069_a/train_16069_a_2.nii.gz
228
+ train/train_16069/train_16069_a/train_16069_a_4.nii.gz
229
+ train/train_16174/train_16174_a/train_16174_a_1.nii.gz
230
+ train/train_16174/train_16174_a/train_16174_a_2.nii.gz
231
+ train/train_16174/train_16174_a/train_16174_a_4.nii.gz
232
+ train/train_16261/train_16261_a/train_16261_a_1.nii.gz
233
+ train/train_16261/train_16261_a/train_16261_a_2.nii.gz
234
+ train/train_16261/train_16261_a/train_16261_a_4.nii.gz
235
+ train/train_16278/train_16278_a/train_16278_a_1.nii.gz
236
+ train/train_16278/train_16278_a/train_16278_a_2.nii.gz
237
+ train/train_16278/train_16278_a/train_16278_a_4.nii.gz
238
+ train/train_16456/train_16456_a/train_16456_a_1.nii.gz
239
+ train/train_16456/train_16456_a/train_16456_a_2.nii.gz
240
+ train/train_16456/train_16456_a/train_16456_a_4.nii.gz
241
+ train/train_16590/train_16590_a/train_16590_a_1.nii.gz
242
+ train/train_16590/train_16590_a/train_16590_a_2.nii.gz
243
+ train/train_16590/train_16590_a/train_16590_a_4.nii.gz
244
+ train/train_16618/train_16618_a/train_16618_a_1.nii.gz
245
+ train/train_16618/train_16618_a/train_16618_a_2.nii.gz
246
+ train/train_16618/train_16618_a/train_16618_a_4.nii.gz
247
+ train/train_16664/train_16664_a/train_16664_a_1.nii.gz
248
+ train/train_16664/train_16664_a/train_16664_a_2.nii.gz
249
+ train/train_16664/train_16664_a/train_16664_a_4.nii.gz
250
+ train/train_16698/train_16698_a/train_16698_a_1.nii.gz
251
+ train/train_16698/train_16698_a/train_16698_a_2.nii.gz
252
+ train/train_16698/train_16698_a/train_16698_a_4.nii.gz
253
+ train/train_16717/train_16717_a/train_16717_a_1.nii.gz
254
+ train/train_16717/train_16717_a/train_16717_a_2.nii.gz
255
+ train/train_16717/train_16717_a/train_16717_a_4.nii.gz
256
+ train/train_16721/train_16721_a/train_16721_a_1.nii.gz
257
+ train/train_16721/train_16721_a/train_16721_a_2.nii.gz
258
+ train/train_16721/train_16721_a/train_16721_a_4.nii.gz
259
+ train/train_16721/train_16721_b/train_16721_b_1.nii.gz
260
+ train/train_16721/train_16721_b/train_16721_b_2.nii.gz
261
+ train/train_16721/train_16721_b/train_16721_b_4.nii.gz
262
+ train/train_16730/train_16730_a/train_16730_a_1.nii.gz
263
+ train/train_16730/train_16730_a/train_16730_a_2.nii.gz
264
+ train/train_16730/train_16730_a/train_16730_a_4.nii.gz
265
+ train/train_16828/train_16828_a/train_16828_a_1.nii.gz
266
+ train/train_16828/train_16828_a/train_16828_a_2.nii.gz
267
+ train/train_16828/train_16828_a/train_16828_a_4.nii.gz
268
+ train/train_17097/train_17097_a/train_17097_a_1.nii.gz
269
+ train/train_17097/train_17097_a/train_17097_a_2.nii.gz
270
+ train/train_17097/train_17097_a/train_17097_a_4.nii.gz
271
+ train/train_17171/train_17171_a/train_17171_a_1.nii.gz
272
+ train/train_17171/train_17171_a/train_17171_a_2.nii.gz
273
+ train/train_17171/train_17171_a/train_17171_a_4.nii.gz
274
+ train/train_17296/train_17296_a/train_17296_a_1.nii.gz
275
+ train/train_17296/train_17296_a/train_17296_a_2.nii.gz
276
+ train/train_17296/train_17296_a/train_17296_a_4.nii.gz
277
+ train/train_17314/train_17314_a/train_17314_a_1.nii.gz
278
+ train/train_17314/train_17314_a/train_17314_a_2.nii.gz
279
+ train/train_17314/train_17314_a/train_17314_a_4.nii.gz
280
+ train/train_17330/train_17330_b/train_17330_b_1.nii.gz
281
+ train/train_17330/train_17330_b/train_17330_b_2.nii.gz
282
+ train/train_17330/train_17330_b/train_17330_b_4.nii.gz
283
+ train/train_17373/train_17373_a/train_17373_a_1.nii.gz
284
+ train/train_17373/train_17373_a/train_17373_a_2.nii.gz
285
+ train/train_17373/train_17373_a/train_17373_a_4.nii.gz
286
+ train/train_17397/train_17397_a/train_17397_a_1.nii.gz
287
+ train/train_17397/train_17397_a/train_17397_a_2.nii.gz
288
+ train/train_17397/train_17397_a/train_17397_a_4.nii.gz
289
+ train/train_17398/train_17398_a/train_17398_a_1.nii.gz
290
+ train/train_17398/train_17398_a/train_17398_a_2.nii.gz
291
+ train/train_17398/train_17398_a/train_17398_a_4.nii.gz
292
+ train/train_17518/train_17518_a/train_17518_a_1.nii.gz
293
+ train/train_17518/train_17518_a/train_17518_a_2.nii.gz
294
+ train/train_17518/train_17518_a/train_17518_a_4.nii.gz
295
+ train/train_17531/train_17531_a/train_17531_a_1.nii.gz
296
+ train/train_17531/train_17531_a/train_17531_a_2.nii.gz
297
+ train/train_17531/train_17531_a/train_17531_a_4.nii.gz
298
+ train/train_17772/train_17772_a/train_17772_a_1.nii.gz
299
+ train/train_17772/train_17772_a/train_17772_a_2.nii.gz
300
+ train/train_17772/train_17772_a/train_17772_a_4.nii.gz
301
+ train/train_17781/train_17781_a/train_17781_a_1.nii.gz
302
+ train/train_17781/train_17781_a/train_17781_a_2.nii.gz
303
+ train/train_17781/train_17781_a/train_17781_a_4.nii.gz
304
+ train/train_17867/train_17867_a/train_17867_a_1.nii.gz
305
+ train/train_17867/train_17867_a/train_17867_a_2.nii.gz
306
+ train/train_17867/train_17867_a/train_17867_a_4.nii.gz
307
+ train/train_17867/train_17867_a/train_17867_a_5.nii.gz
308
+ train/train_17919/train_17919_a/train_17919_a_1.nii.gz
309
+ train/train_17919/train_17919_a/train_17919_a_2.nii.gz
310
+ train/train_17919/train_17919_a/train_17919_a_4.nii.gz
311
+ train/train_18046/train_18046_a/train_18046_a_1.nii.gz
312
+ train/train_18046/train_18046_a/train_18046_a_2.nii.gz
313
+ train/train_18046/train_18046_a/train_18046_a_4.nii.gz
314
+ train/train_18069/train_18069_a/train_18069_a_1.nii.gz
315
+ train/train_18069/train_18069_a/train_18069_a_2.nii.gz
316
+ train/train_18069/train_18069_a/train_18069_a_4.nii.gz
317
+ train/train_1815/train_1815_a/train_1815_a_1.nii.gz
318
+ train/train_1815/train_1815_a/train_1815_a_2.nii.gz
319
+ train/train_1815/train_1815_a/train_1815_a_4.nii.gz
320
+ train/train_18161/train_18161_a/train_18161_a_1.nii.gz
321
+ train/train_18161/train_18161_a/train_18161_a_2.nii.gz
322
+ train/train_18161/train_18161_a/train_18161_a_4.nii.gz
323
+ train/train_18338/train_18338_a/train_18338_a_1.nii.gz
324
+ train/train_18338/train_18338_a/train_18338_a_2.nii.gz
325
+ train/train_18338/train_18338_a/train_18338_a_4.nii.gz
326
+ train/train_18410/train_18410_a/train_18410_a_1.nii.gz
327
+ train/train_18410/train_18410_a/train_18410_a_2.nii.gz
328
+ train/train_18410/train_18410_a/train_18410_a_4.nii.gz
329
+ train/train_1845/train_1845_a/train_1845_a_1.nii.gz
330
+ train/train_1845/train_1845_a/train_1845_a_2.nii.gz
331
+ train/train_1845/train_1845_a/train_1845_a_4.nii.gz
332
+ train/train_18619/train_18619_a/train_18619_a_1.nii.gz
333
+ train/train_18619/train_18619_a/train_18619_a_2.nii.gz
334
+ train/train_18619/train_18619_a/train_18619_a_4.nii.gz
335
+ train/train_18626/train_18626_a/train_18626_a_1.nii.gz
336
+ train/train_18626/train_18626_a/train_18626_a_2.nii.gz
337
+ train/train_18626/train_18626_a/train_18626_a_4.nii.gz
338
+ train/train_18676/train_18676_a/train_18676_a_6.nii.gz
339
+ train/train_18709/train_18709_b/train_18709_b_1.nii.gz
340
+ train/train_18709/train_18709_b/train_18709_b_2.nii.gz
341
+ train/train_18709/train_18709_b/train_18709_b_4.nii.gz
342
+ train/train_18741/train_18741_a/train_18741_a_1.nii.gz
343
+ train/train_18741/train_18741_a/train_18741_a_2.nii.gz
344
+ train/train_18741/train_18741_a/train_18741_a_4.nii.gz
345
+ train/train_18910/train_18910_b/train_18910_b_1.nii.gz
346
+ train/train_18910/train_18910_b/train_18910_b_2.nii.gz
347
+ train/train_18910/train_18910_b/train_18910_b_4.nii.gz
348
+ train/train_18952/train_18952_a/train_18952_a_1.nii.gz
349
+ train/train_18952/train_18952_a/train_18952_a_2.nii.gz
350
+ train/train_18952/train_18952_a/train_18952_a_4.nii.gz
351
+ train/train_19158/train_19158_a/train_19158_a_1.nii.gz
352
+ train/train_19158/train_19158_a/train_19158_a_2.nii.gz
353
+ train/train_19158/train_19158_a/train_19158_a_4.nii.gz
354
+ train/train_19220/train_19220_a/train_19220_a_1.nii.gz
355
+ train/train_19220/train_19220_a/train_19220_a_2.nii.gz
356
+ train/train_19220/train_19220_a/train_19220_a_4.nii.gz
357
+ train/train_19433/train_19433_a/train_19433_a_1.nii.gz
358
+ train/train_19433/train_19433_a/train_19433_a_2.nii.gz
359
+ train/train_19433/train_19433_a/train_19433_a_4.nii.gz
360
+ train/train_19447/train_19447_a/train_19447_a_1.nii.gz
361
+ train/train_19447/train_19447_a/train_19447_a_2.nii.gz
362
+ train/train_19447/train_19447_a/train_19447_a_4.nii.gz
363
+ train/train_19503/train_19503_a/train_19503_a_1.nii.gz
364
+ train/train_19503/train_19503_a/train_19503_a_2.nii.gz
365
+ train/train_19503/train_19503_a/train_19503_a_4.nii.gz
366
+ train/train_19507/train_19507_a/train_19507_a_1.nii.gz
367
+ train/train_19507/train_19507_a/train_19507_a_2.nii.gz
368
+ train/train_19507/train_19507_a/train_19507_a_4.nii.gz
369
+ train/train_19508/train_19508_a/train_19508_a_1.nii.gz
370
+ train/train_19508/train_19508_a/train_19508_a_2.nii.gz
371
+ train/train_19508/train_19508_a/train_19508_a_4.nii.gz
372
+ train/train_19590/train_19590_a/train_19590_a_1.nii.gz
373
+ train/train_19590/train_19590_a/train_19590_a_2.nii.gz
374
+ train/train_19590/train_19590_a/train_19590_a_4.nii.gz
375
+ train/train_19600/train_19600_a/train_19600_a_1.nii.gz
376
+ train/train_19600/train_19600_a/train_19600_a_2.nii.gz
377
+ train/train_19600/train_19600_a/train_19600_a_4.nii.gz
378
+ train/train_19640/train_19640_a/train_19640_a_1.nii.gz
379
+ train/train_19640/train_19640_a/train_19640_a_2.nii.gz
380
+ train/train_19640/train_19640_a/train_19640_a_4.nii.gz
381
+ train/train_1978/train_1978_a/train_1978_a_1.nii.gz
382
+ train/train_1978/train_1978_a/train_1978_a_2.nii.gz
383
+ train/train_1978/train_1978_a/train_1978_a_4.nii.gz
384
+ train/train_19901/train_19901_a/train_19901_a_1.nii.gz
385
+ train/train_19901/train_19901_a/train_19901_a_2.nii.gz
386
+ train/train_19901/train_19901_a/train_19901_a_4.nii.gz
387
+ train/train_19946/train_19946_a/train_19946_a_1.nii.gz
388
+ train/train_19946/train_19946_a/train_19946_a_2.nii.gz
389
+ train/train_19946/train_19946_a/train_19946_a_4.nii.gz
390
+ train/train_19972/train_19972_b/train_19972_b_1.nii.gz
391
+ train/train_19972/train_19972_b/train_19972_b_2.nii.gz
392
+ train/train_19972/train_19972_b/train_19972_b_4.nii.gz
393
+ train/train_19977/train_19977_a/train_19977_a_1.nii.gz
394
+ train/train_19977/train_19977_a/train_19977_a_2.nii.gz
395
+ train/train_19977/train_19977_a/train_19977_a_4.nii.gz
396
+ train/train_208/train_208_a/train_208_a_1.nii.gz
397
+ train/train_208/train_208_a/train_208_a_2.nii.gz
398
+ train/train_208/train_208_a/train_208_a_4.nii.gz
399
+ train/train_2151/train_2151_a/train_2151_a_2.nii.gz
400
+ train/train_2159/train_2159_a/train_2159_a_1.nii.gz
401
+ train/train_2159/train_2159_a/train_2159_a_2.nii.gz
402
+ train/train_2159/train_2159_a/train_2159_a_4.nii.gz
403
+ train/train_2168/train_2168_a/train_2168_a_1.nii.gz
404
+ train/train_2168/train_2168_a/train_2168_a_2.nii.gz
405
+ train/train_2168/train_2168_a/train_2168_a_4.nii.gz
406
+ train/train_2220/train_2220_a/train_2220_a_1.nii.gz
407
+ train/train_2220/train_2220_a/train_2220_a_2.nii.gz
408
+ train/train_2220/train_2220_a/train_2220_a_4.nii.gz
409
+ train/train_2235/train_2235_a/train_2235_a_1.nii.gz
410
+ train/train_2235/train_2235_a/train_2235_a_2.nii.gz
411
+ train/train_2235/train_2235_a/train_2235_a_4.nii.gz
412
+ train/train_2238/train_2238_a/train_2238_a_1.nii.gz
413
+ train/train_2238/train_2238_a/train_2238_a_2.nii.gz
414
+ train/train_2238/train_2238_a/train_2238_a_4.nii.gz
415
+ train/train_2342/train_2342_a/train_2342_a_1.nii.gz
416
+ train/train_2342/train_2342_a/train_2342_a_2.nii.gz
417
+ train/train_2342/train_2342_a/train_2342_a_4.nii.gz
418
+ train/train_2345/train_2345_a/train_2345_a_1.nii.gz
419
+ train/train_2345/train_2345_a/train_2345_a_2.nii.gz
420
+ train/train_2345/train_2345_a/train_2345_a_4.nii.gz
421
+ train/train_2524/train_2524_a/train_2524_a_1.nii.gz
422
+ train/train_2524/train_2524_a/train_2524_a_2.nii.gz
423
+ train/train_2524/train_2524_a/train_2524_a_4.nii.gz
424
+ train/train_2560/train_2560_a/train_2560_a_1.nii.gz
425
+ train/train_2560/train_2560_a/train_2560_a_4.nii.gz
426
+ train/train_2597/train_2597_a/train_2597_a_2.nii.gz
427
+ train/train_2674/train_2674_a/train_2674_a_1.nii.gz
428
+ train/train_2674/train_2674_a/train_2674_a_2.nii.gz
429
+ train/train_2674/train_2674_a/train_2674_a_4.nii.gz
430
+ train/train_2730/train_2730_a/train_2730_a_1.nii.gz
431
+ train/train_2730/train_2730_a/train_2730_a_2.nii.gz
432
+ train/train_2730/train_2730_a/train_2730_a_4.nii.gz
433
+ train/train_2840/train_2840_b/train_2840_b_3.nii.gz
434
+ train/train_2855/train_2855_a/train_2855_a_1.nii.gz
435
+ train/train_2855/train_2855_a/train_2855_a_2.nii.gz
436
+ train/train_2855/train_2855_a/train_2855_a_4.nii.gz
437
+ train/train_2871/train_2871_a/train_2871_a_1.nii.gz
438
+ train/train_2871/train_2871_a/train_2871_a_2.nii.gz
439
+ train/train_2871/train_2871_a/train_2871_a_3.nii.gz
440
+ train/train_2871/train_2871_a/train_2871_a_5.nii.gz
441
+ train/train_290/train_290_a/train_290_a_1.nii.gz
442
+ train/train_290/train_290_a/train_290_a_4.nii.gz
443
+ train/train_291/train_291_a/train_291_a_1.nii.gz
444
+ train/train_3016/train_3016_a/train_3016_a_1.nii.gz
445
+ train/train_3016/train_3016_a/train_3016_a_2.nii.gz
446
+ train/train_3016/train_3016_a/train_3016_a_4.nii.gz
447
+ train/train_3104/train_3104_a/train_3104_a_1.nii.gz
448
+ train/train_3114/train_3114_a/train_3114_a_1.nii.gz
449
+ train/train_3114/train_3114_a/train_3114_a_2.nii.gz
450
+ train/train_3114/train_3114_a/train_3114_a_4.nii.gz
451
+ train/train_3160/train_3160_a/train_3160_a_1.nii.gz
452
+ train/train_3160/train_3160_a/train_3160_a_2.nii.gz
453
+ train/train_3160/train_3160_a/train_3160_a_4.nii.gz
454
+ train/train_3171/train_3171_a/train_3171_a_1.nii.gz
455
+ train/train_3171/train_3171_a/train_3171_a_2.nii.gz
456
+ train/train_3171/train_3171_a/train_3171_a_4.nii.gz
457
+ train/train_3189/train_3189_a/train_3189_a_1.nii.gz
458
+ train/train_3189/train_3189_a/train_3189_a_2.nii.gz
459
+ train/train_3189/train_3189_a/train_3189_a_4.nii.gz
460
+ train/train_3278/train_3278_a/train_3278_a_1.nii.gz
461
+ train/train_3278/train_3278_a/train_3278_a_4.nii.gz
462
+ train/train_3326/train_3326_b/train_3326_b_1.nii.gz
463
+ train/train_3326/train_3326_b/train_3326_b_2.nii.gz
464
+ train/train_3326/train_3326_b/train_3326_b_4.nii.gz
465
+ train/train_3510/train_3510_a/train_3510_a_1.nii.gz
466
+ train/train_3510/train_3510_a/train_3510_a_2.nii.gz
467
+ train/train_3510/train_3510_a/train_3510_a_4.nii.gz
468
+ train/train_3653/train_3653_d/train_3653_d_1.nii.gz
469
+ train/train_3653/train_3653_d/train_3653_d_2.nii.gz
470
+ train/train_3653/train_3653_d/train_3653_d_4.nii.gz
471
+ train/train_3734/train_3734_a/train_3734_a_1.nii.gz
472
+ train/train_3734/train_3734_a/train_3734_a_2.nii.gz
473
+ train/train_3734/train_3734_a/train_3734_a_4.nii.gz
474
+ train/train_3740/train_3740_a/train_3740_a_1.nii.gz
475
+ train/train_3740/train_3740_a/train_3740_a_2.nii.gz
476
+ train/train_3740/train_3740_a/train_3740_a_4.nii.gz
477
+ train/train_3808/train_3808_a/train_3808_a_1.nii.gz
478
+ train/train_3808/train_3808_a/train_3808_a_2.nii.gz
479
+ train/train_3808/train_3808_a/train_3808_a_4.nii.gz
480
+ train/train_3821/train_3821_a/train_3821_a_1.nii.gz
481
+ train/train_3821/train_3821_a/train_3821_a_2.nii.gz
482
+ train/train_3821/train_3821_a/train_3821_a_4.nii.gz
483
+ train/train_3821/train_3821_a/train_3821_a_5.nii.gz
484
+ train/train_385/train_385_a/train_385_a_1.nii.gz
485
+ train/train_385/train_385_a/train_385_a_2.nii.gz
486
+ train/train_385/train_385_a/train_385_a_4.nii.gz
487
+ train/train_39/train_39_b/train_39_b_1.nii.gz
488
+ train/train_39/train_39_b/train_39_b_2.nii.gz
489
+ train/train_39/train_39_b/train_39_b_4.nii.gz
490
+ train/train_3922/train_3922_a/train_3922_a_3.nii.gz
491
+ train/train_4063/train_4063_a/train_4063_a_1.nii.gz
492
+ train/train_4063/train_4063_a/train_4063_a_2.nii.gz
493
+ train/train_4063/train_4063_a/train_4063_a_4.nii.gz
494
+ train/train_4147/train_4147_a/train_4147_a_2.nii.gz
495
+ train/train_4200/train_4200_a/train_4200_a_1.nii.gz
496
+ train/train_4200/train_4200_a/train_4200_a_2.nii.gz
497
+ train/train_4200/train_4200_a/train_4200_a_4.nii.gz
498
+ train/train_4254/train_4254_a/train_4254_a_1.nii.gz
499
+ train/train_4254/train_4254_a/train_4254_a_2.nii.gz
500
+ train/train_4254/train_4254_a/train_4254_a_4.nii.gz
501
+ train/train_4288/train_4288_a/train_4288_a_1.nii.gz
502
+ train/train_4288/train_4288_a/train_4288_a_2.nii.gz
503
+ train/train_4288/train_4288_a/train_4288_a_3.nii.gz
504
+ train/train_4288/train_4288_a/train_4288_a_5.nii.gz
505
+ train/train_431/train_431_a/train_431_a_1.nii.gz
506
+ train/train_431/train_431_a/train_431_a_2.nii.gz
507
+ train/train_431/train_431_a/train_431_a_4.nii.gz
508
+ train/train_4340/train_4340_a/train_4340_a_1.nii.gz
509
+ train/train_4340/train_4340_a/train_4340_a_2.nii.gz
510
+ train/train_4340/train_4340_a/train_4340_a_4.nii.gz
511
+ train/train_4520/train_4520_d/train_4520_d_1.nii.gz
512
+ train/train_4520/train_4520_d/train_4520_d_2.nii.gz
513
+ train/train_4520/train_4520_d/train_4520_d_4.nii.gz
514
+ train/train_4556/train_4556_a/train_4556_a_1.nii.gz
515
+ train/train_4556/train_4556_a/train_4556_a_2.nii.gz
516
+ train/train_4556/train_4556_a/train_4556_a_4.nii.gz
517
+ train/train_4679/train_4679_a/train_4679_a_1.nii.gz
518
+ train/train_4685/train_4685_a/train_4685_a_1.nii.gz
519
+ train/train_4685/train_4685_a/train_4685_a_2.nii.gz
520
+ train/train_4685/train_4685_a/train_4685_a_4.nii.gz
521
+ train/train_47/train_47_a/train_47_a_1.nii.gz
522
+ train/train_47/train_47_a/train_47_a_2.nii.gz
523
+ train/train_47/train_47_a/train_47_a_4.nii.gz
524
+ train/train_4801/train_4801_a/train_4801_a_2.nii.gz
525
+ train/train_4867/train_4867_a/train_4867_a_1.nii.gz
526
+ train/train_4867/train_4867_a/train_4867_a_2.nii.gz
527
+ train/train_4867/train_4867_a/train_4867_a_4.nii.gz
528
+ train/train_4942/train_4942_a/train_4942_a_1.nii.gz
529
+ train/train_4942/train_4942_a/train_4942_a_2.nii.gz
530
+ train/train_4942/train_4942_a/train_4942_a_4.nii.gz
531
+ train/train_4982/train_4982_a/train_4982_a_1.nii.gz
532
+ train/train_4982/train_4982_a/train_4982_a_2.nii.gz
533
+ train/train_4982/train_4982_a/train_4982_a_4.nii.gz
534
+ train/train_5019/train_5019_a/train_5019_a_1.nii.gz
535
+ train/train_5019/train_5019_a/train_5019_a_2.nii.gz
536
+ train/train_5019/train_5019_a/train_5019_a_4.nii.gz
537
+ train/train_518/train_518_j/train_518_j_1.nii.gz
538
+ train/train_518/train_518_j/train_518_j_2.nii.gz
539
+ train/train_5193/train_5193_f/train_5193_f_2.nii.gz
540
+ train/train_5200/train_5200_a/train_5200_a_1.nii.gz
541
+ train/train_5200/train_5200_a/train_5200_a_2.nii.gz
542
+ train/train_5200/train_5200_a/train_5200_a_4.nii.gz
543
+ train/train_5228/train_5228_a/train_5228_a_1.nii.gz
544
+ train/train_5228/train_5228_a/train_5228_a_2.nii.gz
545
+ train/train_5228/train_5228_a/train_5228_a_4.nii.gz
546
+ train/train_5247/train_5247_a/train_5247_a_1.nii.gz
547
+ train/train_5247/train_5247_a/train_5247_a_2.nii.gz
548
+ train/train_5247/train_5247_a/train_5247_a_4.nii.gz
549
+ train/train_5398/train_5398_a/train_5398_a_1.nii.gz
550
+ train/train_5398/train_5398_a/train_5398_a_2.nii.gz
551
+ train/train_5398/train_5398_a/train_5398_a_4.nii.gz
552
+ train/train_5423/train_5423_a/train_5423_a_1.nii.gz
553
+ train/train_5423/train_5423_a/train_5423_a_2.nii.gz
554
+ train/train_5423/train_5423_a/train_5423_a_4.nii.gz
555
+ train/train_55/train_55_b/train_55_b_1.nii.gz
556
+ train/train_55/train_55_b/train_55_b_2.nii.gz
557
+ train/train_55/train_55_b/train_55_b_4.nii.gz
558
+ train/train_5515/train_5515_a/train_5515_a_1.nii.gz
559
+ train/train_5515/train_5515_a/train_5515_a_2.nii.gz
560
+ train/train_5515/train_5515_a/train_5515_a_4.nii.gz
561
+ train/train_5610/train_5610_a/train_5610_a_1.nii.gz
562
+ train/train_5610/train_5610_a/train_5610_a_2.nii.gz
563
+ train/train_5610/train_5610_a/train_5610_a_4.nii.gz
564
+ train/train_5689/train_5689_a/train_5689_a_1.nii.gz
565
+ train/train_5689/train_5689_a/train_5689_a_2.nii.gz
566
+ train/train_5689/train_5689_a/train_5689_a_4.nii.gz
567
+ train/train_578/train_578_a/train_578_a_1.nii.gz
568
+ train/train_578/train_578_a/train_578_a_2.nii.gz
569
+ train/train_578/train_578_a/train_578_a_4.nii.gz
570
+ train/train_5848/train_5848_a/train_5848_a_1.nii.gz
571
+ train/train_5848/train_5848_a/train_5848_a_2.nii.gz
572
+ train/train_5848/train_5848_a/train_5848_a_4.nii.gz
573
+ train/train_5950/train_5950_a/train_5950_a_1.nii.gz
574
+ train/train_5950/train_5950_a/train_5950_a_2.nii.gz
575
+ train/train_5950/train_5950_a/train_5950_a_4.nii.gz
576
+ train/train_5979/train_5979_a/train_5979_a_1.nii.gz
577
+ train/train_5979/train_5979_a/train_5979_a_2.nii.gz
578
+ train/train_5979/train_5979_a/train_5979_a_4.nii.gz
579
+ train/train_6022/train_6022_a/train_6022_a_1.nii.gz
580
+ train/train_6022/train_6022_a/train_6022_a_2.nii.gz
581
+ train/train_6022/train_6022_a/train_6022_a_4.nii.gz
582
+ train/train_6069/train_6069_a/train_6069_a_1.nii.gz
583
+ train/train_6069/train_6069_a/train_6069_a_2.nii.gz
584
+ train/train_6069/train_6069_a/train_6069_a_4.nii.gz
585
+ train/train_6075/train_6075_a/train_6075_a_1.nii.gz
586
+ train/train_6075/train_6075_a/train_6075_a_2.nii.gz
587
+ train/train_6075/train_6075_a/train_6075_a_4.nii.gz
588
+ train/train_6087/train_6087_a/train_6087_a_1.nii.gz
589
+ train/train_6087/train_6087_a/train_6087_a_2.nii.gz
590
+ train/train_6087/train_6087_a/train_6087_a_4.nii.gz
591
+ train/train_6102/train_6102_a/train_6102_a_2.nii.gz
592
+ train/train_623/train_623_b/train_623_b_1.nii.gz
593
+ train/train_623/train_623_b/train_623_b_2.nii.gz
594
+ train/train_623/train_623_b/train_623_b_4.nii.gz
595
+ train/train_6239/train_6239_a/train_6239_a_1.nii.gz
596
+ train/train_6239/train_6239_a/train_6239_a_2.nii.gz
597
+ train/train_6239/train_6239_a/train_6239_a_4.nii.gz
598
+ train/train_6260/train_6260_a/train_6260_a_1.nii.gz
599
+ train/train_6260/train_6260_a/train_6260_a_2.nii.gz
600
+ train/train_6260/train_6260_a/train_6260_a_4.nii.gz
601
+ train/train_6266/train_6266_a/train_6266_a_1.nii.gz
602
+ train/train_6266/train_6266_a/train_6266_a_2.nii.gz
603
+ train/train_6266/train_6266_a/train_6266_a_4.nii.gz
604
+ train/train_6296/train_6296_a/train_6296_a_2.nii.gz
605
+ train/train_6325/train_6325_a/train_6325_a_1.nii.gz
606
+ train/train_6325/train_6325_a/train_6325_a_2.nii.gz
607
+ train/train_6325/train_6325_a/train_6325_a_4.nii.gz
608
+ train/train_6331/train_6331_a/train_6331_a_1.nii.gz
609
+ train/train_6331/train_6331_a/train_6331_a_2.nii.gz
610
+ train/train_6331/train_6331_a/train_6331_a_4.nii.gz
611
+ train/train_6331/train_6331_a/train_6331_a_5.nii.gz
612
+ train/train_6417/train_6417_a/train_6417_a_1.nii.gz
613
+ train/train_6417/train_6417_a/train_6417_a_2.nii.gz
614
+ train/train_6417/train_6417_a/train_6417_a_4.nii.gz
615
+ train/train_6458/train_6458_a/train_6458_a_1.nii.gz
616
+ train/train_6458/train_6458_a/train_6458_a_2.nii.gz
617
+ train/train_6458/train_6458_a/train_6458_a_4.nii.gz
618
+ train/train_6515/train_6515_a/train_6515_a_1.nii.gz
619
+ train/train_6515/train_6515_a/train_6515_a_2.nii.gz
620
+ train/train_6515/train_6515_a/train_6515_a_4.nii.gz
621
+ train/train_6560/train_6560_a/train_6560_a_1.nii.gz
622
+ train/train_6560/train_6560_a/train_6560_a_2.nii.gz
623
+ train/train_6560/train_6560_a/train_6560_a_4.nii.gz
624
+ train/train_6575/train_6575_a/train_6575_a_1.nii.gz
625
+ train/train_6575/train_6575_a/train_6575_a_2.nii.gz
626
+ train/train_6575/train_6575_a/train_6575_a_4.nii.gz
627
+ train/train_6853/train_6853_a/train_6853_a_1.nii.gz
628
+ train/train_6853/train_6853_a/train_6853_a_2.nii.gz
629
+ train/train_6853/train_6853_a/train_6853_a_4.nii.gz
630
+ train/train_7261/train_7261_a/train_7261_a_1.nii.gz
631
+ train/train_7261/train_7261_a/train_7261_a_2.nii.gz
632
+ train/train_7261/train_7261_a/train_7261_a_4.nii.gz
633
+ train/train_7302/train_7302_a/train_7302_a_1.nii.gz
634
+ train/train_7302/train_7302_a/train_7302_a_2.nii.gz
635
+ train/train_7302/train_7302_a/train_7302_a_4.nii.gz
636
+ train/train_7337/train_7337_a/train_7337_a_1.nii.gz
637
+ train/train_7337/train_7337_a/train_7337_a_2.nii.gz
638
+ train/train_7337/train_7337_a/train_7337_a_4.nii.gz
639
+ train/train_7450/train_7450_a/train_7450_a_1.nii.gz
640
+ train/train_7450/train_7450_a/train_7450_a_2.nii.gz
641
+ train/train_7450/train_7450_a/train_7450_a_4.nii.gz
642
+ train/train_746/train_746_a/train_746_a_1.nii.gz
643
+ train/train_746/train_746_a/train_746_a_2.nii.gz
644
+ train/train_746/train_746_a/train_746_a_4.nii.gz
645
+ train/train_7466/train_7466_a/train_7466_a_2.nii.gz
646
+ train/train_7511/train_7511_a/train_7511_a_1.nii.gz
647
+ train/train_7511/train_7511_a/train_7511_a_2.nii.gz
648
+ train/train_7511/train_7511_a/train_7511_a_4.nii.gz
649
+ train/train_7565/train_7565_b/train_7565_b_1.nii.gz
650
+ train/train_7565/train_7565_b/train_7565_b_2.nii.gz
651
+ train/train_7565/train_7565_b/train_7565_b_4.nii.gz
652
+ train/train_7592/train_7592_a/train_7592_a_1.nii.gz
653
+ train/train_7592/train_7592_a/train_7592_a_2.nii.gz
654
+ train/train_7592/train_7592_a/train_7592_a_4.nii.gz
655
+ train/train_7781/train_7781_b/train_7781_b_1.nii.gz
656
+ train/train_7781/train_7781_b/train_7781_b_2.nii.gz
657
+ train/train_7781/train_7781_b/train_7781_b_4.nii.gz
658
+ train/train_788/train_788_a/train_788_a_1.nii.gz
659
+ train/train_788/train_788_a/train_788_a_2.nii.gz
660
+ train/train_788/train_788_a/train_788_a_4.nii.gz
661
+ train/train_7896/train_7896_a/train_7896_a_1.nii.gz
662
+ train/train_7896/train_7896_a/train_7896_a_2.nii.gz
663
+ train/train_7896/train_7896_a/train_7896_a_4.nii.gz
664
+ train/train_7958/train_7958_a/train_7958_a_2.nii.gz
665
+ train/train_8066/train_8066_a/train_8066_a_1.nii.gz
666
+ train/train_8066/train_8066_a/train_8066_a_2.nii.gz
667
+ train/train_8066/train_8066_a/train_8066_a_4.nii.gz
668
+ train/train_8190/train_8190_a/train_8190_a_1.nii.gz
669
+ train/train_8190/train_8190_a/train_8190_a_2.nii.gz
670
+ train/train_8190/train_8190_a/train_8190_a_4.nii.gz
671
+ train/train_8252/train_8252_a/train_8252_a_1.nii.gz
672
+ train/train_8252/train_8252_a/train_8252_a_2.nii.gz
673
+ train/train_8252/train_8252_a/train_8252_a_4.nii.gz
674
+ train/train_8313/train_8313_a/train_8313_a_1.nii.gz
675
+ train/train_8313/train_8313_a/train_8313_a_2.nii.gz
676
+ train/train_8313/train_8313_a/train_8313_a_4.nii.gz
677
+ train/train_8344/train_8344_a/train_8344_a_1.nii.gz
678
+ train/train_8344/train_8344_a/train_8344_a_2.nii.gz
679
+ train/train_8344/train_8344_a/train_8344_a_4.nii.gz
680
+ train/train_8437/train_8437_a/train_8437_a_1.nii.gz
681
+ train/train_8437/train_8437_a/train_8437_a_2.nii.gz
682
+ train/train_8437/train_8437_a/train_8437_a_4.nii.gz
683
+ train/train_8451/train_8451_a/train_8451_a_1.nii.gz
684
+ train/train_8504/train_8504_a/train_8504_a_1.nii.gz
685
+ train/train_8504/train_8504_a/train_8504_a_2.nii.gz
686
+ train/train_8504/train_8504_a/train_8504_a_4.nii.gz
687
+ train/train_8504/train_8504_b/train_8504_b_1.nii.gz
688
+ train/train_8504/train_8504_b/train_8504_b_2.nii.gz
689
+ train/train_8504/train_8504_b/train_8504_b_4.nii.gz
690
+ train/train_861/train_861_a/train_861_a_1.nii.gz
691
+ train/train_861/train_861_a/train_861_a_2.nii.gz
692
+ train/train_861/train_861_a/train_861_a_4.nii.gz
693
+ train/train_8687/train_8687_a/train_8687_a_1.nii.gz
694
+ train/train_8687/train_8687_a/train_8687_a_2.nii.gz
695
+ train/train_8687/train_8687_a/train_8687_a_4.nii.gz
696
+ train/train_8744/train_8744_a/train_8744_a_1.nii.gz
697
+ train/train_8744/train_8744_a/train_8744_a_2.nii.gz
698
+ train/train_8744/train_8744_a/train_8744_a_4.nii.gz
699
+ train/train_8776/train_8776_a/train_8776_a_1.nii.gz
700
+ train/train_8776/train_8776_a/train_8776_a_2.nii.gz
701
+ train/train_8776/train_8776_a/train_8776_a_4.nii.gz
702
+ train/train_8782/train_8782_a/train_8782_a_1.nii.gz
703
+ train/train_8782/train_8782_a/train_8782_a_2.nii.gz
704
+ train/train_8782/train_8782_a/train_8782_a_4.nii.gz
705
+ train/train_8858/train_8858_a/train_8858_a_1.nii.gz
706
+ train/train_8858/train_8858_a/train_8858_a_2.nii.gz
707
+ train/train_8858/train_8858_a/train_8858_a_4.nii.gz
708
+ train/train_8900/train_8900_a/train_8900_a_1.nii.gz
709
+ train/train_8900/train_8900_a/train_8900_a_2.nii.gz
710
+ train/train_8900/train_8900_a/train_8900_a_4.nii.gz
711
+ train/train_8948/train_8948_b/train_8948_b_1.nii.gz
712
+ train/train_8948/train_8948_b/train_8948_b_2.nii.gz
713
+ train/train_8948/train_8948_b/train_8948_b_4.nii.gz
714
+ train/train_8962/train_8962_a/train_8962_a_1.nii.gz
715
+ train/train_8962/train_8962_a/train_8962_a_4.nii.gz
716
+ train/train_8992/train_8992_a/train_8992_a_1.nii.gz
717
+ train/train_8992/train_8992_a/train_8992_a_2.nii.gz
718
+ train/train_8992/train_8992_a/train_8992_a_4.nii.gz
719
+ train/train_9148/train_9148_a/train_9148_a_1.nii.gz
720
+ train/train_9148/train_9148_a/train_9148_a_2.nii.gz
721
+ train/train_9148/train_9148_a/train_9148_a_4.nii.gz
722
+ train/train_9176/train_9176_a/train_9176_a_1.nii.gz
723
+ train/train_9176/train_9176_a/train_9176_a_2.nii.gz
724
+ train/train_9176/train_9176_a/train_9176_a_4.nii.gz
725
+ train/train_9191/train_9191_a/train_9191_a_1.nii.gz
726
+ train/train_9191/train_9191_a/train_9191_a_2.nii.gz
727
+ train/train_9191/train_9191_a/train_9191_a_4.nii.gz
728
+ train/train_923/train_923_a/train_923_a_1.nii.gz
729
+ train/train_923/train_923_a/train_923_a_2.nii.gz
730
+ train/train_9298/train_9298_a/train_9298_a_1.nii.gz
731
+ train/train_9298/train_9298_a/train_9298_a_2.nii.gz
732
+ train/train_9298/train_9298_a/train_9298_a_4.nii.gz
733
+ train/train_9372/train_9372_a/train_9372_a_1.nii.gz
734
+ train/train_9372/train_9372_a/train_9372_a_2.nii.gz
735
+ train/train_9372/train_9372_a/train_9372_a_4.nii.gz
736
+ train/train_9734/train_9734_a/train_9734_a_1.nii.gz
737
+ train/train_9734/train_9734_a/train_9734_a_2.nii.gz
738
+ train/train_9734/train_9734_a/train_9734_a_4.nii.gz
739
+ train/train_9792/train_9792_a/train_9792_a_1.nii.gz
740
+ train/train_9792/train_9792_a/train_9792_a_2.nii.gz
741
+ train/train_9818/train_9818_a/train_9818_a_1.nii.gz
742
+ train/train_9818/train_9818_a/train_9818_a_2.nii.gz
743
+ train/train_9818/train_9818_a/train_9818_a_4.nii.gz
744
+ train/train_9829/train_9829_a/train_9829_a_1.nii.gz
745
+ train/train_9829/train_9829_a/train_9829_a_2.nii.gz
746
+ train/train_9829/train_9829_a/train_9829_a_4.nii.gz
747
+ train/train_9862/train_9862_a/train_9862_a_1.nii.gz
748
+ train/train_9862/train_9862_a/train_9862_a_2.nii.gz
749
+ train/train_9862/train_9862_a/train_9862_a_4.nii.gz
750
+ train/train_9904/train_9904_a/train_9904_a_1.nii.gz
751
+ train/train_9904/train_9904_a/train_9904_a_2.nii.gz
752
+ train/train_9904/train_9904_a/train_9904_a_4.nii.gz
instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/metadata/no_chest_valid.txt ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ valid/valid_109/valid_109_a/valid_109_a_1.nii.gz
2
+ valid/valid_109/valid_109_a/valid_109_a_2.nii.gz
3
+ valid/valid_109/valid_109_a/valid_109_a_4.nii.gz
4
+ valid/valid_1112/valid_1112_a/valid_1112_a_1.nii.gz
5
+ valid/valid_1112/valid_1112_a/valid_1112_a_2.nii.gz
6
+ valid/valid_1112/valid_1112_a/valid_1112_a_4.nii.gz
7
+ valid/valid_1170/valid_1170_a/valid_1170_a_1.nii.gz
8
+ valid/valid_1170/valid_1170_a/valid_1170_a_2.nii.gz
9
+ valid/valid_1170/valid_1170_a/valid_1170_a_5.nii.gz
10
+ valid/valid_208/valid_208_a/valid_208_a_1.nii.gz
11
+ valid/valid_208/valid_208_a/valid_208_a_2.nii.gz
12
+ valid/valid_208/valid_208_a/valid_208_a_4.nii.gz
13
+ valid/valid_257/valid_257_a/valid_257_a_1.nii.gz
14
+ valid/valid_257/valid_257_a/valid_257_a_2.nii.gz
15
+ valid/valid_257/valid_257_a/valid_257_a_4.nii.gz
16
+ valid/valid_340/valid_340_a/valid_340_a_1.nii.gz
17
+ valid/valid_340/valid_340_a/valid_340_a_2.nii.gz
18
+ valid/valid_340/valid_340_a/valid_340_a_4.nii.gz
19
+ valid/valid_365/valid_365_a/valid_365_a_1.nii.gz
20
+ valid/valid_365/valid_365_a/valid_365_a_2.nii.gz
21
+ valid/valid_365/valid_365_a/valid_365_a_4.nii.gz
22
+ valid/valid_417/valid_417_a/valid_417_a_1.nii.gz
23
+ valid/valid_417/valid_417_a/valid_417_a_2.nii.gz
24
+ valid/valid_417/valid_417_a/valid_417_a_4.nii.gz
25
+ valid/valid_520/valid_520_a/valid_520_a_2.nii.gz
26
+ valid/valid_569/valid_569_b/valid_569_b_1.nii.gz
27
+ valid/valid_569/valid_569_b/valid_569_b_2.nii.gz
28
+ valid/valid_569/valid_569_b/valid_569_b_4.nii.gz
29
+ valid/valid_726/valid_726_a/valid_726_a_1.nii.gz
30
+ valid/valid_726/valid_726_a/valid_726_a_2.nii.gz
31
+ valid/valid_726/valid_726_a/valid_726_a_4.nii.gz
32
+ valid/valid_884/valid_884_a/valid_884_a_1.nii.gz
33
+ valid/valid_884/valid_884_a/valid_884_a_2.nii.gz
34
+ valid/valid_884/valid_884_a/valid_884_a_4.nii.gz
35
+ valid/valid_994/valid_994_a/valid_994_a_1.nii.gz
36
+ valid/valid_994/valid_994_a/valid_994_a_2.nii.gz
37
+ valid/valid_994/valid_994_a/valid_994_a_4.nii.gz
instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/metadata/train_metadata.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:575cff9e5dcefba21cda10b6e54f685370b1f00347c68a28eac55ff9544c082c
3
+ size 14922140
instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/metadata/validation_metadata.csv ADDED
The diff for this file is too large to render. See raw diff
 
instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/multi_abnormality_labels/train_predicted_labels.csv ADDED
The diff for this file is too large to render. See raw diff
 
instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/multi_abnormality_labels/train_predicted_labels_100.csv ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ VolumeName,Medical material,Arterial wall calcification,Cardiomegaly,Pericardial effusion,Coronary artery wall calcification,Hiatal hernia,Lymphadenopathy,Emphysema,Atelectasis,Lung nodule,Lung opacity,Pulmonary fibrotic sequela,Pleural effusion,Mosaic attenuation pattern,Peribronchial thickening,Consolidation,Bronchiectasis,Interlobular septal thickening
2
+ train_1_a_1.nii.gz,0,1,0,0,0,0,0,0,1,0,1,0,0,0,1,1,0,0
3
+ train_1_a_2.nii.gz,0,1,0,0,0,0,0,0,1,0,1,0,0,0,1,1,0,0
4
+ train_2_a_1.nii.gz,0,1,0,0,0,0,0,1,1,1,0,0,0,0,1,0,0,0
5
+ train_2_a_2.nii.gz,0,1,0,0,0,0,0,1,1,1,0,0,0,0,1,0,0,0
6
+ train_3_a_1.nii.gz,0,1,1,0,1,0,1,0,0,1,1,1,0,0,1,0,1,0
7
+ train_3_a_2.nii.gz,0,1,1,0,1,0,1,0,0,1,1,1,0,0,1,0,1,0
8
+ train_3_b_1.nii.gz,1,1,0,0,1,1,1,0,0,1,0,0,1,0,0,1,0,1
9
+ train_3_b_2.nii.gz,1,1,0,0,1,1,1,0,0,1,0,0,1,0,0,1,0,1
10
+ train_4_a_1.nii.gz,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0
11
+ train_5_a_1.nii.gz,0,1,0,0,0,1,0,0,0,1,0,1,0,0,1,0,0,0
12
+ train_5_a_2.nii.gz,0,1,0,0,0,1,0,0,0,1,0,1,0,0,1,0,0,0
13
+ train_6_a_1.nii.gz,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1
14
+ train_6_a_2.nii.gz,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1
15
+ train_6_b_1.nii.gz,0,1,0,0,1,0,0,0,1,0,1,0,0,0,0,0,0,1
16
+ train_6_b_2.nii.gz,0,1,0,0,1,0,0,0,1,0,1,0,0,0,0,0,0,1
17
+ train_7_a_1.nii.gz,1,0,0,0,0,0,1,0,0,1,0,1,0,0,0,0,1,0
18
+ train_7_a_2.nii.gz,1,0,0,0,0,0,1,0,0,1,0,1,0,0,0,0,1,0
19
+ train_8_a_1.nii.gz,1,1,1,1,0,0,1,0,1,1,0,1,1,0,0,0,0,1
20
+ train_8_a_2.nii.gz,1,1,1,1,0,0,1,0,1,1,0,1,1,0,0,0,0,1
21
+ train_8_b_1.nii.gz,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0,1
22
+ train_8_b_2.nii.gz,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0,1
23
+ train_9_a_1.nii.gz,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0
24
+ train_9_a_2.nii.gz,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0
25
+ train_10_a_1.nii.gz,0,1,0,0,1,0,1,0,0,1,1,0,0,0,0,0,0,0
26
+ train_10_a_2.nii.gz,0,1,0,0,1,0,1,0,0,1,1,0,0,0,0,0,0,0
27
+ train_11_a_1.nii.gz,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0
28
+ train_11_a_2.nii.gz,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0
29
+ train_12_a_1.nii.gz,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0
30
+ train_12_a_2.nii.gz,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0
31
+ train_13_a_1.nii.gz,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
32
+ train_13_a_2.nii.gz,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
33
+ train_14_a_1.nii.gz,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0
34
+ train_14_a_2.nii.gz,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0
35
+ train_15_a_1.nii.gz,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0
36
+ train_15_a_2.nii.gz,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0
37
+ train_16_a_1.nii.gz,1,0,0,0,0,0,1,0,0,1,1,1,1,0,0,1,0,0
38
+ train_16_a_2.nii.gz,1,0,0,0,0,0,1,0,0,1,1,1,1,0,0,1,0,0
39
+ train_16_b_1.nii.gz,0,0,0,0,0,0,1,0,0,0,1,0,1,0,0,1,0,0
40
+ train_16_b_2.nii.gz,0,0,0,0,0,0,1,0,0,0,1,0,1,0,0,1,0,0
41
+ train_17_a_1.nii.gz,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0
42
+ train_17_a_2.nii.gz,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0
43
+ train_18_a_1.nii.gz,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0
44
+ train_18_a_2.nii.gz,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0
45
+ train_19_a_1.nii.gz,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0
46
+ train_19_a_2.nii.gz,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0
47
+ train_20_a_1.nii.gz,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1
48
+ train_20_a_2.nii.gz,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1
49
+ train_21_a_1.nii.gz,0,1,1,1,1,0,0,0,0,1,0,0,0,0,1,0,1,0
50
+ train_21_a_2.nii.gz,0,1,1,1,1,0,0,0,0,1,0,0,0,0,1,0,1,0
51
+ train_22_a_1.nii.gz,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0
52
+ train_22_a_2.nii.gz,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0
53
+ train_23_a_1.nii.gz,0,0,0,0,0,0,1,1,0,1,0,1,0,0,0,0,0,0
54
+ train_23_a_2.nii.gz,0,0,0,0,0,0,1,1,0,1,0,1,0,0,0,0,0,0
55
+ train_24_a_1.nii.gz,0,1,0,0,1,0,0,1,1,0,1,1,0,0,0,0,1,0
56
+ train_24_a_2.nii.gz,0,1,0,0,1,0,0,1,1,0,1,1,0,0,0,0,1,0
57
+ train_25_a_1.nii.gz,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0
58
+ train_25_a_2.nii.gz,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0
59
+ train_26_a_1.nii.gz,1,0,0,0,0,0,1,0,1,1,0,0,1,0,0,0,0,0
60
+ train_26_a_2.nii.gz,1,0,0,0,0,0,1,0,1,1,0,0,1,0,0,0,0,0
61
+ train_27_a_1.nii.gz,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0
62
+ train_27_a_2.nii.gz,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0
63
+ train_28_a_1.nii.gz,0,0,1,0,1,0,1,0,0,0,1,0,0,0,0,1,0,0
64
+ train_28_a_2.nii.gz,0,0,1,0,1,0,1,0,0,0,1,0,0,0,0,1,0,0
65
+ train_29_a_1.nii.gz,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0
66
+ train_29_a_2.nii.gz,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0
67
+ train_29_b_1.nii.gz,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0
68
+ train_30_a_1.nii.gz,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,1,0,0
69
+ train_30_a_2.nii.gz,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,1,0,0
70
+ train_31_a_1.nii.gz,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0
71
+ train_31_a_2.nii.gz,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0
72
+ train_32_a_1.nii.gz,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0
73
+ train_32_a_2.nii.gz,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0
74
+ train_33_a_1.nii.gz,0,1,0,1,1,0,0,0,0,0,1,0,0,0,0,0,0,1
75
+ train_33_a_2.nii.gz,0,1,0,1,1,0,0,0,0,0,1,0,0,0,0,0,0,1
76
+ train_34_a_1.nii.gz,0,1,0,0,1,0,1,1,0,1,0,1,0,0,0,0,1,0
77
+ train_34_a_2.nii.gz,0,1,0,0,1,0,1,1,0,1,0,1,0,0,0,0,1,0
78
+ train_35_a_1.nii.gz,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0
79
+ train_35_a_2.nii.gz,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0
80
+ train_36_a_1.nii.gz,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0
81
+ train_36_a_2.nii.gz,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0
82
+ train_36_b_1.nii.gz,0,0,0,0,0,0,1,0,0,1,1,0,0,0,0,0,0,0
83
+ train_36_b_2.nii.gz,0,0,0,0,0,0,1,0,0,1,1,0,0,0,0,0,0,0
84
+ train_37_a_1.nii.gz,0,0,0,0,1,0,0,0,1,1,0,0,0,0,0,1,0,0
85
+ train_37_a_2.nii.gz,0,0,0,0,1,0,0,0,1,1,0,0,0,0,0,1,0,0
86
+ train_37_b_1.nii.gz,0,1,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0
87
+ train_37_b_2.nii.gz,0,1,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0
88
+ train_37_c_1.nii.gz,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,0,0
89
+ train_37_c_2.nii.gz,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,0,0
90
+ train_38_a_1.nii.gz,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
91
+ train_38_a_2.nii.gz,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
92
+ train_39_a_1.nii.gz,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0
93
+ train_39_a_2.nii.gz,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0
94
+ train_39_b_1.nii.gz,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0
95
+ train_39_b_2.nii.gz,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0
96
+ train_39_b_3.nii.gz,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0
97
+ train_39_b_4.nii.gz,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0
98
+ train_39_b_5.nii.gz,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0
99
+ train_39_c_1.nii.gz,1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0
100
+ train_39_c_2.nii.gz,1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0
101
+ train_39_d_1.nii.gz,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0
instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/multi_abnormality_labels/valid_predicted_labels.csv ADDED
The diff for this file is too large to render. See raw diff
 
instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/multi_abnormality_labels/valid_predicted_labels_100.csv ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ VolumeName,Medical material,Arterial wall calcification,Cardiomegaly,Pericardial effusion,Coronary artery wall calcification,Hiatal hernia,Lymphadenopathy,Emphysema,Atelectasis,Lung nodule,Lung opacity,Pulmonary fibrotic sequela,Pleural effusion,Mosaic attenuation pattern,Peribronchial thickening,Consolidation,Bronchiectasis,Interlobular septal thickening
2
+ valid_1_a_1.nii.gz,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0
3
+ valid_1_a_2.nii.gz,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0
4
+ valid_2_a_1.nii.gz,0,0,0,0,0,1,0,0,0,1,0,1,0,0,1,0,0,0
5
+ valid_2_a_2.nii.gz,0,0,0,0,0,1,0,0,0,1,0,1,0,0,1,0,0,0
6
+ valid_3_a_1.nii.gz,0,0,0,0,0,1,0,0,0,1,1,0,0,0,0,0,0,0
7
+ valid_3_a_2.nii.gz,0,0,0,0,0,1,0,0,0,1,1,0,0,0,0,0,0,0
8
+ valid_4_a_1.nii.gz,0,0,0,0,0,0,0,0,1,1,1,0,1,0,0,0,0,0
9
+ valid_4_a_2.nii.gz,0,0,0,0,0,0,0,0,1,1,1,0,1,0,0,0,0,0
10
+ valid_4_b_1.nii.gz,0,0,0,0,0,0,1,0,0,0,1,1,1,0,0,0,0,0
11
+ valid_4_b_2.nii.gz,0,0,0,0,0,0,1,0,0,0,1,1,1,0,0,0,0,0
12
+ valid_5_a_1.nii.gz,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
13
+ valid_5_a_2.nii.gz,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
14
+ valid_6_a_1.nii.gz,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0
15
+ valid_6_a_2.nii.gz,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0
16
+ valid_7_a_1.nii.gz,0,0,0,0,0,0,1,0,0,1,1,0,0,1,0,0,0,0
17
+ valid_7_a_2.nii.gz,0,0,0,0,0,0,1,0,0,1,1,0,0,1,0,0,0,0
18
+ valid_7_b_1.nii.gz,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0
19
+ valid_7_b_2.nii.gz,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0
20
+ valid_8_a_1.nii.gz,0,0,0,0,0,1,1,0,0,1,1,0,0,1,0,0,0,1
21
+ valid_8_a_2.nii.gz,0,0,0,0,0,1,1,0,0,1,1,0,0,1,0,0,0,1
22
+ valid_9_a_1.nii.gz,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0
23
+ valid_9_a_2.nii.gz,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0
24
+ valid_10_a_1.nii.gz,0,0,0,0,0,1,0,1,0,1,1,1,0,0,0,0,0,0
25
+ valid_10_a_2.nii.gz,0,0,0,0,0,1,0,1,0,1,1,1,0,0,0,0,0,0
26
+ valid_11_a_1.nii.gz,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
27
+ valid_11_a_2.nii.gz,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
28
+ valid_12_a_1.nii.gz,1,1,0,0,0,0,1,0,1,1,1,0,1,0,0,1,0,1
29
+ valid_12_a_2.nii.gz,1,1,0,0,0,0,1,0,1,1,1,0,1,0,0,1,0,1
30
+ valid_13_a_1.nii.gz,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0
31
+ valid_13_a_2.nii.gz,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0
32
+ valid_14_a_1.nii.gz,0,1,1,0,1,0,1,1,0,0,1,0,0,0,0,0,0,0
33
+ valid_14_a_2.nii.gz,0,1,1,0,1,0,1,1,0,0,1,0,0,0,0,0,0,0
34
+ valid_15_a_1.nii.gz,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
35
+ valid_15_a_2.nii.gz,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
36
+ valid_16_a_1.nii.gz,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0
37
+ valid_16_a_2.nii.gz,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0
38
+ valid_17_a_1.nii.gz,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0
39
+ valid_17_a_2.nii.gz,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0
40
+ valid_18_a_1.nii.gz,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0
41
+ valid_18_a_2.nii.gz,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0
42
+ valid_19_a_1.nii.gz,0,0,0,0,0,0,0,0,1,1,0,1,1,0,0,0,0,0
43
+ valid_20_a_1.nii.gz,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0
44
+ valid_20_a_2.nii.gz,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0
45
+ valid_20_b_1.nii.gz,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
46
+ valid_20_b_2.nii.gz,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
47
+ valid_21_a_1.nii.gz,0,1,0,0,1,0,0,1,0,1,0,0,0,0,0,0,0,0
48
+ valid_21_a_2.nii.gz,0,1,0,0,1,0,0,1,0,1,0,0,0,0,0,0,0,0
49
+ valid_22_a_1.nii.gz,0,1,1,1,1,0,1,0,0,0,1,0,0,0,0,1,0,0
50
+ valid_22_a_2.nii.gz,0,1,1,1,1,0,1,0,0,0,1,0,0,0,0,1,0,0
51
+ valid_23_a_1.nii.gz,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0
52
+ valid_23_a_2.nii.gz,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0
53
+ valid_24_a_1.nii.gz,0,1,0,0,1,1,0,1,0,0,1,0,0,0,0,1,0,1
54
+ valid_24_a_2.nii.gz,0,1,0,0,1,1,0,1,0,0,1,0,0,0,0,1,0,1
55
+ valid_25_a_1.nii.gz,0,0,0,0,1,0,1,0,0,1,1,0,0,0,1,0,0,0
56
+ valid_25_a_2.nii.gz,0,0,0,0,1,0,1,0,0,1,1,0,0,0,1,0,0,0
57
+ valid_26_a_1.nii.gz,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0
58
+ valid_26_a_2.nii.gz,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0
59
+ valid_27_a_1.nii.gz,0,1,1,1,0,0,1,0,1,1,0,1,1,1,0,1,0,1
60
+ valid_27_a_2.nii.gz,0,1,1,1,0,0,1,0,1,1,0,1,1,1,0,1,0,1
61
+ valid_27_b_1.nii.gz,0,0,0,1,0,0,0,0,0,0,1,0,1,0,0,1,0,0
62
+ valid_27_b_2.nii.gz,0,0,0,1,0,0,0,0,0,0,1,0,1,0,0,1,0,0
63
+ valid_28_a_1.nii.gz,1,1,0,0,1,0,0,1,0,0,0,1,0,0,0,0,0,0
64
+ valid_28_a_2.nii.gz,1,1,0,0,1,0,0,1,0,0,0,1,0,0,0,0,0,0
65
+ valid_29_a_1.nii.gz,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1,0,1,0
66
+ valid_29_a_2.nii.gz,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1,0,1,0
67
+ valid_30_a_1.nii.gz,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0
68
+ valid_31_a_1.nii.gz,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0
69
+ valid_31_a_2.nii.gz,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0
70
+ valid_32_a_1.nii.gz,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
71
+ valid_33_a_1.nii.gz,0,0,0,0,0,0,1,0,0,0,1,0,1,1,0,0,0,0
72
+ valid_33_a_2.nii.gz,0,0,0,0,0,0,1,0,0,0,1,0,1,1,0,0,0,0
73
+ valid_34_a_1.nii.gz,1,1,0,0,1,0,0,0,1,0,0,1,0,0,0,0,0,0
74
+ valid_34_a_2.nii.gz,1,1,0,0,1,0,0,0,1,0,0,1,0,0,0,0,0,0
75
+ valid_35_a_1.nii.gz,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0
76
+ valid_35_a_2.nii.gz,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0
77
+ valid_36_a_1.nii.gz,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0
78
+ valid_37_a_1.nii.gz,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
79
+ valid_38_a_1.nii.gz,1,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,1,0
80
+ valid_38_a_2.nii.gz,1,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,1,0
81
+ valid_39_a_1.nii.gz,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,1
82
+ valid_39_a_2.nii.gz,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,1
83
+ valid_40_a_1.nii.gz,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0
84
+ valid_40_a_2.nii.gz,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0
85
+ valid_41_a_1.nii.gz,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0
86
+ valid_41_a_2.nii.gz,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0
87
+ valid_41_b_1.nii.gz,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0
88
+ valid_41_b_2.nii.gz,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0
89
+ valid_42_a_1.nii.gz,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0
90
+ valid_43_a_1.nii.gz,0,1,0,0,1,0,1,1,0,0,1,1,0,0,0,0,0,0
91
+ valid_43_a_2.nii.gz,0,1,0,0,1,0,1,1,0,0,1,1,0,0,0,0,0,0
92
+ valid_44_a_1.nii.gz,0,1,1,0,1,0,0,1,1,0,1,0,1,0,0,1,0,0
93
+ valid_44_a_2.nii.gz,0,1,1,0,1,0,0,1,1,0,1,0,1,0,0,1,0,0
94
+ valid_45_a_1.nii.gz,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0
95
+ valid_45_a_2.nii.gz,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0
96
+ valid_46_a_1.nii.gz,1,1,1,0,1,1,0,1,1,1,0,0,0,0,1,0,1,0
97
+ valid_46_a_2.nii.gz,1,1,1,0,1,1,0,1,1,1,0,0,0,0,1,0,1,0
98
+ valid_47_a_1.nii.gz,0,0,0,0,1,0,0,0,0,0,0,1,0,1,1,0,0,0
99
+ valid_47_a_2.nii.gz,0,0,0,0,1,0,0,0,0,0,0,1,0,1,1,0,0,0
100
+ valid_48_a_1.nii.gz,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0
101
+ valid_48_a_2.nii.gz,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0
instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/radiology_text_reports/train_reports.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e885df178fab09dfe7a0f2bdba121d5a4efe0c89d13db6f341a3bb3f8105ada7
3
+ size 79667286
instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/radiology_text_reports/valid_reports.csv ADDED
The diff for this file is too large to render. See raw diff
 
instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/train_no_disease_2_checked.json ADDED
The diff for this file is too large to render. See raw diff
 
instruct-pix2pix-BioMedCLIP-concat-newdata/data_json/valid_no_disease_2_checked.json ADDED
The diff for this file is too large to render. See raw diff
 
instruct-pix2pix-BioMedCLIP-concat-newdata/dataset_creation/generate_img_dataset.py ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ import k_diffusion
7
+ import numpy as np
8
+ import torch
9
+ import torch.nn as nn
10
+ from einops import rearrange, repeat
11
+ from omegaconf import OmegaConf
12
+ from PIL import Image
13
+ from pytorch_lightning import seed_everything
14
+ from tqdm import tqdm
15
+
16
+ sys.path.append("./")
17
+ sys.path.append("./stable_diffusion")
18
+
19
+ from ldm.modules.attention import CrossAttention
20
+ from ldm.util import instantiate_from_config
21
+ from metrics.clip_similarity import ClipSimilarity
22
+
23
+
24
+ ################################################################################
25
+ # Modified K-diffusion Euler ancestral sampler with prompt-to-prompt.
26
+ # https://github.com/crowsonkb/k-diffusion/blob/master/k_diffusion/sampling.py
27
+
28
+
29
+ def append_dims(x, target_dims):
30
+ """Appends dimensions to the end of a tensor until it has target_dims dimensions."""
31
+ dims_to_append = target_dims - x.ndim
32
+ if dims_to_append < 0:
33
+ raise ValueError(f"input has {x.ndim} dims but target_dims is {target_dims}, which is less")
34
+ return x[(...,) + (None,) * dims_to_append]
35
+
36
+
37
+ def to_d(x, sigma, denoised):
38
+ """Converts a denoiser output to a Karras ODE derivative."""
39
+ return (x - denoised) / append_dims(sigma, x.ndim)
40
+
41
+
42
+ def get_ancestral_step(sigma_from, sigma_to):
43
+ """Calculates the noise level (sigma_down) to step down to and the amount
44
+ of noise to add (sigma_up) when doing an ancestral sampling step."""
45
+ sigma_up = min(sigma_to, (sigma_to**2 * (sigma_from**2 - sigma_to**2) / sigma_from**2) ** 0.5)
46
+ sigma_down = (sigma_to**2 - sigma_up**2) ** 0.5
47
+ return sigma_down, sigma_up
48
+
49
+
50
+ def sample_euler_ancestral(model, x, sigmas, prompt2prompt_threshold=0.0, **extra_args):
51
+ """Ancestral sampling with Euler method steps."""
52
+ s_in = x.new_ones([x.shape[0]])
53
+ for i in range(len(sigmas) - 1):
54
+ prompt_to_prompt = prompt2prompt_threshold > i / (len(sigmas) - 2)
55
+ for m in model.modules():
56
+ if isinstance(m, CrossAttention):
57
+ m.prompt_to_prompt = prompt_to_prompt
58
+ denoised = model(x, sigmas[i] * s_in, **extra_args)
59
+ sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1])
60
+ d = to_d(x, sigmas[i], denoised)
61
+ # Euler method
62
+ dt = sigma_down - sigmas[i]
63
+ x = x + d * dt
64
+ if sigmas[i + 1] > 0:
65
+ # Make noise the same across all samples in batch.
66
+ x = x + torch.randn_like(x[:1]) * sigma_up
67
+ return x
68
+
69
+
70
+ ################################################################################
71
+
72
+
73
+ def load_model_from_config(config, ckpt, vae_ckpt=None, verbose=False):
74
+ print(f"Loading model from {ckpt}")
75
+ pl_sd = torch.load(ckpt, map_location="cpu")
76
+ if "global_step" in pl_sd:
77
+ print(f"Global Step: {pl_sd['global_step']}")
78
+ sd = pl_sd["state_dict"]
79
+ if vae_ckpt is not None:
80
+ print(f"Loading VAE from {vae_ckpt}")
81
+ vae_sd = torch.load(vae_ckpt, map_location="cpu")["state_dict"]
82
+ sd = {
83
+ k: vae_sd[k[len("first_stage_model.") :]] if k.startswith("first_stage_model.") else v
84
+ for k, v in sd.items()
85
+ }
86
+ model = instantiate_from_config(config.model)
87
+ m, u = model.load_state_dict(sd, strict=False)
88
+ if len(m) > 0 and verbose:
89
+ print("missing keys:")
90
+ print(m)
91
+ if len(u) > 0 and verbose:
92
+ print("unexpected keys:")
93
+ print(u)
94
+ return model
95
+
96
+
97
+ class CFGDenoiser(nn.Module):
98
+ def __init__(self, model):
99
+ super().__init__()
100
+ self.inner_model = model
101
+
102
+ def forward(self, x, sigma, uncond, cond, cfg_scale):
103
+ x_in = torch.cat([x] * 2)
104
+ sigma_in = torch.cat([sigma] * 2)
105
+ cond_in = torch.cat([uncond, cond])
106
+ uncond, cond = self.inner_model(x_in, sigma_in, cond=cond_in).chunk(2)
107
+ return uncond + (cond - uncond) * cfg_scale
108
+
109
+
110
+ def to_pil(image: torch.Tensor) -> Image.Image:
111
+ image = 255.0 * rearrange(image.cpu().numpy(), "c h w -> h w c")
112
+ image = Image.fromarray(image.astype(np.uint8))
113
+ return image
114
+
115
+
116
+ def main():
117
+ parser = argparse.ArgumentParser()
118
+ parser.add_argument(
119
+ "--out_dir",
120
+ type=str,
121
+ required=True,
122
+ help="Path to output dataset directory.",
123
+ )
124
+ parser.add_argument(
125
+ "--prompts_file",
126
+ type=str,
127
+ required=True,
128
+ help="Path to prompts .jsonl file.",
129
+ )
130
+ parser.add_argument(
131
+ "--ckpt",
132
+ type=str,
133
+ default="stable_diffusion/models/ldm/stable-diffusion-v1/v1-5-pruned-emaonly.ckpt",
134
+ help="Path to stable diffusion checkpoint.",
135
+ )
136
+ parser.add_argument(
137
+ "--vae-ckpt",
138
+ type=str,
139
+ default="stable_diffusion/models/ldm/stable-diffusion-v1/vae-ft-mse-840000-ema-pruned.ckpt",
140
+ help="Path to vae checkpoint.",
141
+ )
142
+ parser.add_argument(
143
+ "--steps",
144
+ type=int,
145
+ default=100,
146
+ help="Number of sampling steps.",
147
+ )
148
+ parser.add_argument(
149
+ "--n-samples",
150
+ type=int,
151
+ default=100,
152
+ help="Number of samples to generate per prompt (before CLIP filtering).",
153
+ )
154
+ parser.add_argument(
155
+ "--max-out-samples",
156
+ type=int,
157
+ default=4,
158
+ help="Max number of output samples to save per prompt (after CLIP filtering).",
159
+ )
160
+ parser.add_argument(
161
+ "--n-partitions",
162
+ type=int,
163
+ default=1,
164
+ help="Number of total partitions.",
165
+ )
166
+ parser.add_argument(
167
+ "--partition",
168
+ type=int,
169
+ default=0,
170
+ help="Partition index.",
171
+ )
172
+ parser.add_argument(
173
+ "--min-p2p",
174
+ type=float,
175
+ default=0.1,
176
+ help="Min prompt2prompt threshold (portion of denoising for which to fix self attention maps).",
177
+ )
178
+ parser.add_argument(
179
+ "--max-p2p",
180
+ type=float,
181
+ default=0.9,
182
+ help="Max prompt2prompt threshold (portion of denoising for which to fix self attention maps).",
183
+ )
184
+ parser.add_argument(
185
+ "--min-cfg",
186
+ type=float,
187
+ default=7.5,
188
+ help="Min classifier free guidance scale.",
189
+ )
190
+ parser.add_argument(
191
+ "--max-cfg",
192
+ type=float,
193
+ default=15,
194
+ help="Max classifier free guidance scale.",
195
+ )
196
+ parser.add_argument(
197
+ "--clip-threshold",
198
+ type=float,
199
+ default=0.2,
200
+ help="CLIP threshold for text-image similarity of each image.",
201
+ )
202
+ parser.add_argument(
203
+ "--clip-dir-threshold",
204
+ type=float,
205
+ default=0.2,
206
+ help="Directional CLIP threshold for similarity of change between pairs of text and pairs of images.",
207
+ )
208
+ parser.add_argument(
209
+ "--clip-img-threshold",
210
+ type=float,
211
+ default=0.7,
212
+ help="CLIP threshold for image-image similarity.",
213
+ )
214
+ opt = parser.parse_args()
215
+
216
+ global_seed = torch.randint(1 << 32, ()).item()
217
+ print(f"Global seed: {global_seed}")
218
+ seed_everything(global_seed)
219
+
220
+ model = load_model_from_config(
221
+ OmegaConf.load("stable_diffusion/configs/stable-diffusion/v1-inference.yaml"),
222
+ ckpt=opt.ckpt,
223
+ vae_ckpt=opt.vae_ckpt,
224
+ )
225
+ model.cuda().eval()
226
+ model_wrap = k_diffusion.external.CompVisDenoiser(model)
227
+
228
+ clip_similarity = ClipSimilarity().cuda()
229
+
230
+ out_dir = Path(opt.out_dir)
231
+ out_dir.mkdir(exist_ok=True, parents=True)
232
+
233
+ with open(opt.prompts_file) as fp:
234
+ prompts = [json.loads(line) for line in fp]
235
+
236
+ print(f"Partition index {opt.partition} ({opt.partition + 1} / {opt.n_partitions})")
237
+ prompts = np.array_split(list(enumerate(prompts)), opt.n_partitions)[opt.partition]
238
+
239
+ with torch.no_grad(), torch.autocast("cuda"), model.ema_scope():
240
+ uncond = model.get_learned_conditioning(2 * [""])
241
+ sigmas = model_wrap.get_sigmas(opt.steps)
242
+
243
+ for i, prompt in tqdm(prompts, desc="Prompts"):
244
+ prompt_dir = out_dir.joinpath(f"{i:07d}")
245
+ prompt_dir.mkdir(exist_ok=True)
246
+
247
+ with open(prompt_dir.joinpath("prompt.json"), "w") as fp:
248
+ json.dump(prompt, fp)
249
+
250
+ cond = model.get_learned_conditioning([prompt["caption"], prompt["output"]])
251
+ results = {}
252
+
253
+ with tqdm(total=opt.n_samples, desc="Samples") as progress_bar:
254
+
255
+ while len(results) < opt.n_samples:
256
+ seed = torch.randint(1 << 32, ()).item()
257
+ if seed in results:
258
+ continue
259
+ torch.manual_seed(seed)
260
+
261
+ x = torch.randn(1, 4, 512 // 8, 512 // 8, device="cuda") * sigmas[0]
262
+ x = repeat(x, "1 ... -> n ...", n=2)
263
+
264
+ model_wrap_cfg = CFGDenoiser(model_wrap)
265
+ p2p_threshold = opt.min_p2p + torch.rand(()).item() * (opt.max_p2p - opt.min_p2p)
266
+ cfg_scale = opt.min_cfg + torch.rand(()).item() * (opt.max_cfg - opt.min_cfg)
267
+ extra_args = {"cond": cond, "uncond": uncond, "cfg_scale": cfg_scale}
268
+ samples_ddim = sample_euler_ancestral(model_wrap_cfg, x, sigmas, p2p_threshold, **extra_args)
269
+ x_samples_ddim = model.decode_first_stage(samples_ddim)
270
+ x_samples_ddim = torch.clamp((x_samples_ddim + 1.0) / 2.0, min=0.0, max=1.0)
271
+
272
+ x0 = x_samples_ddim[0]
273
+ x1 = x_samples_ddim[1]
274
+
275
+ clip_sim_0, clip_sim_1, clip_sim_dir, clip_sim_image = clip_similarity(
276
+ x0[None], x1[None], [prompt["caption"]], [prompt["output"]]
277
+ )
278
+
279
+ results[seed] = dict(
280
+ image_0=to_pil(x0),
281
+ image_1=to_pil(x1),
282
+ p2p_threshold=p2p_threshold,
283
+ cfg_scale=cfg_scale,
284
+ clip_sim_0=clip_sim_0[0].item(),
285
+ clip_sim_1=clip_sim_1[0].item(),
286
+ clip_sim_dir=clip_sim_dir[0].item(),
287
+ clip_sim_image=clip_sim_image[0].item(),
288
+ )
289
+
290
+ progress_bar.update()
291
+
292
+ # CLIP filter to get best samples for each prompt.
293
+ metadata = [
294
+ (result["clip_sim_dir"], seed)
295
+ for seed, result in results.items()
296
+ if result["clip_sim_image"] >= opt.clip_img_threshold
297
+ and result["clip_sim_dir"] >= opt.clip_dir_threshold
298
+ and result["clip_sim_0"] >= opt.clip_threshold
299
+ and result["clip_sim_1"] >= opt.clip_threshold
300
+ ]
301
+ metadata.sort(reverse=True)
302
+ for _, seed in metadata[: opt.max_out_samples]:
303
+ result = results[seed]
304
+ image_0 = result.pop("image_0")
305
+ image_1 = result.pop("image_1")
306
+ image_0.save(prompt_dir.joinpath(f"{seed}_0.jpg"), quality=100)
307
+ image_1.save(prompt_dir.joinpath(f"{seed}_1.jpg"), quality=100)
308
+ with open(prompt_dir.joinpath(f"metadata.jsonl"), "a") as fp:
309
+ fp.write(f"{json.dumps(dict(seed=seed, **result))}\n")
310
+
311
+ print("Done.")
312
+
313
+
314
+ if __name__ == "__main__":
315
+ main()
instruct-pix2pix-BioMedCLIP-concat-newdata/dataset_creation/generate_txt_dataset.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import time
5
+ from argparse import ArgumentParser
6
+ from pathlib import Path
7
+ from typing import Optional
8
+
9
+ import datasets
10
+ import numpy as np
11
+ import openai
12
+ from tqdm.auto import tqdm
13
+
14
+
15
+ DELIMITER_0 = "\n##\n"
16
+ DELIMITER_1 = "\n%%\n"
17
+ STOP = "\nEND"
18
+
19
+
20
+ def generate(
21
+ openai_model: str,
22
+ caption: str,
23
+ num_retries: int = 3,
24
+ max_tokens: int = 256,
25
+ temperature: float = 0.7,
26
+ top_p: float = 1.0,
27
+ frequency_penalty: float = 0.1,
28
+ presence_penalty: float = 0.0,
29
+ sleep_on_error: float = 1.0,
30
+ ) -> Optional[tuple[str, str]]:
31
+ for _ in range(1 + num_retries):
32
+ try:
33
+ response = openai.Completion.create(
34
+ model=openai_model,
35
+ prompt=caption + DELIMITER_0,
36
+ temperature=temperature,
37
+ max_tokens=max_tokens,
38
+ top_p=top_p,
39
+ frequency_penalty=frequency_penalty,
40
+ presence_penalty=presence_penalty,
41
+ stop=[STOP],
42
+ )
43
+ except Exception as e:
44
+ print(e)
45
+ time.sleep(sleep_on_error)
46
+ continue
47
+ output = response["choices"][0]["text"].split(DELIMITER_1)
48
+ if len(output) == 2:
49
+ instruction, edited_caption = output
50
+ results = openai.Moderation.create([instruction, edited_caption])["results"]
51
+ if results[0]["flagged"] or results[1]["flagged"]:
52
+ continue
53
+ if caption.strip().strip(".!?").lower() != edited_caption.strip().strip(".!?").lower():
54
+ return instruction, edited_caption
55
+
56
+
57
+ def main(openai_model: str, num_samples: int, num_partitions: int, partition: int, seed: int):
58
+ dataset = datasets.load_dataset("ChristophSchuhmann/improved_aesthetics_6.5plus", split="train")
59
+ # Other datasets we considered that may be worth trying:
60
+ # dataset = datasets.load_dataset("ChristophSchuhmann/MS_COCO_2017_URL_TEXT", split="train")
61
+ # dataset = datasets.load_dataset("laion/laion-coco", split="train")
62
+
63
+ np.random.seed(seed)
64
+ permutation = np.array_split(np.random.permutation(len(dataset)), num_partitions)[partition]
65
+ dataset = dataset[permutation]
66
+ captions = dataset["TEXT"]
67
+ urls = dataset["URL"]
68
+ output_path = f"data/dataset=laion-aesthetics-6.5_model={openai_model}_samples={num_samples}_partition={partition}.jsonl" # fmt: skip
69
+ print(f"Prompt file path: {output_path}")
70
+
71
+ count = 0
72
+ caption_set = set()
73
+ url_set = set()
74
+
75
+ if Path(output_path).exists():
76
+ with open(output_path, "r") as f:
77
+ for line in tqdm(f, desc="Resuming from existing prompts"):
78
+ prompt = json.loads(line)
79
+ if prompt["caption"] not in caption_set and prompt["url"] not in url_set:
80
+ caption_set.add(prompt["caption"])
81
+ url_set.add(prompt["url"])
82
+ count += 1
83
+
84
+ with open(output_path, "a") as fp:
85
+ with tqdm(total=num_samples - count, desc="Generating instructions and edited captions") as progress_bar:
86
+ for caption, url in zip(captions, urls):
87
+ if caption in caption_set or url in url_set:
88
+ continue
89
+ if openai.Moderation.create(caption)["results"][0]["flagged"]:
90
+ continue
91
+ edit_output = generate(openai_model, caption)
92
+ if edit_output is not None:
93
+ edit, output = edit_output
94
+ fp.write(f"{json.dumps(dict(caption=caption, edit=edit, output=output, url=url))}\n")
95
+ count += 1
96
+ progress_bar.update()
97
+ caption_set.add(caption)
98
+ url_set.add(url)
99
+ if count == num_samples:
100
+ break
101
+
102
+
103
+ if __name__ == "__main__":
104
+ parser = ArgumentParser()
105
+ parser.add_argument("--openai-api-key", required=True, type=str)
106
+ parser.add_argument("--openai-model", required=True, type=str)
107
+ parser.add_argument("--num-samples", default=10000, type=int)
108
+ parser.add_argument("--num-partitions", default=1, type=int)
109
+ parser.add_argument("--partition", default=0, type=int)
110
+ parser.add_argument("--seed", default=0, type=int)
111
+ args = parser.parse_args()
112
+ openai.api_key = args.openai_api_key
113
+ main(args.openai_model, args.num_samples, args.num_partitions, args.partition, args.seed)
instruct-pix2pix-BioMedCLIP-concat-newdata/dataset_creation/prepare_dataset.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from argparse import ArgumentParser
3
+ from pathlib import Path
4
+
5
+ from tqdm.auto import tqdm
6
+
7
+
8
+ def main():
9
+ parser = ArgumentParser()
10
+ parser.add_argument("dataset_dir")
11
+ args = parser.parse_args()
12
+ dataset_dir = Path(args.dataset_dir)
13
+
14
+ seeds = []
15
+ with tqdm(desc="Listing dataset image seeds") as progress_bar:
16
+ for prompt_dir in dataset_dir.iterdir():
17
+ if prompt_dir.is_dir():
18
+ prompt_seeds = [image_path.name.split("_")[0] for image_path in sorted(prompt_dir.glob("*_0.jpg"))]
19
+ if len(prompt_seeds) > 0:
20
+ seeds.append((prompt_dir.name, prompt_seeds))
21
+ progress_bar.update()
22
+ seeds.sort()
23
+
24
+ with open(dataset_dir.joinpath("seeds.json"), "w") as f:
25
+ json.dump(seeds, f)
26
+
27
+
28
+ if __name__ == "__main__":
29
+ main()
instruct-pix2pix-BioMedCLIP-concat-newdata/dataset_creation/prepare_for_gpt.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from argparse import ArgumentParser
3
+
4
+ from generate_txt_dataset import DELIMITER_0, DELIMITER_1, STOP
5
+
6
+
7
+ def main(input_path: str, output_path: str):
8
+ with open(input_path) as f:
9
+ prompts = [json.loads(l) for l in f]
10
+
11
+ with open(output_path, "w") as f:
12
+ for prompt in prompts:
13
+ prompt_for_gpt = {
14
+ "prompt": f"{prompt['input']}{DELIMITER_0}",
15
+ "completion": f"{prompt['edit']}{DELIMITER_1}{prompt['output']}{STOP}",
16
+ }
17
+ f.write(f"{json.dumps(prompt_for_gpt)}\n")
18
+
19
+
20
+ if __name__ == "__main__":
21
+ parser = ArgumentParser()
22
+ parser.add_argument("--input-path", required=True, type=str)
23
+ parser.add_argument("--output-path", required=True, type=str)
24
+ args = parser.parse_args()
25
+ main(args.input_path, args.output_path)
instruct-pix2pix-BioMedCLIP-concat-newdata/edit_app.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ import random
5
+ import sys
6
+ from argparse import ArgumentParser
7
+
8
+ import einops
9
+ import gradio as gr
10
+ import k_diffusion as K
11
+ import numpy as np
12
+ import torch
13
+ import torch.nn as nn
14
+ from einops import rearrange
15
+ from omegaconf import OmegaConf
16
+ from PIL import Image, ImageOps
17
+ from torch import autocast
18
+
19
+ sys.path.append("./stable_diffusion")
20
+
21
+ from stable_diffusion.ldm.util import instantiate_from_config
22
+
23
+
24
+ help_text = """
25
+ If you're not getting what you want, there may be a few reasons:
26
+ 1. Is the image not changing enough? Your Image CFG weight may be too high. This value dictates how similar the output should be to the input. It's possible your edit requires larger changes from the original image, and your Image CFG weight isn't allowing that. Alternatively, your Text CFG weight may be too low. This value dictates how much to listen to the text instruction. The default Image CFG of 1.5 and Text CFG of 7.5 are a good starting point, but aren't necessarily optimal for each edit. Try:
27
+ * Decreasing the Image CFG weight, or
28
+ * Incerasing the Text CFG weight, or
29
+ 2. Conversely, is the image changing too much, such that the details in the original image aren't preserved? Try:
30
+ * Increasing the Image CFG weight, or
31
+ * Decreasing the Text CFG weight
32
+ 3. Try generating results with different random seeds by setting "Randomize Seed" and running generation multiple times. You can also try setting "Randomize CFG" to sample new Text CFG and Image CFG values each time.
33
+ 4. Rephrasing the instruction sometimes improves results (e.g., "turn him into a dog" vs. "make him a dog" vs. "as a dog").
34
+ 5. Increasing the number of steps sometimes improves results.
35
+ 6. Do faces look weird? The Stable Diffusion autoencoder has a hard time with faces that are small in the image. Try:
36
+ * Cropping the image so the face takes up a larger portion of the frame.
37
+ """
38
+
39
+
40
+ example_instructions = [
41
+ "Make it a picasso painting",
42
+ "as if it were by modigliani",
43
+ "convert to a bronze statue",
44
+ "Turn it into an anime.",
45
+ "have it look like a graphic novel",
46
+ "make him gain weight",
47
+ "what would he look like bald?",
48
+ "Have him smile",
49
+ "Put him in a cocktail party.",
50
+ "move him at the beach.",
51
+ "add dramatic lighting",
52
+ "Convert to black and white",
53
+ "What if it were snowing?",
54
+ "Give him a leather jacket",
55
+ "Turn him into a cyborg!",
56
+ "make him wear a beanie",
57
+ ]
58
+
59
+
60
+ class CFGDenoiser(nn.Module):
61
+ def __init__(self, model):
62
+ super().__init__()
63
+ self.inner_model = model
64
+
65
+ def forward(self, z, sigma, cond, uncond, text_cfg_scale, image_cfg_scale):
66
+ cfg_z = einops.repeat(z, "1 ... -> n ...", n=3)
67
+ cfg_sigma = einops.repeat(sigma, "1 ... -> n ...", n=3)
68
+ cfg_cond = {
69
+ "c_crossattn": [torch.cat([cond["c_crossattn"][0], uncond["c_crossattn"][0], uncond["c_crossattn"][0]])],
70
+ "c_concat": [torch.cat([cond["c_concat"][0], cond["c_concat"][0], uncond["c_concat"][0]])],
71
+ }
72
+ out_cond, out_img_cond, out_uncond = self.inner_model(cfg_z, cfg_sigma, cond=cfg_cond).chunk(3)
73
+ return out_uncond + text_cfg_scale * (out_cond - out_img_cond) + image_cfg_scale * (out_img_cond - out_uncond)
74
+
75
+
76
+ def load_model_from_config(config, ckpt, vae_ckpt=None, verbose=False):
77
+ print(f"Loading model from {ckpt}")
78
+ pl_sd = torch.load(ckpt, map_location="cpu")
79
+ if "global_step" in pl_sd:
80
+ print(f"Global Step: {pl_sd['global_step']}")
81
+ sd = pl_sd["state_dict"]
82
+ if vae_ckpt is not None:
83
+ print(f"Loading VAE from {vae_ckpt}")
84
+ vae_sd = torch.load(vae_ckpt, map_location="cpu")["state_dict"]
85
+ sd = {
86
+ k: vae_sd[k[len("first_stage_model.") :]] if k.startswith("first_stage_model.") else v
87
+ for k, v in sd.items()
88
+ }
89
+ model = instantiate_from_config(config.model)
90
+ m, u = model.load_state_dict(sd, strict=False)
91
+ if len(m) > 0 and verbose:
92
+ print("missing keys:")
93
+ print(m)
94
+ if len(u) > 0 and verbose:
95
+ print("unexpected keys:")
96
+ print(u)
97
+ return model
98
+
99
+
100
+ def main():
101
+ parser = ArgumentParser()
102
+ parser.add_argument("--resolution", default=512, type=int)
103
+ parser.add_argument("--config", default="configs/generate.yaml", type=str)
104
+ parser.add_argument("--ckpt", default="checkpoints/instruct-pix2pix-00-22000.ckpt", type=str)
105
+ parser.add_argument("--vae-ckpt", default=None, type=str)
106
+ args = parser.parse_args()
107
+
108
+ config = OmegaConf.load(args.config)
109
+ model = load_model_from_config(config, args.ckpt, args.vae_ckpt)
110
+ model.eval().cuda()
111
+ model_wrap = K.external.CompVisDenoiser(model)
112
+ model_wrap_cfg = CFGDenoiser(model_wrap)
113
+ null_token = model.get_learned_conditioning([""])
114
+ example_image = Image.open("imgs/example.jpg").convert("RGB")
115
+
116
+ def load_example(
117
+ steps: int,
118
+ randomize_seed: bool,
119
+ seed: int,
120
+ randomize_cfg: bool,
121
+ text_cfg_scale: float,
122
+ image_cfg_scale: float,
123
+ ):
124
+ example_instruction = random.choice(example_instructions)
125
+ return [example_image, example_instruction] + generate(
126
+ example_image,
127
+ example_instruction,
128
+ steps,
129
+ randomize_seed,
130
+ seed,
131
+ randomize_cfg,
132
+ text_cfg_scale,
133
+ image_cfg_scale,
134
+ )
135
+
136
+ def generate(
137
+ input_image: Image.Image,
138
+ instruction: str,
139
+ steps: int,
140
+ randomize_seed: bool,
141
+ seed: int,
142
+ randomize_cfg: bool,
143
+ text_cfg_scale: float,
144
+ image_cfg_scale: float,
145
+ ):
146
+ seed = random.randint(0, 100000) if randomize_seed else seed
147
+ text_cfg_scale = round(random.uniform(6.0, 9.0), ndigits=2) if randomize_cfg else text_cfg_scale
148
+ image_cfg_scale = round(random.uniform(1.2, 1.8), ndigits=2) if randomize_cfg else image_cfg_scale
149
+
150
+ width, height = input_image.size
151
+ factor = args.resolution / max(width, height)
152
+ factor = math.ceil(min(width, height) * factor / 64) * 64 / min(width, height)
153
+ width = int((width * factor) // 64) * 64
154
+ height = int((height * factor) // 64) * 64
155
+ input_image = ImageOps.fit(input_image, (width, height), method=Image.Resampling.LANCZOS)
156
+
157
+ if instruction == "":
158
+ return [input_image, seed]
159
+
160
+ with torch.no_grad(), autocast("cuda"), model.ema_scope():
161
+ cond = {}
162
+ cond["c_crossattn"] = [model.get_learned_conditioning([instruction])]
163
+ input_image = 2 * torch.tensor(np.array(input_image)).float() / 255 - 1
164
+ input_image = rearrange(input_image, "h w c -> 1 c h w").to(model.device)
165
+ cond["c_concat"] = [model.encode_first_stage(input_image).mode()]
166
+
167
+ uncond = {}
168
+ uncond["c_crossattn"] = [null_token]
169
+ uncond["c_concat"] = [torch.zeros_like(cond["c_concat"][0])]
170
+
171
+ sigmas = model_wrap.get_sigmas(steps)
172
+
173
+ extra_args = {
174
+ "cond": cond,
175
+ "uncond": uncond,
176
+ "text_cfg_scale": text_cfg_scale,
177
+ "image_cfg_scale": image_cfg_scale,
178
+ }
179
+ torch.manual_seed(seed)
180
+ z = torch.randn_like(cond["c_concat"][0]) * sigmas[0]
181
+ z = K.sampling.sample_euler_ancestral(model_wrap_cfg, z, sigmas, extra_args=extra_args)
182
+ x = model.decode_first_stage(z)
183
+ x = torch.clamp((x + 1.0) / 2.0, min=0.0, max=1.0)
184
+ x = 255.0 * rearrange(x, "1 c h w -> h w c")
185
+ edited_image = Image.fromarray(x.type(torch.uint8).cpu().numpy())
186
+
187
+ return [seed, text_cfg_scale, image_cfg_scale, edited_image]
188
+
189
+ def reset():
190
+ return [0, "Randomize Seed", 1371, "Fix CFG", 7.5, 1.5, None]
191
+
192
+ with gr.Blocks(css="footer {visibility: hidden}") as demo:
193
+ with gr.Row():
194
+ with gr.Column(scale=1, min_width=100):
195
+ generate_button = gr.Button("Generate")
196
+ with gr.Column(scale=1, min_width=100):
197
+ load_button = gr.Button("Load Example")
198
+ with gr.Column(scale=1, min_width=100):
199
+ reset_button = gr.Button("Reset")
200
+ with gr.Column(scale=3):
201
+ instruction = gr.Textbox(lines=1, label="Edit Instruction", interactive=True)
202
+
203
+ with gr.Row():
204
+ input_image = gr.Image(label="Input Image", type="pil", interactive=True)
205
+ edited_image = gr.Image(label=f"Edited Image", type="pil", interactive=False)
206
+ input_image.style(height=512, width=512)
207
+ edited_image.style(height=512, width=512)
208
+
209
+ with gr.Row():
210
+ steps = gr.Number(value=100, precision=0, label="Steps", interactive=True)
211
+ randomize_seed = gr.Radio(
212
+ ["Fix Seed", "Randomize Seed"],
213
+ value="Randomize Seed",
214
+ type="index",
215
+ show_label=False,
216
+ interactive=True,
217
+ )
218
+ seed = gr.Number(value=1371, precision=0, label="Seed", interactive=True)
219
+ randomize_cfg = gr.Radio(
220
+ ["Fix CFG", "Randomize CFG"],
221
+ value="Fix CFG",
222
+ type="index",
223
+ show_label=False,
224
+ interactive=True,
225
+ )
226
+ text_cfg_scale = gr.Number(value=7.5, label=f"Text CFG", interactive=True)
227
+ image_cfg_scale = gr.Number(value=1.5, label=f"Image CFG", interactive=True)
228
+
229
+ gr.Markdown(help_text)
230
+
231
+ load_button.click(
232
+ fn=load_example,
233
+ inputs=[
234
+ steps,
235
+ randomize_seed,
236
+ seed,
237
+ randomize_cfg,
238
+ text_cfg_scale,
239
+ image_cfg_scale,
240
+ ],
241
+ outputs=[input_image, instruction, seed, text_cfg_scale, image_cfg_scale, edited_image],
242
+ )
243
+ generate_button.click(
244
+ fn=generate,
245
+ inputs=[
246
+ input_image,
247
+ instruction,
248
+ steps,
249
+ randomize_seed,
250
+ seed,
251
+ randomize_cfg,
252
+ text_cfg_scale,
253
+ image_cfg_scale,
254
+ ],
255
+ outputs=[seed, text_cfg_scale, image_cfg_scale, edited_image],
256
+ )
257
+ reset_button.click(
258
+ fn=reset,
259
+ inputs=[],
260
+ outputs=[steps, randomize_seed, seed, randomize_cfg, text_cfg_scale, image_cfg_scale, edited_image],
261
+ )
262
+
263
+ demo.queue(concurrency_count=1)
264
+ demo.launch(share=True)
265
+
266
+
267
+ if __name__ == "__main__":
268
+ main()
instruct-pix2pix-BioMedCLIP-concat-newdata/edit_cli.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ import random
5
+ import sys
6
+ from argparse import ArgumentParser
7
+
8
+ import einops
9
+ import k_diffusion as K
10
+ import numpy as np
11
+ import torch
12
+ import torch.nn as nn
13
+ from einops import rearrange
14
+ from omegaconf import OmegaConf
15
+ from PIL import Image, ImageOps
16
+ from torch import autocast
17
+
18
+ sys.path.append("./stable_diffusion")
19
+
20
+ from stable_diffusion.ldm.util import instantiate_from_config
21
+
22
+
23
+ class CFGDenoiser(nn.Module):
24
+ def __init__(self, model):
25
+ super().__init__()
26
+ self.inner_model = model
27
+
28
+ def forward(self, z, sigma, cond, uncond, text_cfg_scale, image_cfg_scale):
29
+ cfg_z = einops.repeat(z, "1 ... -> n ...", n=3)
30
+ cfg_sigma = einops.repeat(sigma, "1 ... -> n ...", n=3)
31
+ cfg_cond = {
32
+ "c_crossattn": [torch.cat([cond["c_crossattn"][0], uncond["c_crossattn"][0], uncond["c_crossattn"][0]])],
33
+ "c_concat": [torch.cat([cond["c_concat"][0], cond["c_concat"][0], uncond["c_concat"][0]])],
34
+ }
35
+ out_cond, out_img_cond, out_uncond = self.inner_model(cfg_z, cfg_sigma, cond=cfg_cond).chunk(3)
36
+ return out_uncond + text_cfg_scale * (out_cond - out_img_cond) + image_cfg_scale * (out_img_cond - out_uncond)
37
+
38
+
39
+ def load_model_from_config(config, ckpt, vae_ckpt=None, verbose=False):
40
+ print(f"Loading model from {ckpt}")
41
+ pl_sd = torch.load(ckpt, map_location="cpu")
42
+ if "global_step" in pl_sd:
43
+ print(f"Global Step: {pl_sd['global_step']}")
44
+ sd = pl_sd["state_dict"]
45
+ if vae_ckpt is not None:
46
+ print(f"Loading VAE from {vae_ckpt}")
47
+ vae_sd = torch.load(vae_ckpt, map_location="cpu")["state_dict"]
48
+ sd = {
49
+ k: vae_sd[k[len("first_stage_model.") :]] if k.startswith("first_stage_model.") else v
50
+ for k, v in sd.items()
51
+ }
52
+ model = instantiate_from_config(config.model)
53
+ m, u = model.load_state_dict(sd, strict=False)
54
+ if len(m) > 0 and verbose:
55
+ print("missing keys:")
56
+ print(m)
57
+ if len(u) > 0 and verbose:
58
+ print("unexpected keys:")
59
+ print(u)
60
+ return model
61
+
62
+
63
+ def main():
64
+ parser = ArgumentParser()
65
+ parser.add_argument("--resolution", default=512, type=int)
66
+ parser.add_argument("--steps", default=100, type=int)
67
+ parser.add_argument("--config", default="configs/generate.yaml", type=str)
68
+ parser.add_argument("--ckpt", default="checkpoints/instruct-pix2pix-00-22000.ckpt", type=str)
69
+ parser.add_argument("--vae-ckpt", default=None, type=str)
70
+ parser.add_argument("--input", required=True, type=str)
71
+ parser.add_argument("--output", required=True, type=str)
72
+ parser.add_argument("--edit", required=True, type=str)
73
+ parser.add_argument("--cfg-text", default=7.5, type=float)
74
+ parser.add_argument("--cfg-image", default=1.5, type=float)
75
+ parser.add_argument("--seed", type=int)
76
+ args = parser.parse_args()
77
+
78
+ config = OmegaConf.load(args.config)
79
+ model = load_model_from_config(config, args.ckpt, args.vae_ckpt)
80
+ model.eval().cuda()
81
+ model_wrap = K.external.CompVisDenoiser(model)
82
+ model_wrap_cfg = CFGDenoiser(model_wrap)
83
+ null_token = model.get_learned_conditioning([""])
84
+
85
+ seed = random.randint(0, 100000) if args.seed is None else args.seed
86
+ input_image = Image.open(args.input).convert("RGB")
87
+ width, height = input_image.size
88
+ factor = args.resolution / max(width, height)
89
+ factor = math.ceil(min(width, height) * factor / 64) * 64 / min(width, height)
90
+ width = int((width * factor) // 64) * 64
91
+ height = int((height * factor) // 64) * 64
92
+ input_image = ImageOps.fit(input_image, (width, height), method=Image.Resampling.LANCZOS)
93
+
94
+ if args.edit == "":
95
+ input_image.save(args.output)
96
+ return
97
+
98
+ with torch.no_grad(), autocast("cuda"), model.ema_scope():
99
+ cond = {}
100
+ cond["c_crossattn"] = [model.get_learned_conditioning([args.edit])]
101
+ input_image = 2 * torch.tensor(np.array(input_image)).float() / 255 - 1
102
+ input_image = rearrange(input_image, "h w c -> 1 c h w").to(model.device)
103
+ cond["c_concat"] = [model.encode_first_stage(input_image).mode()]
104
+
105
+ uncond = {}
106
+ uncond["c_crossattn"] = [null_token]
107
+ uncond["c_concat"] = [torch.zeros_like(cond["c_concat"][0])]
108
+
109
+ sigmas = model_wrap.get_sigmas(args.steps)
110
+
111
+ extra_args = {
112
+ "cond": cond,
113
+ "uncond": uncond,
114
+ "text_cfg_scale": args.cfg_text,
115
+ "image_cfg_scale": args.cfg_image,
116
+ }
117
+ torch.manual_seed(seed)
118
+ z = torch.randn_like(cond["c_concat"][0]) * sigmas[0]
119
+ z = K.sampling.sample_euler_ancestral(model_wrap_cfg, z, sigmas, extra_args=extra_args)
120
+ x = model.decode_first_stage(z)
121
+ x = torch.clamp((x + 1.0) / 2.0, min=0.0, max=1.0)
122
+ x = 255.0 * rearrange(x, "1 c h w -> h w c")
123
+ edited_image = Image.fromarray(x.type(torch.uint8).cpu().numpy())
124
+ edited_image.save(args.output)
125
+
126
+
127
+ if __name__ == "__main__":
128
+ main()
instruct-pix2pix-BioMedCLIP-concat-newdata/edit_dataset.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import math
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ import numpy as np
9
+ import torch
10
+ import torchvision
11
+ from einops import rearrange
12
+ from PIL import Image
13
+ from torch.utils.data import Dataset
14
+
15
+
16
+ class EditDataset(Dataset):
17
+ def __init__(
18
+ self,
19
+ path: str,
20
+ split: str = "train",
21
+ splits: tuple[float, float, float] = (0.9, 0.05, 0.05),
22
+ min_resize_res: int = 256,
23
+ max_resize_res: int = 256,
24
+ crop_res: int = 256,
25
+ flip_prob: float = 0.0,
26
+ ):
27
+ assert split in ("train", "val", "test")
28
+ assert sum(splits) == 1
29
+ self.path = path
30
+ self.min_resize_res = min_resize_res
31
+ self.max_resize_res = max_resize_res
32
+ self.crop_res = crop_res
33
+ self.flip_prob = flip_prob
34
+
35
+ with open(Path(self.path, "seeds.json")) as f:
36
+ self.seeds = json.load(f)
37
+
38
+ split_0, split_1 = {
39
+ "train": (0.0, splits[0]),
40
+ "val": (splits[0], splits[0] + splits[1]),
41
+ "test": (splits[0] + splits[1], 1.0),
42
+ }[split]
43
+
44
+ idx_0 = math.floor(split_0 * len(self.seeds))
45
+ idx_1 = math.floor(split_1 * len(self.seeds))
46
+ self.seeds = self.seeds[idx_0:idx_1]
47
+
48
+ def __len__(self) -> int:
49
+ return len(self.seeds)
50
+
51
+ def __getitem__(self, i: int) -> dict[str, Any]:
52
+ name, seeds = self.seeds[i]
53
+ propt_dir = Path(self.path, name)
54
+ seed = seeds[torch.randint(0, len(seeds), ()).item()]
55
+ with open(propt_dir.joinpath("prompt.json")) as fp:
56
+ prompt = json.load(fp)["edit"]
57
+
58
+ image_0 = Image.open(propt_dir.joinpath(f"{seed}_0.jpg"))
59
+ image_1 = Image.open(propt_dir.joinpath(f"{seed}_1.jpg"))
60
+
61
+ reize_res = torch.randint(self.min_resize_res, self.max_resize_res + 1, ()).item()
62
+ image_0 = image_0.resize((reize_res, reize_res), Image.Resampling.LANCZOS)
63
+ image_1 = image_1.resize((reize_res, reize_res), Image.Resampling.LANCZOS)
64
+
65
+ image_0 = rearrange(2 * torch.tensor(np.array(image_0)).float() / 255 - 1, "h w c -> c h w")
66
+ image_1 = rearrange(2 * torch.tensor(np.array(image_1)).float() / 255 - 1, "h w c -> c h w")
67
+
68
+ crop = torchvision.transforms.RandomCrop(self.crop_res)
69
+ flip = torchvision.transforms.RandomHorizontalFlip(float(self.flip_prob))
70
+ image_0, image_1 = flip(crop(torch.cat((image_0, image_1)))).chunk(2)
71
+
72
+ return dict(edited=image_1, edit=dict(c_concat=image_0, c_crossattn=prompt))
73
+
74
+
75
+ class EditDatasetEval(Dataset):
76
+ def __init__(
77
+ self,
78
+ path: str,
79
+ split: str = "train",
80
+ splits: tuple[float, float, float] = (0.9, 0.05, 0.05),
81
+ res: int = 256,
82
+ ):
83
+ assert split in ("train", "val", "test")
84
+ assert sum(splits) == 1
85
+ self.path = path
86
+ self.res = res
87
+
88
+ with open(Path(self.path, "seeds.json")) as f:
89
+ self.seeds = json.load(f)
90
+
91
+ split_0, split_1 = {
92
+ "train": (0.0, splits[0]),
93
+ "val": (splits[0], splits[0] + splits[1]),
94
+ "test": (splits[0] + splits[1], 1.0),
95
+ }[split]
96
+
97
+ idx_0 = math.floor(split_0 * len(self.seeds))
98
+ idx_1 = math.floor(split_1 * len(self.seeds))
99
+ self.seeds = self.seeds[idx_0:idx_1]
100
+
101
+ def __len__(self) -> int:
102
+ return len(self.seeds)
103
+
104
+ def __getitem__(self, i: int) -> dict[str, Any]:
105
+ name, seeds = self.seeds[i]
106
+ propt_dir = Path(self.path, name)
107
+ seed = seeds[torch.randint(0, len(seeds), ()).item()]
108
+ with open(propt_dir.joinpath("prompt.json")) as fp:
109
+ prompt = json.load(fp)
110
+ edit = prompt["edit"]
111
+ input_prompt = prompt["input"]
112
+ output_prompt = prompt["output"]
113
+
114
+ image_0 = Image.open(propt_dir.joinpath(f"{seed}_0.jpg"))
115
+
116
+ reize_res = torch.randint(self.res, self.res + 1, ()).item()
117
+ image_0 = image_0.resize((reize_res, reize_res), Image.Resampling.LANCZOS)
118
+
119
+ image_0 = rearrange(2 * torch.tensor(np.array(image_0)).float() / 255 - 1, "h w c -> c h w")
120
+
121
+ return dict(image_0=image_0, input_prompt=input_prompt, edit=edit, output_prompt=output_prompt)
instruct-pix2pix-BioMedCLIP-concat-newdata/environment.yaml ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File modified by authors of InstructPix2Pix from original (https://github.com/CompVis/stable-diffusion).
2
+ # See more details in LICENSE.
3
+
4
+ name: ip2p
5
+ channels:
6
+ - pytorch
7
+ - defaults
8
+ dependencies:
9
+ - python=3.8.5
10
+ - pip=20.3
11
+ - cudatoolkit=11.3
12
+ - pytorch=1.11.0
13
+ - torchvision=0.12.0
14
+ - numpy=1.19.2
15
+ - pip:
16
+ - albumentations==0.4.3
17
+ - datasets==2.8.0
18
+ - diffusers
19
+ - opencv-python==4.1.2.30
20
+ - pudb==2019.2
21
+ - invisible-watermark
22
+ - imageio==2.9.0
23
+ - imageio-ffmpeg==0.4.2
24
+ - pytorch-lightning==1.4.2
25
+ - omegaconf==2.1.1
26
+ - test-tube>=0.7.5
27
+ - streamlit>=0.73.1
28
+ - einops==0.3.0
29
+ - torch-fidelity==0.3.0
30
+ - transformers==4.19.2
31
+ - torchmetrics==0.6.0
32
+ - kornia==0.6
33
+ - -e git+https://github.com/CompVis/taming-transformers.git@master#egg=taming-transformers
34
+ - -e git+https://github.com/openai/CLIP.git@main#egg=clip
35
+ - openai
36
+ - gradio
37
+ - seaborn
38
+ - git+https://github.com/crowsonkb/k-diffusion.git
instruct-pix2pix-BioMedCLIP-concat-newdata/imgs/dataset.jpg ADDED

Git LFS Details

  • SHA256: 9393c97383a25b93e0bfef374033b6c6d953124bb1f37181de7345c725ff8dbc
  • Pointer size: 131 Bytes
  • Size of remote file: 100 kB
instruct-pix2pix-BioMedCLIP-concat-newdata/imgs/edit_app.jpg ADDED

Git LFS Details

  • SHA256: 395761cecae1d5442f8c48435f552f129b3425df1bccaaff82526d49bf5aeaea
  • Pointer size: 131 Bytes
  • Size of remote file: 402 kB
instruct-pix2pix-BioMedCLIP-concat-newdata/imgs/example.jpg ADDED
instruct-pix2pix-BioMedCLIP-concat-newdata/imgs/prompt_app.jpg ADDED
instruct-pix2pix-BioMedCLIP-concat-newdata/inference_full_ct_2d_with_body_mask.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import nibabel as nib
3
+ import numpy as np
4
+ import os
5
+ import torch
6
+ from skimage import io
7
+ from einops import rearrange
8
+ from omegaconf import OmegaConf
9
+ from torch.utils.data import DataLoader
10
+ from tqdm import tqdm
11
+ from argparse import ArgumentParser
12
+ import sys
13
+ sys.path.append("./stable_diffusion")
14
+ import torch.nn as nn
15
+ from ldm.util import instantiate_from_config
16
+ import k_diffusion as K
17
+ from torch import autocast
18
+ import random
19
+ import einops
20
+ from PIL import Image, ImageOps
21
+ class CFGDenoiser(nn.Module):
22
+ def __init__(self, model):
23
+ super().__init__()
24
+ self.inner_model = model
25
+
26
+ def forward(self, z, sigma, cond, uncond, text_cfg_scale, image_cfg_scale):
27
+ cfg_z = einops.repeat(z, "1 ... -> n ...", n=3)
28
+ cfg_sigma = einops.repeat(sigma, "1 ... -> n ...", n=3)
29
+ cfg_cond = {
30
+ "c_crossattn": [torch.cat([cond["c_crossattn"][0], uncond["c_crossattn"][0], uncond["c_crossattn"][0]])],
31
+ "c_concat": [torch.cat([cond["c_concat"][0], cond["c_concat"][0], uncond["c_concat"][0]])],
32
+ }
33
+ out_cond, out_img_cond, out_uncond = self.inner_model(cfg_z, cfg_sigma, cond=cfg_cond).chunk(3)
34
+ return out_uncond + text_cfg_scale * (out_cond - out_img_cond) + image_cfg_scale * (out_img_cond - out_uncond)
35
+
36
+
37
+ def load_model_from_config(config, ckpt, vae_ckpt=None, verbose=False):
38
+ print(f"Loading model from {ckpt}")
39
+ pl_sd = torch.load(ckpt, map_location="cpu")
40
+ if "global_step" in pl_sd:
41
+ print(f"Global Step: {pl_sd['global_step']}")
42
+ sd = pl_sd["state_dict"]
43
+ if vae_ckpt is not None:
44
+ print(f"Loading VAE from {vae_ckpt}")
45
+ vae_sd = torch.load(vae_ckpt, map_location="cpu")["state_dict"]
46
+ sd = {
47
+ k: vae_sd[k[len("first_stage_model.") :]] if k.startswith("first_stage_model.") else v
48
+ for k, v in sd.items()
49
+ }
50
+ model = instantiate_from_config(config.model)
51
+ m, u = model.load_state_dict(sd, strict=False)
52
+ if len(m) > 0 and verbose:
53
+ print("missing keys:")
54
+ print(m)
55
+ if len(u) > 0 and verbose:
56
+ print("unexpected keys:")
57
+ print(u)
58
+ return model
59
+
60
+ parser = ArgumentParser()
61
+ parser.add_argument("--resolution", default=512, type=int)
62
+ parser.add_argument("--steps", default=100, type=int)
63
+ parser.add_argument("--config", default="configs/generate.yaml", type=str)
64
+ # parser.add_argument("--ckpt", default="checkpoints/instruct-pix2pix-00-22000.ckpt", type=str)
65
+ parser.add_argument("--ckpt", default="logs/train_instructpix2pix/checkpoints/epoch=000806.ckpt", type=str)
66
+ parser.add_argument("--vae-ckpt", default=None, type=str)
67
+
68
+ parser.add_argument("--cfg-text", default=7.5, type=float)
69
+ parser.add_argument("--cfg-image", default=1.5, type=float)
70
+ parser.add_argument("--seed", type=int)
71
+ args = parser.parse_args()
72
+ seed = random.randint(0, 100000) if args.seed is None else args.seed
73
+
74
+ config = OmegaConf.load(args.config)
75
+ model = load_model_from_config(config, args.ckpt, args.vae_ckpt)
76
+ model.eval().cuda()
77
+ model_wrap = K.external.CompVisDenoiser(model)
78
+ model_wrap_cfg = CFGDenoiser(model_wrap)
79
+ null_token = model.get_learned_conditioning([""])
80
+
81
+
82
+ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
83
+ print("Using device", device)
84
+ model = model.to(device)
85
+
86
+ config = OmegaConf.load('./configs/train.yaml')
87
+ data = instantiate_from_config(config.data)
88
+ data.prepare_data()
89
+ data.setup()
90
+
91
+ save_path = 'logs/train_instructpix2pix/inference'
92
+ if not os.path.exists(save_path):
93
+ os.makedirs(save_path)
94
+
95
+ val_dataset = data.datasets['validation']
96
+ batch_size = 1
97
+ valloader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False, num_workers=0, pin_memory=True)
98
+ val_num = len(val_dataset)
99
+ save_gt = True
100
+ # val_num = 10
101
+ # breakpoint()
102
+ for idx, data in tqdm(enumerate(valloader)):
103
+ # if idx >= val_num:
104
+ # break
105
+ name=data['name'][0].split('.')[0]
106
+
107
+ # breakpoint()
108
+ z, cond = model.get_input(data, model.first_stage_key)
109
+
110
+ with torch.no_grad(), autocast("cuda"), model.ema_scope():
111
+ uncond = {}
112
+ uncond["c_crossattn"] = [null_token]
113
+ uncond["c_concat"] = [torch.zeros_like(cond["c_concat"][0])]
114
+
115
+ sigmas = model_wrap.get_sigmas(args.steps)
116
+
117
+ extra_args = {
118
+ "cond": cond,
119
+ "uncond": uncond,
120
+ "text_cfg_scale": args.cfg_text,
121
+ "image_cfg_scale": args.cfg_image,
122
+ }
123
+ torch.manual_seed(seed)
124
+ z = torch.randn_like(cond["c_concat"][0]) * sigmas[0]
125
+ z = K.sampling.sample_euler_ancestral(model_wrap_cfg, z, sigmas, extra_args=extra_args)
126
+ x = model.decode_first_stage(z)
127
+ x = torch.clamp((x + 1.0) / 2.0, min=0.0, max=1.0)
128
+ x = 255.0 * rearrange(x, "1 c h w -> h w c")
129
+ # breakpoint()
130
+ edited_image = x.type(torch.uint8).cpu().numpy()
131
+ # edited_image = Image.fromarray(x.type(torch.uint8).cpu().numpy())
132
+
133
+ input_img = (data['edit']['c_concat'][0].detach().cpu().numpy() + 1.0) / 2.0
134
+ input_img = np.clip(input_img ,0,1) * 255
135
+
136
+ io.imsave(os.path.join(save_path, str(name) + f'edited_image_{idx}.png'), edited_image.astype(np.uint8))
137
+ io.imsave(os.path.join(save_path, str(name) + f'input_image_{idx}.png'), input_img.astype(np.uint8))
138
+
139
+ # break
140
+
141
+
instruct-pix2pix-BioMedCLIP-concat-newdata/main.py ADDED
@@ -0,0 +1,829 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse, os, sys, datetime, glob
2
+ import numpy as np
3
+ import time
4
+ import torch
5
+ import torchvision
6
+
7
+ import enum
8
+
9
+ # 保存原始实现(可选,用于调试或回滚)
10
+ _enum_format_orig = enum.Enum.__format__
11
+
12
+ def _enum_format_value(self, format_spec: str) -> str:
13
+ # 如果指定了 format 规范,就交给 value 本身的格式化;否则直接返回 value
14
+ return format(self.value, format_spec) if format_spec else str(self.value)
15
+
16
+ # 全局替换 Enum.__format__
17
+ enum.Enum.__format__ = _enum_format_value
18
+
19
+ import pytorch_lightning as pl
20
+ import json
21
+ import pickle
22
+
23
+ from packaging import version
24
+ from omegaconf import OmegaConf
25
+ from torch.utils.data import DataLoader, Dataset
26
+ from functools import partial
27
+ from PIL import Image
28
+
29
+ import torch.distributed as dist
30
+ from pytorch_lightning import seed_everything
31
+ from pytorch_lightning.trainer import Trainer
32
+ from pytorch_lightning.callbacks import ModelCheckpoint, Callback, LearningRateMonitor
33
+ from pytorch_lightning.utilities.distributed import rank_zero_only
34
+ from pytorch_lightning.utilities import rank_zero_info
35
+ from pytorch_lightning.plugins import DDPPlugin
36
+
37
+ sys.path.append("./stable_diffusion")
38
+
39
+ from ldm.data.base import Txt2ImgIterableBaseDataset
40
+ from ldm.util import instantiate_from_config
41
+
42
+ # add jing
43
+ from torch.serialization import add_safe_globals, safe_globals
44
+ from pytorch_lightning.callbacks.model_checkpoint import ModelCheckpoint
45
+
46
+ add_safe_globals([
47
+ ModelCheckpoint,
48
+ np.core.multiarray.scalar,
49
+ ])
50
+
51
+ _real_torch_load = torch.load
52
+
53
+ def torch_load_compat(*args, **kwargs):
54
+ kwargs['weights_only'] = False
55
+ return _real_torch_load(*args, **kwargs)
56
+
57
+ torch.load = torch_load_compat
58
+ print("[patch] torch.load monkey-patched for legacy Lightning/NumPy ckpt")
59
+
60
+ def get_parser(**parser_kwargs):
61
+ def str2bool(v):
62
+ if isinstance(v, bool):
63
+ return v
64
+ if v.lower() in ("yes", "true", "t", "y", "1"):
65
+ return True
66
+ elif v.lower() in ("no", "false", "f", "n", "0"):
67
+ return False
68
+ else:
69
+ raise argparse.ArgumentTypeError("Boolean value expected.")
70
+
71
+ parser = argparse.ArgumentParser(**parser_kwargs)
72
+ parser.add_argument(
73
+ "-n",
74
+ "--name",
75
+ type=str,
76
+ const=True,
77
+ default="",
78
+ nargs="?",
79
+ help="postfix for logdir",
80
+ )
81
+ parser.add_argument(
82
+ "-r",
83
+ "--resume",
84
+ type=str,
85
+ const=True,
86
+ default="",
87
+ nargs="?",
88
+ help="resume from logdir or checkpoint in logdir",
89
+ )
90
+ parser.add_argument(
91
+ "-b",
92
+ "--base",
93
+ nargs="*",
94
+ metavar="base_config.yaml",
95
+ help="paths to base configs. Loaded from left-to-right. "
96
+ "Parameters can be overwritten or added with command-line options of the form `--key value`.",
97
+ default=list(),
98
+ )
99
+ parser.add_argument(
100
+ "-t",
101
+ "--train",
102
+ type=str2bool,
103
+ const=True,
104
+ default=False,
105
+ nargs="?",
106
+ help="train",
107
+ )
108
+ parser.add_argument(
109
+ "--no-test",
110
+ type=str2bool,
111
+ const=True,
112
+ default=False,
113
+ nargs="?",
114
+ help="disable test",
115
+ )
116
+ parser.add_argument(
117
+ "-p",
118
+ "--project",
119
+ help="name of new or path to existing project"
120
+ )
121
+ parser.add_argument(
122
+ "-d",
123
+ "--debug",
124
+ type=str2bool,
125
+ nargs="?",
126
+ const=True,
127
+ default=False,
128
+ help="enable post-mortem debugging",
129
+ )
130
+ parser.add_argument(
131
+ "-s",
132
+ "--seed",
133
+ type=int,
134
+ default=23,
135
+ help="seed for seed_everything",
136
+ )
137
+ parser.add_argument(
138
+ "-f",
139
+ "--postfix",
140
+ type=str,
141
+ default="",
142
+ help="post-postfix for default name",
143
+ )
144
+ parser.add_argument(
145
+ "-l",
146
+ "--logdir",
147
+ type=str,
148
+ default="logs",
149
+ help="directory for logging dat shit",
150
+ )
151
+ parser.add_argument(
152
+ "--scale_lr",
153
+ action="store_true",
154
+ default=False,
155
+ help="scale base-lr by ngpu * batch_size * n_accumulate",
156
+ )
157
+ return parser
158
+
159
+
160
+ def nondefault_trainer_args(opt):
161
+ parser = argparse.ArgumentParser()
162
+ parser = Trainer.add_argparse_args(parser)
163
+ args = parser.parse_args([])
164
+ return sorted(k for k in vars(args) if getattr(opt, k) != getattr(args, k))
165
+
166
+
167
+ class WrappedDataset(Dataset):
168
+ """Wraps an arbitrary object with __len__ and __getitem__ into a pytorch dataset"""
169
+
170
+ def __init__(self, dataset):
171
+ self.data = dataset
172
+
173
+ def __len__(self):
174
+ return len(self.data)
175
+
176
+ def __getitem__(self, idx):
177
+ return self.data[idx]
178
+
179
+
180
+ def worker_init_fn(_):
181
+ worker_info = torch.utils.data.get_worker_info()
182
+
183
+ dataset = worker_info.dataset
184
+ worker_id = worker_info.id
185
+
186
+ if isinstance(dataset, Txt2ImgIterableBaseDataset):
187
+ split_size = dataset.num_records // worker_info.num_workers
188
+ # reset num_records to the true number to retain reliable length information
189
+ dataset.sample_ids = dataset.valid_ids[worker_id * split_size:(worker_id + 1) * split_size]
190
+ current_id = np.random.choice(len(np.random.get_state()[1]), 1)
191
+ return np.random.seed(np.random.get_state()[1][current_id] + worker_id)
192
+ else:
193
+ return np.random.seed(np.random.get_state()[1][0] + worker_id)
194
+
195
+
196
+ class DataModuleFromConfig(pl.LightningDataModule):
197
+ def __init__(self, batch_size, train=None, validation=None, test=None, predict=None,
198
+ wrap=False, num_workers=None, shuffle_test_loader=False, use_worker_init_fn=False,
199
+ shuffle_val_dataloader=False):
200
+ super().__init__()
201
+ self.batch_size = batch_size
202
+ self.dataset_configs = dict()
203
+ self.num_workers = num_workers if num_workers is not None else batch_size * 2
204
+ self.use_worker_init_fn = use_worker_init_fn
205
+ if train is not None:
206
+ self.dataset_configs["train"] = train
207
+ self.train_dataloader = self._train_dataloader
208
+ if validation is not None:
209
+ self.dataset_configs["validation"] = validation
210
+ self.val_dataloader = partial(self._val_dataloader, shuffle=shuffle_val_dataloader)
211
+ if test is not None:
212
+ self.dataset_configs["test"] = test
213
+ self.test_dataloader = partial(self._test_dataloader, shuffle=shuffle_test_loader)
214
+ if predict is not None:
215
+ self.dataset_configs["predict"] = predict
216
+ self.predict_dataloader = self._predict_dataloader
217
+ self.wrap = wrap
218
+
219
+ def prepare_data(self):
220
+ for data_cfg in self.dataset_configs.values():
221
+ instantiate_from_config(data_cfg)
222
+
223
+ def setup(self, stage=None):
224
+ self.datasets = dict(
225
+ (k, instantiate_from_config(self.dataset_configs[k]))
226
+ for k in self.dataset_configs)
227
+ if self.wrap:
228
+ for k in self.datasets:
229
+ self.datasets[k] = WrappedDataset(self.datasets[k])
230
+
231
+ def _train_dataloader(self):
232
+ is_iterable_dataset = isinstance(self.datasets['train'], Txt2ImgIterableBaseDataset)
233
+ if is_iterable_dataset or self.use_worker_init_fn:
234
+ init_fn = worker_init_fn
235
+ else:
236
+ init_fn = None
237
+ return DataLoader(self.datasets["train"], batch_size=self.batch_size,
238
+ num_workers=self.num_workers, shuffle=False if is_iterable_dataset else True,
239
+ worker_init_fn=init_fn, persistent_workers=False)
240
+
241
+ def _val_dataloader(self, shuffle=False):
242
+ if isinstance(self.datasets['validation'], Txt2ImgIterableBaseDataset) or self.use_worker_init_fn:
243
+ init_fn = worker_init_fn
244
+ else:
245
+ init_fn = None
246
+ return DataLoader(self.datasets["validation"],
247
+ batch_size=self.batch_size,
248
+ num_workers=self.num_workers,
249
+ worker_init_fn=init_fn,
250
+ shuffle=shuffle, persistent_workers=False)
251
+
252
+ def _test_dataloader(self, shuffle=False):
253
+ is_iterable_dataset = isinstance(self.datasets['train'], Txt2ImgIterableBaseDataset)
254
+ if is_iterable_dataset or self.use_worker_init_fn:
255
+ init_fn = worker_init_fn
256
+ else:
257
+ init_fn = None
258
+
259
+ # do not shuffle dataloader for iterable dataset
260
+ shuffle = shuffle and (not is_iterable_dataset)
261
+
262
+ return DataLoader(self.datasets["test"], batch_size=self.batch_size,
263
+ num_workers=self.num_workers, worker_init_fn=init_fn, shuffle=shuffle, persistent_workers=False)
264
+
265
+ def _predict_dataloader(self, shuffle=False):
266
+ if isinstance(self.datasets['predict'], Txt2ImgIterableBaseDataset) or self.use_worker_init_fn:
267
+ init_fn = worker_init_fn
268
+ else:
269
+ init_fn = None
270
+ return DataLoader(self.datasets["predict"], batch_size=self.batch_size,
271
+ num_workers=self.num_workers, worker_init_fn=init_fn, persistent_workers=False)
272
+
273
+
274
+ class SetupCallback(Callback):
275
+ def __init__(self, resume, now, logdir, ckptdir, cfgdir, config, lightning_config):
276
+ super().__init__()
277
+ self.resume = resume
278
+ self.now = now
279
+ self.logdir = logdir
280
+ self.ckptdir = ckptdir
281
+ self.cfgdir = cfgdir
282
+ self.config = config
283
+ self.lightning_config = lightning_config
284
+
285
+ def on_keyboard_interrupt(self, trainer, pl_module):
286
+ if trainer.global_rank == 0:
287
+ print("Summoning checkpoint.")
288
+ ckpt_path = os.path.join(self.ckptdir, "last.ckpt")
289
+ trainer.save_checkpoint(ckpt_path)
290
+
291
+ def on_pretrain_routine_start(self, trainer, pl_module):
292
+ if trainer.global_rank == 0:
293
+ # Create logdirs and save configs
294
+ # os.makedirs(self.logdir, exist_ok=True)
295
+ # os.makedirs(self.ckptdir, exist_ok=True)
296
+ # os.makedirs(self.cfgdir, exist_ok=True)
297
+
298
+ if "callbacks" in self.lightning_config:
299
+ if 'metrics_over_trainsteps_checkpoint' in self.lightning_config['callbacks']:
300
+ os.makedirs(os.path.join(self.ckptdir, 'trainstep_checkpoints'), exist_ok=True)
301
+ print("Project config")
302
+ print(OmegaConf.to_yaml(self.config))
303
+ OmegaConf.save(self.config,
304
+ os.path.join(self.cfgdir, "{}-project.yaml".format(self.now)))
305
+
306
+ print("Lightning config")
307
+ print(OmegaConf.to_yaml(self.lightning_config))
308
+ OmegaConf.save(OmegaConf.create({"lightning": self.lightning_config}),
309
+ os.path.join(self.cfgdir, "{}-lightning.yaml".format(self.now)))
310
+
311
+ def get_world_size():
312
+ if not dist.is_available():
313
+ return 1
314
+ if not dist.is_initialized():
315
+ return 1
316
+ return dist.get_world_size()
317
+
318
+ def all_gather(data):
319
+ """
320
+ Run all_gather on arbitrary picklable data (not necessarily tensors)
321
+ Args:
322
+ data: any picklable object
323
+ Returns:
324
+ list[data]: list of data gathered from each rank
325
+ """
326
+ world_size = get_world_size()
327
+ if world_size == 1:
328
+ return [data]
329
+
330
+ # serialized to a Tensor
331
+ origin_size = None
332
+ if not isinstance(data, torch.Tensor):
333
+ buffer = pickle.dumps(data)
334
+ storage = torch.ByteStorage.from_buffer(buffer)
335
+ tensor = torch.ByteTensor(storage).to("cuda")
336
+ else:
337
+ origin_size = data.size()
338
+ tensor = data.reshape(-1)
339
+
340
+ tensor_type = tensor.dtype
341
+
342
+ # obtain Tensor size of each rank
343
+ local_size = torch.LongTensor([tensor.numel()]).to("cuda")
344
+ size_list = [torch.LongTensor([0]).to("cuda") for _ in range(world_size)]
345
+ dist.all_gather(size_list, local_size)
346
+ size_list = [int(size.item()) for size in size_list]
347
+ max_size = max(size_list)
348
+
349
+ # receiving Tensor from all ranks
350
+ # we pad the tensor because torch all_gather does not support
351
+ # gathering tensors of different shapes
352
+ tensor_list = []
353
+ for _ in size_list:
354
+ tensor_list.append(torch.FloatTensor(size=(max_size,)).cuda().to(tensor_type))
355
+ if local_size != max_size:
356
+ padding = torch.FloatTensor(size=(max_size - local_size,)).cuda().to(tensor_type)
357
+ tensor = torch.cat((tensor, padding), dim=0)
358
+ dist.all_gather(tensor_list, tensor)
359
+
360
+ data_list = []
361
+ for size, tensor in zip(size_list, tensor_list):
362
+ if origin_size is None:
363
+ buffer = tensor.cpu().numpy().tobytes()[:size]
364
+ data_list.append(pickle.loads(buffer))
365
+ else:
366
+ buffer = tensor[:size]
367
+ data_list.append(buffer)
368
+
369
+ if origin_size is not None:
370
+ new_shape = [-1] + list(origin_size[1:])
371
+ resized_list = []
372
+ for data in data_list:
373
+ # suppose the difference of tensor size exist in first dimension
374
+ data = data.reshape(new_shape)
375
+ resized_list.append(data)
376
+
377
+ return resized_list
378
+ else:
379
+ return data_list
380
+
381
+ class ImageLogger(Callback):
382
+ def __init__(self, batch_frequency, max_images, clamp=True, increase_log_steps=True,
383
+ rescale=True, disabled=False, log_on_batch_idx=False, log_first_step=False,
384
+ log_images_kwargs=None):
385
+ super().__init__()
386
+ self.rescale = rescale
387
+ self.batch_freq = batch_frequency
388
+ self.max_images = max_images
389
+ self.logger_log_images = {
390
+ pl.loggers.TestTubeLogger: self._testtube,
391
+ }
392
+ self.log_steps = [2 ** n for n in range(6, int(np.log2(self.batch_freq)) + 1)]
393
+ if not increase_log_steps:
394
+ self.log_steps = [self.batch_freq]
395
+ self.clamp = clamp
396
+ self.disabled = disabled
397
+ self.log_on_batch_idx = log_on_batch_idx
398
+ self.log_images_kwargs = log_images_kwargs if log_images_kwargs else {}
399
+ self.log_first_step = log_first_step
400
+
401
+ @rank_zero_only
402
+ def _testtube(self, pl_module, images, batch_idx, split):
403
+ for k in images:
404
+ grid = torchvision.utils.make_grid(images[k])
405
+ grid = (grid + 1.0) / 2.0 # -1,1 -> 0,1; c,h,w
406
+
407
+ tag = f"{split}/{k}"
408
+ pl_module.logger.experiment.add_image(
409
+ tag, grid,
410
+ global_step=pl_module.global_step)
411
+
412
+ @rank_zero_only
413
+ def log_local(self, save_dir, split, images, prompts,
414
+ global_step, current_epoch, batch_idx):
415
+ root = os.path.join(save_dir, "images", split)
416
+ names = {"reals": "before", "inputs": "after", "reconstruction": "before-vq", "samples": "after-gen"}
417
+ # print(root)
418
+ for k in images:
419
+ grid = torchvision.utils.make_grid(images[k], nrow=8)
420
+ if self.rescale:
421
+ grid = (grid + 1.0) / 2.0 # -1,1 -> 0,1; c,h,w
422
+ grid = grid.transpose(0, 1).transpose(1, 2).squeeze(-1)
423
+ grid = grid.numpy()
424
+ grid = (grid * 255).astype(np.uint8)
425
+ filename = "gs-{:06}_e-{:06}_b-{:06}_{}.png".format(
426
+ global_step,
427
+ current_epoch,
428
+ batch_idx,
429
+ names[k])
430
+ path = os.path.join(root, filename)
431
+ os.makedirs(os.path.split(path)[0], exist_ok=True)
432
+ # print(path)
433
+ Image.fromarray(grid).save(path)
434
+
435
+ filename = "gs-{:06}_e-{:06}_b-{:06}_prompt.json".format(
436
+ global_step,
437
+ current_epoch,
438
+ batch_idx)
439
+ path = os.path.join(root, filename)
440
+ with open(path, "w") as f:
441
+ for p in prompts:
442
+ f.write(f"{json.dumps(p)}\n")
443
+
444
+ def log_img(self, pl_module, batch, batch_idx, split="train"):
445
+ check_idx = batch_idx if self.log_on_batch_idx else pl_module.global_step
446
+ if (self.check_frequency(check_idx) and # batch_idx % self.batch_freq == 0
447
+ hasattr(pl_module, "log_images") and
448
+ callable(pl_module.log_images) and
449
+ self.max_images > 0) or (split == "val" and batch_idx == 0):
450
+ logger = type(pl_module.logger)
451
+
452
+ is_train = pl_module.training
453
+ if is_train:
454
+ pl_module.eval()
455
+
456
+ with torch.no_grad():
457
+ images = pl_module.log_images(batch, split=split, **self.log_images_kwargs)
458
+
459
+ prompts = batch["edit"]["c_crossattn"][:self.max_images]
460
+ prompts = [p for ps in all_gather(prompts) for p in ps]
461
+
462
+ for k in images:
463
+ N = min(images[k].shape[0], self.max_images)
464
+ images[k] = images[k][:N]
465
+ images[k] = torch.cat(all_gather(images[k][:N]))
466
+ if isinstance(images[k], torch.Tensor):
467
+ images[k] = images[k].detach().cpu()
468
+ if self.clamp:
469
+ images[k] = torch.clamp(images[k], -1., 1.)
470
+
471
+ self.log_local(pl_module.logger.save_dir, split, images, prompts,
472
+ pl_module.global_step, pl_module.current_epoch, batch_idx)
473
+
474
+ logger_log_images = self.logger_log_images.get(logger, lambda *args, **kwargs: None)
475
+ logger_log_images(pl_module, images, pl_module.global_step, split)
476
+
477
+ if is_train:
478
+ pl_module.train()
479
+
480
+ def check_frequency(self, check_idx):
481
+ if ((check_idx % self.batch_freq) == 0 or (check_idx in self.log_steps)) and (
482
+ check_idx > 0 or self.log_first_step):
483
+ if len(self.log_steps) > 0:
484
+ self.log_steps.pop(0)
485
+ return True
486
+ return False
487
+
488
+ def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
489
+ if not self.disabled and (pl_module.global_step > 0 or self.log_first_step):
490
+ self.log_img(pl_module, batch, batch_idx, split="train")
491
+
492
+ def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
493
+ if not self.disabled and pl_module.global_step > 0:
494
+ self.log_img(pl_module, batch, batch_idx, split="val")
495
+ if hasattr(pl_module, 'calibrate_grad_norm'):
496
+ if (pl_module.calibrate_grad_norm and batch_idx % 25 == 0) and batch_idx > 0:
497
+ self.log_gradients(trainer, pl_module, batch_idx=batch_idx)
498
+
499
+
500
+ class CUDACallback(Callback):
501
+ # see https://github.com/SeanNaren/minGPT/blob/master/mingpt/callback.py
502
+ def on_train_epoch_start(self, trainer, pl_module):
503
+ # Reset the memory use counter
504
+ torch.cuda.reset_peak_memory_stats(trainer.root_gpu)
505
+ torch.cuda.synchronize(trainer.root_gpu)
506
+ self.start_time = time.time()
507
+
508
+ def on_train_epoch_end(self, trainer, pl_module, outputs):
509
+ torch.cuda.synchronize(trainer.root_gpu)
510
+ max_memory = torch.cuda.max_memory_allocated(trainer.root_gpu) / 2 ** 20
511
+ epoch_time = time.time() - self.start_time
512
+
513
+ try:
514
+ max_memory = trainer.training_type_plugin.reduce(max_memory)
515
+ epoch_time = trainer.training_type_plugin.reduce(epoch_time)
516
+
517
+ rank_zero_info(f"Average Epoch time: {epoch_time:.2f} seconds")
518
+ rank_zero_info(f"Average Peak memory {max_memory:.2f}MiB")
519
+ except AttributeError:
520
+ pass
521
+
522
+
523
+ if __name__ == "__main__":
524
+ # custom parser to specify config files, train, test and debug mode,
525
+ # postfix, resume.
526
+ # `--key value` arguments are interpreted as arguments to the trainer.
527
+ # `nested.key=value` arguments are interpreted as config parameters.
528
+ # configs are merged from left-to-right followed by command line parameters.
529
+
530
+ # model:
531
+ # base_learning_rate: float
532
+ # target: path to lightning module
533
+ # params:
534
+ # key: value
535
+ # data:
536
+ # target: main.DataModuleFromConfig
537
+ # params:
538
+ # batch_size: int
539
+ # wrap: bool
540
+ # train:
541
+ # target: path to train dataset
542
+ # params:
543
+ # key: value
544
+ # validation:
545
+ # target: path to validation dataset
546
+ # params:
547
+ # key: value
548
+ # test:
549
+ # target: path to test dataset
550
+ # params:
551
+ # key: value
552
+ # lightning: (optional, has sane defaults and can be specified on cmdline)
553
+ # trainer:
554
+ # additional arguments to trainer
555
+ # logger:
556
+ # logger to instantiate
557
+ # modelcheckpoint:
558
+ # modelcheckpoint to instantiate
559
+ # callbacks:
560
+ # callback1:
561
+ # target: importpath
562
+ # params:
563
+ # key: value
564
+
565
+ now = datetime.datetime.now().strftime("%Y-%m-%dT%H-%M-%S")
566
+
567
+ # add cwd for convenience and to make classes in this file available when
568
+ # running as `python main.py`
569
+ # (in particular `main.DataModuleFromConfig`)
570
+ sys.path.append(os.getcwd())
571
+
572
+ parser = get_parser()
573
+ parser = Trainer.add_argparse_args(parser)
574
+
575
+ opt, unknown = parser.parse_known_args()
576
+
577
+ assert opt.name
578
+ cfg_fname = os.path.split(opt.base[0])[-1]
579
+ cfg_name = os.path.splitext(cfg_fname)[0]
580
+ nowname = f"{cfg_name}_{opt.name}"
581
+ logdir = os.path.join(opt.logdir, nowname)
582
+ ckpt = os.path.join(logdir, "checkpoints", "last.ckpt")
583
+ resume = False
584
+
585
+ if os.path.isfile(ckpt):
586
+ opt.resume_from_checkpoint = ckpt
587
+ base_configs = sorted(glob.glob(os.path.join(logdir, "configs/*.yaml")))
588
+ opt.base = base_configs + opt.base
589
+ _tmp = logdir.split("/")
590
+ nowname = _tmp[-1]
591
+ resume = True
592
+
593
+ ckptdir = os.path.join(logdir, "checkpoints")
594
+ cfgdir = os.path.join(logdir, "configs")
595
+
596
+ os.makedirs(logdir, exist_ok=True)
597
+ os.makedirs(ckptdir, exist_ok=True)
598
+ os.makedirs(cfgdir, exist_ok=True)
599
+
600
+ try:
601
+ # init and save configs
602
+ configs = [OmegaConf.load(cfg) for cfg in opt.base]
603
+ cli = OmegaConf.from_dotlist(unknown)
604
+ config = OmegaConf.merge(*configs, cli)
605
+
606
+ if resume:
607
+ # By default, when finetuning from Stable Diffusion, we load the EMA-only checkpoint to initialize all weights.
608
+ # If resuming InstructPix2Pix from a finetuning checkpoint, instead load both EMA and non-EMA weights.
609
+ config.model.params.load_ema = True
610
+
611
+ lightning_config = config.pop("lightning", OmegaConf.create())
612
+ # merge trainer cli with config
613
+ trainer_config = lightning_config.get("trainer", OmegaConf.create())
614
+ # default to ddp
615
+ trainer_config["accelerator"] = "ddp"
616
+ for k in nondefault_trainer_args(opt):
617
+ trainer_config[k] = getattr(opt, k)
618
+ if not "gpus" in trainer_config:
619
+ del trainer_config["accelerator"]
620
+ cpu = True
621
+ else:
622
+ gpuinfo = trainer_config["gpus"]
623
+ print(f"Running on GPUs {gpuinfo}")
624
+ cpu = False
625
+ trainer_opt = argparse.Namespace(**trainer_config)
626
+ lightning_config.trainer = trainer_config
627
+
628
+ # model
629
+ model = instantiate_from_config(config.model)
630
+
631
+ # trainer and callbacks
632
+ trainer_kwargs = dict()
633
+
634
+ # default logger configs
635
+ default_logger_cfgs = {
636
+ "wandb": {
637
+ "target": "pytorch_lightning.loggers.WandbLogger",
638
+ "params": {
639
+ "name": nowname,
640
+ "save_dir": logdir,
641
+ "id": nowname,
642
+ }
643
+ },
644
+ "testtube": {
645
+ "target": "pytorch_lightning.loggers.TestTubeLogger",
646
+ "params": {
647
+ "name": "testtube",
648
+ "save_dir": logdir,
649
+ }
650
+ },
651
+ }
652
+ default_logger_cfg = default_logger_cfgs["testtube"]
653
+ if "logger" in lightning_config:
654
+ logger_cfg = lightning_config.logger
655
+ else:
656
+ logger_cfg = OmegaConf.create()
657
+ logger_cfg = OmegaConf.merge(default_logger_cfg, logger_cfg)
658
+ trainer_kwargs["logger"] = instantiate_from_config(logger_cfg)
659
+
660
+ # modelcheckpoint - use TrainResult/EvalResult(checkpoint_on=metric) to
661
+ # specify which metric is used to determine best models
662
+ default_modelckpt_cfg = {
663
+ "target": "pytorch_lightning.callbacks.ModelCheckpoint",
664
+ "params": {
665
+ "dirpath": ckptdir,
666
+ "filename": "{epoch:06}",
667
+ "verbose": True,
668
+ "save_last": True,
669
+ }
670
+ }
671
+
672
+ if "modelcheckpoint" in lightning_config:
673
+ modelckpt_cfg = lightning_config.modelcheckpoint
674
+ else:
675
+ modelckpt_cfg = OmegaConf.create()
676
+ modelckpt_cfg = OmegaConf.merge(default_modelckpt_cfg, modelckpt_cfg)
677
+ print(f"Merged modelckpt-cfg: \n{modelckpt_cfg}")
678
+ if version.parse(pl.__version__) < version.parse('1.4.0'):
679
+ trainer_kwargs["checkpoint_callback"] = instantiate_from_config(modelckpt_cfg)
680
+
681
+ # add callback which sets up log directory
682
+ default_callbacks_cfg = {
683
+ "setup_callback": {
684
+ "target": "main.SetupCallback",
685
+ "params": {
686
+ "resume": opt.resume,
687
+ "now": now,
688
+ "logdir": logdir,
689
+ "ckptdir": ckptdir,
690
+ "cfgdir": cfgdir,
691
+ "config": config,
692
+ "lightning_config": lightning_config,
693
+ }
694
+ },
695
+ "image_logger": {
696
+ "target": "main.ImageLogger",
697
+ "params": {
698
+ "batch_frequency": 750,
699
+ "max_images": 4,
700
+ "clamp": True
701
+ }
702
+ },
703
+ "learning_rate_logger": {
704
+ "target": "main.LearningRateMonitor",
705
+ "params": {
706
+ "logging_interval": "step",
707
+ # "log_momentum": True
708
+ }
709
+ },
710
+ "cuda_callback": {
711
+ "target": "main.CUDACallback"
712
+ },
713
+ }
714
+ if version.parse(pl.__version__) >= version.parse('1.4.0'):
715
+ default_callbacks_cfg.update({'checkpoint_callback': modelckpt_cfg})
716
+
717
+ if "callbacks" in lightning_config:
718
+ callbacks_cfg = lightning_config.callbacks
719
+ else:
720
+ callbacks_cfg = OmegaConf.create()
721
+
722
+ print(
723
+ 'Caution: Saving checkpoints every n train steps without deleting. This might require some free space.')
724
+ default_metrics_over_trainsteps_ckpt_dict = {
725
+ 'metrics_over_trainsteps_checkpoint': {
726
+ "target": 'pytorch_lightning.callbacks.ModelCheckpoint',
727
+ 'params': {
728
+ "dirpath": os.path.join(ckptdir, 'trainstep_checkpoints'),
729
+ "filename": "{epoch:06}-{step:09}",
730
+ "verbose": True,
731
+ 'save_top_k': -1,
732
+ 'every_n_train_steps': 1000,
733
+ 'save_weights_only': True
734
+ }
735
+ }
736
+ }
737
+ default_callbacks_cfg.update(default_metrics_over_trainsteps_ckpt_dict)
738
+
739
+ callbacks_cfg = OmegaConf.merge(default_callbacks_cfg, callbacks_cfg)
740
+ if 'ignore_keys_callback' in callbacks_cfg and hasattr(trainer_opt, 'resume_from_checkpoint'):
741
+ callbacks_cfg.ignore_keys_callback.params['ckpt_path'] = trainer_opt.resume_from_checkpoint
742
+ elif 'ignore_keys_callback' in callbacks_cfg:
743
+ del callbacks_cfg['ignore_keys_callback']
744
+
745
+ trainer_kwargs["callbacks"] = [instantiate_from_config(callbacks_cfg[k]) for k in callbacks_cfg]
746
+
747
+ trainer = Trainer.from_argparse_args(trainer_opt, plugins=DDPPlugin(find_unused_parameters=False), **trainer_kwargs)
748
+ trainer.logdir = logdir ###
749
+
750
+ # data
751
+ data = instantiate_from_config(config.data)
752
+ # NOTE according to https://pytorch-lightning.readthedocs.io/en/latest/datamodules.html
753
+ # calling these ourselves should not be necessary but it is.
754
+ # lightning still takes care of proper multiprocessing though
755
+ data.prepare_data()
756
+ data.setup()
757
+ print("#### Data #####")
758
+ for k in data.datasets:
759
+ print(f"{k}, {data.datasets[k].__class__.__name__}, {len(data.datasets[k])}")
760
+
761
+ # configure learning rate
762
+ bs, base_lr = config.data.params.batch_size, config.model.base_learning_rate
763
+ if not cpu:
764
+ ngpu = len(lightning_config.trainer.gpus.strip(",").split(','))
765
+ else:
766
+ ngpu = 1
767
+ if 'accumulate_grad_batches' in lightning_config.trainer:
768
+ accumulate_grad_batches = lightning_config.trainer.accumulate_grad_batches
769
+ else:
770
+ accumulate_grad_batches = 1
771
+ print(f"accumulate_grad_batches = {accumulate_grad_batches}")
772
+ lightning_config.trainer.accumulate_grad_batches = accumulate_grad_batches
773
+ if opt.scale_lr:
774
+ model.learning_rate = accumulate_grad_batches * ngpu * bs * base_lr
775
+ print(
776
+ "Setting learning rate to {:.2e} = {} (accumulate_grad_batches) * {} (num_gpus) * {} (batchsize) * {:.2e} (base_lr)".format(
777
+ model.learning_rate, accumulate_grad_batches, ngpu, bs, base_lr))
778
+ else:
779
+ model.learning_rate = base_lr
780
+ print("++++ NOT USING LR SCALING ++++")
781
+ print(f"Setting learning rate to {model.learning_rate:.2e}")
782
+
783
+
784
+ # allow checkpointing via USR1
785
+ def melk(*args, **kwargs):
786
+ # run all checkpoint hooks
787
+ if trainer.global_rank == 0:
788
+ print("Summoning checkpoint.")
789
+ ckpt_path = os.path.join(ckptdir, "last.ckpt")
790
+ trainer.save_checkpoint(ckpt_path)
791
+
792
+
793
+ def divein(*args, **kwargs):
794
+ if trainer.global_rank == 0:
795
+ import pudb;
796
+ pudb.set_trace()
797
+
798
+
799
+ import signal
800
+
801
+ signal.signal(signal.SIGUSR1, melk)
802
+ signal.signal(signal.SIGUSR2, divein)
803
+
804
+ # run
805
+ if opt.train:
806
+ try:
807
+ trainer.fit(model, data)
808
+ except Exception:
809
+ melk()
810
+ raise
811
+ if not opt.no_test and not trainer.interrupted:
812
+ trainer.test(model, data)
813
+ except Exception:
814
+ if opt.debug and trainer.global_rank == 0:
815
+ try:
816
+ import pudb as debugger
817
+ except ImportError:
818
+ import pdb as debugger
819
+ debugger.post_mortem()
820
+ raise
821
+ finally:
822
+ # move newly created debug project to debug_runs
823
+ if opt.debug and not opt.resume and trainer.global_rank == 0:
824
+ dst, name = os.path.split(logdir)
825
+ dst = os.path.join(dst, "debug_runs", name)
826
+ os.makedirs(os.path.split(dst)[0], exist_ok=True)
827
+ os.rename(logdir, dst)
828
+ if trainer.global_rank == 0:
829
+ print(trainer.profiler.summary())
instruct-pix2pix-BioMedCLIP-concat-newdata/metrics/clip_similarity.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import clip
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ from einops import rearrange
8
+
9
+
10
+ class ClipSimilarity(nn.Module):
11
+ def __init__(self, name: str = "ViT-L/14"):
12
+ super().__init__()
13
+ assert name in ("RN50", "RN101", "RN50x4", "RN50x16", "RN50x64", "ViT-B/32", "ViT-B/16", "ViT-L/14", "ViT-L/14@336px") # fmt: skip
14
+ self.size = {"RN50x4": 288, "RN50x16": 384, "RN50x64": 448, "ViT-L/14@336px": 336}.get(name, 224)
15
+
16
+ self.model, _ = clip.load(name, device="cpu", download_root="./")
17
+ self.model.eval().requires_grad_(False)
18
+
19
+ self.register_buffer("mean", torch.tensor((0.48145466, 0.4578275, 0.40821073)))
20
+ self.register_buffer("std", torch.tensor((0.26862954, 0.26130258, 0.27577711)))
21
+
22
+ def encode_text(self, text: list[str]) -> torch.Tensor:
23
+ text = clip.tokenize(text, truncate=True).to(next(self.parameters()).device)
24
+ text_features = self.model.encode_text(text)
25
+ text_features = text_features / text_features.norm(dim=1, keepdim=True)
26
+ return text_features
27
+
28
+ def encode_image(self, image: torch.Tensor) -> torch.Tensor: # Input images in range [0, 1].
29
+ image = F.interpolate(image.float(), size=self.size, mode="bicubic", align_corners=False)
30
+ image = image - rearrange(self.mean, "c -> 1 c 1 1")
31
+ image = image / rearrange(self.std, "c -> 1 c 1 1")
32
+ image_features = self.model.encode_image(image)
33
+ image_features = image_features / image_features.norm(dim=1, keepdim=True)
34
+ return image_features
35
+
36
+ def forward(
37
+ self, image_0: torch.Tensor, image_1: torch.Tensor, text_0: list[str], text_1: list[str]
38
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
39
+ image_features_0 = self.encode_image(image_0)
40
+ image_features_1 = self.encode_image(image_1)
41
+ text_features_0 = self.encode_text(text_0)
42
+ text_features_1 = self.encode_text(text_1)
43
+ sim_0 = F.cosine_similarity(image_features_0, text_features_0)
44
+ sim_1 = F.cosine_similarity(image_features_1, text_features_1)
45
+ sim_direction = F.cosine_similarity(image_features_1 - image_features_0, text_features_1 - text_features_0)
46
+ sim_image = F.cosine_similarity(image_features_0, image_features_1)
47
+ return sim_0, sim_1, sim_direction, sim_image
instruct-pix2pix-BioMedCLIP-concat-newdata/metrics/compute_metrics.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ import random
5
+ import sys
6
+ from argparse import ArgumentParser
7
+
8
+ import einops
9
+ import k_diffusion as K
10
+ import numpy as np
11
+ import torch
12
+ import torch.nn as nn
13
+ from tqdm.auto import tqdm
14
+ from einops import rearrange
15
+ from omegaconf import OmegaConf
16
+ from PIL import Image, ImageOps
17
+ from torch import autocast
18
+
19
+ import json
20
+ import matplotlib.pyplot as plt
21
+ import seaborn
22
+ from pathlib import Path
23
+
24
+ sys.path.append("./")
25
+
26
+ from clip_similarity import ClipSimilarity
27
+ from edit_dataset import EditDatasetEval
28
+
29
+ sys.path.append("./stable_diffusion")
30
+
31
+ from ldm.util import instantiate_from_config
32
+
33
+
34
+ class CFGDenoiser(nn.Module):
35
+ def __init__(self, model):
36
+ super().__init__()
37
+ self.inner_model = model
38
+
39
+ def forward(self, z, sigma, cond, uncond, text_cfg_scale, image_cfg_scale):
40
+ cfg_z = einops.repeat(z, "1 ... -> n ...", n=3)
41
+ cfg_sigma = einops.repeat(sigma, "1 ... -> n ...", n=3)
42
+ cfg_cond = {
43
+ "c_crossattn": [torch.cat([cond["c_crossattn"][0], uncond["c_crossattn"][0], uncond["c_crossattn"][0]])],
44
+ "c_concat": [torch.cat([cond["c_concat"][0], cond["c_concat"][0], uncond["c_concat"][0]])],
45
+ }
46
+ out_cond, out_img_cond, out_uncond = self.inner_model(cfg_z, cfg_sigma, cond=cfg_cond).chunk(3)
47
+ return out_uncond + text_cfg_scale * (out_cond - out_img_cond) + image_cfg_scale * (out_img_cond - out_uncond)
48
+
49
+
50
+ def load_model_from_config(config, ckpt, vae_ckpt=None, verbose=False):
51
+ print(f"Loading model from {ckpt}")
52
+ pl_sd = torch.load(ckpt, map_location="cpu")
53
+ if "global_step" in pl_sd:
54
+ print(f"Global Step: {pl_sd['global_step']}")
55
+ sd = pl_sd["state_dict"]
56
+ if vae_ckpt is not None:
57
+ print(f"Loading VAE from {vae_ckpt}")
58
+ vae_sd = torch.load(vae_ckpt, map_location="cpu")["state_dict"]
59
+ sd = {
60
+ k: vae_sd[k[len("first_stage_model.") :]] if k.startswith("first_stage_model.") else v
61
+ for k, v in sd.items()
62
+ }
63
+ model = instantiate_from_config(config.model)
64
+ m, u = model.load_state_dict(sd, strict=False)
65
+ if len(m) > 0 and verbose:
66
+ print("missing keys:")
67
+ print(m)
68
+ if len(u) > 0 and verbose:
69
+ print("unexpected keys:")
70
+ print(u)
71
+ return model
72
+
73
+ class ImageEditor(nn.Module):
74
+ def __init__(self, config, ckpt, vae_ckpt=None):
75
+ super().__init__()
76
+
77
+ config = OmegaConf.load(config)
78
+ self.model = load_model_from_config(config, ckpt, vae_ckpt)
79
+ self.model.eval().cuda()
80
+ self.model_wrap = K.external.CompVisDenoiser(self.model)
81
+ self.model_wrap_cfg = CFGDenoiser(self.model_wrap)
82
+ self.null_token = self.model.get_learned_conditioning([""])
83
+
84
+ def forward(
85
+ self,
86
+ image: torch.Tensor,
87
+ edit: str,
88
+ scale_txt: float = 7.5,
89
+ scale_img: float = 1.0,
90
+ steps: int = 100,
91
+ ) -> torch.Tensor:
92
+ assert image.dim() == 3
93
+ assert image.size(1) % 64 == 0
94
+ assert image.size(2) % 64 == 0
95
+ with torch.no_grad(), autocast("cuda"), self.model.ema_scope():
96
+ cond = {
97
+ "c_crossattn": [self.model.get_learned_conditioning([edit])],
98
+ "c_concat": [self.model.encode_first_stage(image[None]).mode()],
99
+ }
100
+ uncond = {
101
+ "c_crossattn": [self.model.get_learned_conditioning([""])],
102
+ "c_concat": [torch.zeros_like(cond["c_concat"][0])],
103
+ }
104
+ extra_args = {
105
+ "uncond": uncond,
106
+ "cond": cond,
107
+ "image_cfg_scale": scale_img,
108
+ "text_cfg_scale": scale_txt,
109
+ }
110
+ sigmas = self.model_wrap.get_sigmas(steps)
111
+ x = torch.randn_like(cond["c_concat"][0]) * sigmas[0]
112
+ x = K.sampling.sample_euler_ancestral(self.model_wrap_cfg, x, sigmas, extra_args=extra_args)
113
+ x = self.model.decode_first_stage(x)[0]
114
+ return x
115
+
116
+
117
+ def compute_metrics(config,
118
+ model_path,
119
+ vae_ckpt,
120
+ data_path,
121
+ output_path,
122
+ scales_img,
123
+ scales_txt,
124
+ num_samples = 5000,
125
+ split = "test",
126
+ steps = 50,
127
+ res = 512,
128
+ seed = 0):
129
+ editor = ImageEditor(config, model_path, vae_ckpt).cuda()
130
+ clip_similarity = ClipSimilarity().cuda()
131
+
132
+
133
+
134
+ outpath = Path(output_path, f"n={num_samples}_p={split}_s={steps}_r={res}_e={seed}.jsonl")
135
+ Path(output_path).mkdir(parents=True, exist_ok=True)
136
+
137
+ for scale_txt in scales_txt:
138
+ for scale_img in scales_img:
139
+ dataset = EditDatasetEval(
140
+ path=data_path,
141
+ split=split,
142
+ res=res
143
+ )
144
+ assert num_samples <= len(dataset)
145
+ print(f'Processing t={scale_txt}, i={scale_img}')
146
+ torch.manual_seed(seed)
147
+ perm = torch.randperm(len(dataset))
148
+ count = 0
149
+ i = 0
150
+
151
+ sim_0_avg = 0
152
+ sim_1_avg = 0
153
+ sim_direction_avg = 0
154
+ sim_image_avg = 0
155
+ count = 0
156
+
157
+ pbar = tqdm(total=num_samples)
158
+ while count < num_samples:
159
+
160
+ idx = perm[i].item()
161
+ sample = dataset[idx]
162
+ i += 1
163
+
164
+ gen = editor(sample["image_0"].cuda(), sample["edit"], scale_txt=scale_txt, scale_img=scale_img, steps=steps)
165
+
166
+ sim_0, sim_1, sim_direction, sim_image = clip_similarity(
167
+ sample["image_0"][None].cuda(), gen[None].cuda(), [sample["input_prompt"]], [sample["output_prompt"]]
168
+ )
169
+ sim_0_avg += sim_0.item()
170
+ sim_1_avg += sim_1.item()
171
+ sim_direction_avg += sim_direction.item()
172
+ sim_image_avg += sim_image.item()
173
+ count += 1
174
+ pbar.update(count)
175
+ pbar.close()
176
+
177
+ sim_0_avg /= count
178
+ sim_1_avg /= count
179
+ sim_direction_avg /= count
180
+ sim_image_avg /= count
181
+
182
+ with open(outpath, "a") as f:
183
+ f.write(f"{json.dumps(dict(sim_0=sim_0_avg, sim_1=sim_1_avg, sim_direction=sim_direction_avg, sim_image=sim_image_avg, num_samples=num_samples, split=split, scale_txt=scale_txt, scale_img=scale_img, steps=steps, res=res, seed=seed))}\n")
184
+ return outpath
185
+
186
+ def plot_metrics(metrics_file, output_path):
187
+
188
+ with open(metrics_file, 'r') as f:
189
+ data = [json.loads(line) for line in f]
190
+
191
+ plt.rcParams.update({'font.size': 11.5})
192
+ seaborn.set_style("darkgrid")
193
+ plt.figure(figsize=(20.5* 0.7, 10.8* 0.7), dpi=200)
194
+
195
+ x = [d["sim_direction"] for d in data]
196
+ y = [d["sim_image"] for d in data]
197
+
198
+ plt.plot(x, y, marker='o', linewidth=2, markersize=4)
199
+
200
+ plt.xlabel("CLIP Text-Image Direction Similarity", labelpad=10)
201
+ plt.ylabel("CLIP Image Similarity", labelpad=10)
202
+
203
+ plt.savefig(Path(output_path) / Path("plot.pdf"), bbox_inches="tight")
204
+
205
+ def main():
206
+ parser = ArgumentParser()
207
+ parser.add_argument("--resolution", default=512, type=int)
208
+ parser.add_argument("--steps", default=100, type=int)
209
+ parser.add_argument("--config", default="configs/generate.yaml", type=str)
210
+ parser.add_argument("--output_path", default="analysis/", type=str)
211
+ parser.add_argument("--ckpt", default="checkpoints/instruct-pix2pix-00-22000.ckpt", type=str)
212
+ parser.add_argument("--dataset", default="data/clip-filtered-dataset/", type=str)
213
+ parser.add_argument("--vae-ckpt", default=None, type=str)
214
+ args = parser.parse_args()
215
+
216
+ scales_img = [1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2]
217
+ scales_txt = [7.5]
218
+
219
+ metrics_file = compute_metrics(
220
+ args.config,
221
+ args.ckpt,
222
+ args.vae_ckpt,
223
+ args.dataset,
224
+ args.output_path,
225
+ scales_img,
226
+ scales_txt,
227
+ steps = args.steps,
228
+ )
229
+
230
+ plot_metrics(metrics_file, args.output_path)
231
+
232
+
233
+
234
+ if __name__ == "__main__":
235
+ main()
instruct-pix2pix-BioMedCLIP-concat-newdata/prompt_app.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from argparse import ArgumentParser
4
+
5
+ import datasets
6
+ import gradio as gr
7
+ import numpy as np
8
+ import openai
9
+
10
+ from dataset_creation.generate_txt_dataset import generate
11
+
12
+
13
+ def main(openai_model: str):
14
+ dataset = datasets.load_dataset("ChristophSchuhmann/improved_aesthetics_6.5plus", split="train")
15
+ captions = dataset[np.random.permutation(len(dataset))]["TEXT"]
16
+ index = 0
17
+
18
+ def click_random():
19
+ nonlocal index
20
+ output = captions[index]
21
+ index = (index + 1) % len(captions)
22
+ return output
23
+
24
+ def click_generate(input: str):
25
+ if input == "":
26
+ raise gr.Error("Input caption is missing!")
27
+ edit_output = generate(openai_model, input)
28
+ if edit_output is None:
29
+ return "Failed :(", "Failed :("
30
+ return edit_output
31
+
32
+ with gr.Blocks(css="footer {visibility: hidden}") as demo:
33
+ txt_input = gr.Textbox(lines=3, label="Input Caption", interactive=True, placeholder="Type image caption here...") # fmt: skip
34
+ txt_edit = gr.Textbox(lines=1, label="GPT-3 Instruction", interactive=False)
35
+ txt_output = gr.Textbox(lines=3, label="GPT3 Edited Caption", interactive=False)
36
+
37
+ with gr.Row():
38
+ clear_btn = gr.Button("Clear")
39
+ random_btn = gr.Button("Random Input")
40
+ generate_btn = gr.Button("Generate Instruction + Edited Caption")
41
+
42
+ clear_btn.click(fn=lambda: ("", "", ""), inputs=[], outputs=[txt_input, txt_edit, txt_output])
43
+ random_btn.click(fn=click_random, inputs=[], outputs=[txt_input])
44
+ generate_btn.click(fn=click_generate, inputs=[txt_input], outputs=[txt_edit, txt_output])
45
+
46
+ demo.launch(share=True)
47
+
48
+
49
+ if __name__ == "__main__":
50
+ parser = ArgumentParser()
51
+ parser.add_argument("--openai-api-key", required=True, type=str)
52
+ parser.add_argument("--openai-model", required=True, type=str)
53
+ args = parser.parse_args()
54
+ openai.api_key = args.openai_api_key
55
+ main(args.openai_model)
instruct-pix2pix-BioMedCLIP-concat-newdata/requirements.txt ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ absl-py==2.3.0
2
+ aiohappyeyeballs==2.6.1
3
+ aiohttp==3.12.12
4
+ aiosignal==1.3.2
5
+ antlr4-python3-runtime==4.8
6
+ async-timeout==5.0.1
7
+ attrs==25.3.0
8
+ blosc2==2.5.1
9
+ Brotli==1.0.9
10
+ cachetools==5.5.2
11
+ certifi==2025.4.26
12
+ charset-normalizer==3.3.2
13
+ contourpy==1.3.0
14
+ cycler==0.12.1
15
+ easydict==1.11
16
+ einops==0.7.0
17
+ filelock==3.17.0
18
+ fonttools==4.58.2
19
+ frozenlist==1.7.0
20
+ fsspec==2025.5.1
21
+ ftfy==6.3.1
22
+ future==1.0.0
23
+ gmpy2==2.2.1
24
+ google-auth==2.40.3
25
+ google-auth-oauthlib==1.2.2
26
+ grpcio==1.73.0
27
+ hf-xet==1.1.3
28
+ huggingface-hub==0.33.0
29
+ idna==3.7
30
+ imageio==2.31.6
31
+ importlib_metadata==8.7.0
32
+ importlib_resources==6.5.2
33
+ Jinja2==3.1.6
34
+ joblib==1.5.1
35
+ kiwisolver==1.4.7
36
+ lazy_loader==0.4
37
+ lightning-utilities==0.9.0
38
+ lpips==0.1.4
39
+ Markdown==3.8
40
+ MarkupSafe==3.0.2
41
+ matplotlib==3.9.4
42
+ mkl_fft==1.3.11
43
+ mkl_random==1.2.8
44
+ mkl-service==2.4.1
45
+ mpmath==1.3.0
46
+ msgpack==1.1.0
47
+ multidict==6.4.4
48
+ ndindex==1.10.0
49
+ networkx==3.2.1
50
+ nibabel==5.2.0
51
+ numpy
52
+ oauthlib==3.2.2
53
+ omegaconf==2.1.1
54
+ open-clip-torch==2.7.0
55
+ opencv-python==4.8.1.78
56
+ packaging==25.0
57
+ pandas==2.1.2
58
+ Pillow==10.0.1
59
+ pip==22.3.1
60
+ propcache==0.3.2
61
+ protobuf==4.23.4
62
+ py-cpuinfo==9.0.0
63
+ pyasn1==0.6.1
64
+ pyasn1_modules==0.4.2
65
+ pyDeprecate==0.3.1
66
+ pyparsing==3.1.1
67
+ PySocks==1.7.1
68
+ python-dateutil==2.9.0.post0
69
+ pytorch-lightning==1.4.2
70
+ pytz==2025.2
71
+ PyYAML==6.0.2
72
+ regex==2024.11.6
73
+ requests==2.32.3
74
+ requests-oauthlib==2.0.0
75
+ rsa==4.9.1
76
+ scikit-image==0.22.0
77
+ scikit-learn==1.3.2
78
+ scipy==1.11.3
79
+ seaborn==0.13.0
80
+ setuptools==78.1.1
81
+ six==1.17.0
82
+ sympy==1.13.3
83
+ tensorboard==2.15.1
84
+ tensorboard-data-server==0.7.2
85
+ tensorboardX==2.6.2.2
86
+ test_tube==0.7.5
87
+ threadpoolctl==3.6.0
88
+ tifffile==2024.8.30
89
+ tokenizers==0.13.3
90
+ tqdm==4.66.1
91
+ transformers==4.29.2
92
+ triton==2.1.0
93
+ typing_extensions==4.12.2
94
+ tzdata==2025.2
95
+ urllib3==2.3.0
96
+ volumentations-3D==1.0.4
97
+ wcwidth==0.2.13
98
+ Werkzeug==3.1.3
99
+ wheel==0.45.1
100
+ yarl==1.20.1
101
+ zipp==3.23.0
instruct-pix2pix-BioMedCLIP-concat-newdata/scripts/download_checkpoints.sh ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
4
+
5
+ mkdir -p $SCRIPT_DIR/../checkpoints
6
+
7
+ curl http://instruct-pix2pix.eecs.berkeley.edu/instruct-pix2pix-00-22000.ckpt -o $SCRIPT_DIR/../checkpoints/instruct-pix2pix-00-22000.ckpt
instruct-pix2pix-BioMedCLIP-concat-newdata/scripts/download_data.sh ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Make data folder relative to script location
4
+ SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
5
+
6
+ mkdir -p $SCRIPT_DIR/../data
7
+
8
+ # Copy text datasets
9
+ wget -q --show-progress http://instruct-pix2pix.eecs.berkeley.edu/gpt-generated-prompts.jsonl -O $SCRIPT_DIR/../data/gpt-generated-prompts.jsonl
10
+ wget -q --show-progress http://instruct-pix2pix.eecs.berkeley.edu/human-written-prompts.jsonl -O $SCRIPT_DIR/../data/human-written-prompts.jsonl
11
+
12
+ # If dataset name isn't provided, exit.
13
+ if [ -z $1 ]
14
+ then
15
+ exit 0
16
+ fi
17
+
18
+ # Copy dataset files
19
+ mkdir $SCRIPT_DIR/../data/$1
20
+ wget -A zip,json -R "index.html*" -q --show-progress -r --no-parent http://instruct-pix2pix.eecs.berkeley.edu/$1/ -nd -P $SCRIPT_DIR/../data/$1/
21
+
22
+ # Unzip to folders
23
+ unzip $SCRIPT_DIR/../data/$1/\*.zip -d $SCRIPT_DIR/../data/$1/
24
+
25
+ # Cleanup
26
+ rm -f $SCRIPT_DIR/../data/$1/*.zip
27
+ rm -f $SCRIPT_DIR/../data/$1/*.html
instruct-pix2pix-BioMedCLIP-concat-newdata/scripts/download_pretrained_sd.sh ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
4
+
5
+ mkdir -p $SCRIPT_DIR/../stable_diffusion/models/ldm/stable-diffusion-v1
6
+ curl -L https://huggingface.co/runwayml/stable-diffusion-v1-5/resolve/main/v1-5-pruned-emaonly.ckpt -o $SCRIPT_DIR/../stable_diffusion/models/ldm/stable-diffusion-v1/v1-5-pruned-emaonly.ckpt
7
+ curl -L https://huggingface.co/stabilityai/sd-vae-ft-mse-original/resolve/main/vae-ft-mse-840000-ema-pruned.ckpt -o $SCRIPT_DIR/../stable_diffusion/models/ldm/stable-diffusion-v1/vae-ft-mse-840000-ema-pruned.ckpt
instruct-pix2pix-BioMedCLIP-concat-newdata/stable_diffusion/LICENSE ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2022 Robin Rombach and Patrick Esser and contributors
2
+
3
+ CreativeML Open RAIL-M
4
+ dated August 22, 2022
5
+
6
+ Section I: PREAMBLE
7
+
8
+ Multimodal generative models are being widely adopted and used, and have the potential to transform the way artists, among other individuals, conceive and benefit from AI or ML technologies as a tool for content creation.
9
+
10
+ Notwithstanding the current and potential benefits that these artifacts can bring to society at large, there are also concerns about potential misuses of them, either due to their technical limitations or ethical considerations.
11
+
12
+ In short, this license strives for both the open and responsible downstream use of the accompanying model. When it comes to the open character, we took inspiration from open source permissive licenses regarding the grant of IP rights. Referring to the downstream responsible use, we added use-based restrictions not permitting the use of the Model in very specific scenarios, in order for the licensor to be able to enforce the license in case potential misuses of the Model may occur. At the same time, we strive to promote open and responsible research on generative models for art and content generation.
13
+
14
+ Even though downstream derivative versions of the model could be released under different licensing terms, the latter will always have to include - at minimum - the same use-based restrictions as the ones in the original license (this license). We believe in the intersection between open and responsible AI development; thus, this License aims to strike a balance between both in order to enable responsible open-science in the field of AI.
15
+
16
+ This License governs the use of the model (and its derivatives) and is informed by the model card associated with the model.
17
+
18
+ NOW THEREFORE, You and Licensor agree as follows:
19
+
20
+ 1. Definitions
21
+
22
+ - "License" means the terms and conditions for use, reproduction, and Distribution as defined in this document.
23
+ - "Data" means a collection of information and/or content extracted from the dataset used with the Model, including to train, pretrain, or otherwise evaluate the Model. The Data is not licensed under this License.
24
+ - "Output" means the results of operating a Model as embodied in informational content resulting therefrom.
25
+ - "Model" means any accompanying machine-learning based assemblies (including checkpoints), consisting of learnt weights, parameters (including optimizer states), corresponding to the model architecture as embodied in the Complementary Material, that have been trained or tuned, in whole or in part on the Data, using the Complementary Material.
26
+ - "Derivatives of the Model" means all modifications to the Model, works based on the Model, or any other model which is created or initialized by transfer of patterns of the weights, parameters, activations or output of the Model, to the other model, in order to cause the other model to perform similarly to the Model, including - but not limited to - distillation methods entailing the use of intermediate data representations or methods based on the generation of synthetic data by the Model for training the other model.
27
+ - "Complementary Material" means the accompanying source code and scripts used to define, run, load, benchmark or evaluate the Model, and used to prepare data for training or evaluation, if any. This includes any accompanying documentation, tutorials, examples, etc, if any.
28
+ - "Distribution" means any transmission, reproduction, publication or other sharing of the Model or Derivatives of the Model to a third party, including providing the Model as a hosted service made available by electronic or other remote means - e.g. API-based or web access.
29
+ - "Licensor" means the copyright owner or entity authorized by the copyright owner that is granting the License, including the persons or entities that may have rights in the Model and/or distributing the Model.
30
+ - "You" (or "Your") means an individual or Legal Entity exercising permissions granted by this License and/or making use of the Model for whichever purpose and in any field of use, including usage of the Model in an end-use application - e.g. chatbot, translator, image generator.
31
+ - "Third Parties" means individuals or legal entities that are not under common control with Licensor or You.
32
+ - "Contribution" means any work of authorship, including the original version of the Model and any modifications or additions to that Model or Derivatives of the Model thereof, that is intentionally submitted to Licensor for inclusion in the Model by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Model, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
33
+ - "Contributor" means Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Model.
34
+
35
+ Section II: INTELLECTUAL PROPERTY RIGHTS
36
+
37
+ Both copyright and patent grants apply to the Model, Derivatives of the Model and Complementary Material. The Model and Derivatives of the Model are subject to additional terms as described in Section III.
38
+
39
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare, publicly display, publicly perform, sublicense, and distribute the Complementary Material, the Model, and Derivatives of the Model.
40
+ 3. Grant of Patent License. Subject to the terms and conditions of this License and where and as applicable, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this paragraph) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Model and the Complementary Material, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Model to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Model and/or Complementary Material or a Contribution incorporated within the Model and/or Complementary Material constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for the Model and/or Work shall terminate as of the date such litigation is asserted or filed.
41
+
42
+ Section III: CONDITIONS OF USAGE, DISTRIBUTION AND REDISTRIBUTION
43
+
44
+ 4. Distribution and Redistribution. You may host for Third Party remote access purposes (e.g. software-as-a-service), reproduce and distribute copies of the Model or Derivatives of the Model thereof in any medium, with or without modifications, provided that You meet the following conditions:
45
+ Use-based restrictions as referenced in paragraph 5 MUST be included as an enforceable provision by You in any type of legal agreement (e.g. a license) governing the use and/or distribution of the Model or Derivatives of the Model, and You shall give notice to subsequent users You Distribute to, that the Model or Derivatives of the Model are subject to paragraph 5. This provision does not apply to the use of Complementary Material.
46
+ You must give any Third Party recipients of the Model or Derivatives of the Model a copy of this License;
47
+ You must cause any modified files to carry prominent notices stating that You changed the files;
48
+ You must retain all copyright, patent, trademark, and attribution notices excluding those notices that do not pertain to any part of the Model, Derivatives of the Model.
49
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions - respecting paragraph 4.a. - for use, reproduction, or Distribution of Your modifications, or for any such Derivatives of the Model as a whole, provided Your use, reproduction, and Distribution of the Model otherwise complies with the conditions stated in this License.
50
+ 5. Use-based restrictions. The restrictions set forth in Attachment A are considered Use-based restrictions. Therefore You cannot use the Model and the Derivatives of the Model for the specified restricted uses. You may use the Model subject to this License, including only for lawful purposes and in accordance with the License. Use may include creating any content with, finetuning, updating, running, training, evaluating and/or reparametrizing the Model. You shall require all of Your users who use the Model or a Derivative of the Model to comply with the terms of this paragraph (paragraph 5).
51
+ 6. The Output You Generate. Except as set forth herein, Licensor claims no rights in the Output You generate using the Model. You are accountable for the Output you generate and its subsequent uses. No use of the output can contravene any provision as stated in the License.
52
+
53
+ Section IV: OTHER PROVISIONS
54
+
55
+ 7. Updates and Runtime Restrictions. To the maximum extent permitted by law, Licensor reserves the right to restrict (remotely or otherwise) usage of the Model in violation of this License, update the Model through electronic means, or modify the Output of the Model based on updates. You shall undertake reasonable efforts to use the latest version of the Model.
56
+ 8. Trademarks and related. Nothing in this License permits You to make use of Licensors’ trademarks, trade names, logos or to otherwise suggest endorsement or misrepresent the relationship between the parties; and any rights not expressly granted herein are reserved by the Licensors.
57
+ 9. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Model and the Complementary Material (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Model, Derivatives of the Model, and the Complementary Material and assume any risks associated with Your exercise of permissions under this License.
58
+ 10. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Model and the Complementary Material (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
59
+ 11. Accepting Warranty or Additional Liability. While redistributing the Model, Derivatives of the Model and the Complementary Material thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
60
+ 12. If any provision of this License is held to be invalid, illegal or unenforceable, the remaining provisions shall be unaffected thereby and remain valid as if such provision had not been set forth herein.
61
+
62
+ END OF TERMS AND CONDITIONS
63
+
64
+
65
+
66
+
67
+ Attachment A
68
+
69
+ Use Restrictions
70
+
71
+ You agree not to use the Model or Derivatives of the Model:
72
+ - In any way that violates any applicable national, federal, state, local or international law or regulation;
73
+ - For the purpose of exploiting, harming or attempting to exploit or harm minors in any way;
74
+ - To generate or disseminate verifiably false information and/or content with the purpose of harming others;
75
+ - To generate or disseminate personal identifiable information that can be used to harm an individual;
76
+ - To defame, disparage or otherwise harass others;
77
+ - For fully automated decision making that adversely impacts an individual’s legal rights or otherwise creates or modifies a binding, enforceable obligation;
78
+ - For any use intended to or which has the effect of discriminating against or harming individuals or groups based on online or offline social behavior or known or predicted personal or personality characteristics;
79
+ - To exploit any of the vulnerabilities of a specific group of persons based on their age, social, physical or mental characteristics, in order to materially distort the behavior of a person pertaining to that group in a manner that causes or is likely to cause that person or another person physical or psychological harm;
80
+ - For any use intended to or which has the effect of discriminating against individuals or groups based on legally protected characteristics or categories;
81
+ - To provide medical advice and medical results interpretation;
82
+ - To generate or disseminate information for the purpose to be used for administration of justice, law enforcement, immigration or asylum processes, such as predicting an individual will commit fraud/crime commitment (e.g. by text profiling, drawing causal relationships between assertions made in documents, indiscriminate and arbitrarily-targeted use).