Add a disclaimer about the fact that we can only run first stage as we don't have A100 available

#3
by multimodalart HF Staff - opened
Files changed (15) hide show
  1. .gitmodules +3 -0
  2. .pre-commit-config.yaml +46 -0
  3. .style.yapf +5 -0
  4. CogView2 +1 -0
  5. LICENSE +21 -0
  6. LICENSE.CogView2 +201 -0
  7. README.md +1 -0
  8. app.py +108 -24
  9. model.py +421 -0
  10. packages.txt +1 -1
  11. patch +51 -0
  12. patch.apex +29 -0
  13. requirements.txt +4 -3
  14. samples.txt +9 -0
  15. style.css +7 -0
.gitmodules ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [submodule "CogView2"]
2
+ path = CogView2
3
+ url = https://github.com/THUDM/CogView2
.pre-commit-config.yaml ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ exclude: ^patch
2
+ repos:
3
+ - repo: https://github.com/pre-commit/pre-commit-hooks
4
+ rev: v4.2.0
5
+ hooks:
6
+ - id: check-executables-have-shebangs
7
+ - id: check-json
8
+ - id: check-merge-conflict
9
+ - id: check-shebang-scripts-are-executable
10
+ - id: check-toml
11
+ - id: check-yaml
12
+ - id: double-quote-string-fixer
13
+ - id: end-of-file-fixer
14
+ - id: mixed-line-ending
15
+ args: ['--fix=lf']
16
+ - id: requirements-txt-fixer
17
+ - id: trailing-whitespace
18
+ - repo: https://github.com/myint/docformatter
19
+ rev: v1.4
20
+ hooks:
21
+ - id: docformatter
22
+ args: ['--in-place']
23
+ - repo: https://github.com/pycqa/isort
24
+ rev: 5.10.1
25
+ hooks:
26
+ - id: isort
27
+ - repo: https://github.com/pre-commit/mirrors-mypy
28
+ rev: v0.812
29
+ hooks:
30
+ - id: mypy
31
+ args: ['--ignore-missing-imports']
32
+ - repo: https://github.com/google/yapf
33
+ rev: v0.32.0
34
+ hooks:
35
+ - id: yapf
36
+ args: ['--parallel', '--in-place']
37
+ - repo: https://github.com/kynan/nbstripout
38
+ rev: 0.5.0
39
+ hooks:
40
+ - id: nbstripout
41
+ args: ['--extra-keys', 'metadata.interpreter metadata.kernelspec cell.metadata.pycharm']
42
+ - repo: https://github.com/nbQA-dev/nbQA
43
+ rev: 1.3.1
44
+ hooks:
45
+ - id: nbqa-isort
46
+ - id: nbqa-yapf
.style.yapf ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ [style]
2
+ based_on_style = pep8
3
+ blank_line_before_nested_class_or_def = false
4
+ spaces_before_comment = 2
5
+ split_before_logical_operator = true
CogView2 ADDED
@@ -0,0 +1 @@
 
 
1
+ Subproject commit 4e55cce981eb94b9c8c1f19ba9f632fd3ee42ba8
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2022 hysts
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
LICENSE.CogView2 ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md CHANGED
@@ -5,6 +5,7 @@ colorFrom: pink
5
  colorTo: red
6
  sdk: gradio
7
  sdk_version: 3.0.19
 
8
  app_file: app.py
9
  pinned: false
10
  ---
 
5
  colorTo: red
6
  sdk: gradio
7
  sdk_version: 3.0.19
8
+ python_version: 3.9.13
9
  app_file: app.py
10
  pinned: false
11
  ---
app.py CHANGED
@@ -1,32 +1,116 @@
1
- import os
 
 
 
2
  import gradio as gr
3
- os.system("pip install torch==1.10.1+cu111 torchvision==0.11.2+cu111 torchaudio==0.10.1 -f https://download.pytorch.org/whl/torch_stable.html")
4
- os.system("git clone https://github.com/Sleepychord/Image-Local-Attention")
5
- os.chdir("Image-Local-Attention")
6
- os.system("python setup.py install")
7
- os.chdir("..")
8
- os.system("git clone https://github.com/NVIDIA/apex")
9
- os.chdir("apex")
10
- os.system('pip install -v --disable-pip-version-check --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./')
11
- os.chdir("..")
12
- os.system("git clone https://github.com/THUDM/CogView2")
13
- os.chdir("CogView2")
14
- os.system("gdown https://drive.google.com/uc?id=1-2nI2TTUOdiQ2WpydGafk_bZIZggQBK4")
15
- os.system("7za x coglm.zip")
16
- os.system("gdown https://drive.google.com/uc?id=1ulfXJFstYZUestvWcQIadKkNNDVbpIdM")
17
 
18
- def inference(text):
19
- with open("input.txt") as f:
20
- lines = f.readlines()
21
- lines[0] = text
22
- with open("input.txt", "w") as f:
23
- f.writelines(lines)
24
- os.system("python cogview2_text2image.py --mode inference --fp16 --input-source input.txt --output-path samples_sat_v0.2 --batch-size 4 --max-inference-batch-size 8 --only-first-stage")
25
- return "/content/CogView2/output.png"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
- gr.Interface(inference,"text","image",title="CogView 2").launch(debug=True,enable_queue=True)
 
 
 
 
 
 
 
28
 
 
 
29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
 
31
 
32
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ from __future__ import annotations
4
+
5
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
+ from model import AppModel
8
+
9
+ DESCRIPTION = '''# <a href="https://github.com/THUDM/CogView2">CogView2</a> (text2image)
10
+
11
+ This Spaces demo runs only one of the two stages the CogView2 codebase has, due to GPU hardware limitations, with that the outputs may not match the original codebase/paper
12
+ This application accepts English or Chinese as input.
13
+ In general, Chinese input produces better results than English input.
14
+ If you check the "Translate to Chinese" checkbox, the app will use the English to Chinese translation results with [this Space](https://huggingface.co/spaces/chinhon/translation_eng2ch) as input.
15
+ But the translation model may mistranslate and the results could be poor.
16
+ So, it is also a good idea to input the translation results from other translation services.
17
+ '''
18
+ NOTES = '''
19
+ - This app is adapted from <a href="https://github.com/hysts/CogView2_demo">https://github.com/hysts/CogView2_demo</a>. It would be recommended to use the repo if you want to run the app yourself.
20
+ '''
21
+ FOOTER = '<img id="visitor-badge" alt="visitor badge" src="https://visitor-badge.glitch.me/badge?page_id=THUDM.CogView2" />'
22
+
23
+
24
+ def set_example_text(example: list) -> list[dict]:
25
+ return [
26
+ gr.Textbox.update(value=example[0]),
27
+ gr.Dropdown.update(value=example[1]),
28
+ ]
29
+
30
+
31
+ def main():
32
+ only_first_stage = True
33
+ max_inference_batch_size = 8
34
+ model = AppModel(max_inference_batch_size, only_first_stage)
35
+
36
+ with gr.Blocks(css='style.css') as demo:
37
+ gr.Markdown(DESCRIPTION)
38
+
39
+ with gr.Row():
40
+ with gr.Column():
41
+ with gr.Group():
42
+ text = gr.Textbox(label='Input Text')
43
+ translate = gr.Checkbox(label='Translate to Chinese',
44
+ value=False)
45
+ style = gr.Dropdown(choices=[
46
+ 'none',
47
+ 'mainbody',
48
+ 'photo',
49
+ 'flat',
50
+ 'comics',
51
+ 'oil',
52
+ 'sketch',
53
+ 'isometric',
54
+ 'chinese',
55
+ 'watercolor',
56
+ ],
57
+ value='mainbody',
58
+ label='Style')
59
+ seed = gr.Slider(0,
60
+ 100000,
61
+ step=1,
62
+ value=1234,
63
+ label='Seed')
64
+ only_first_stage = gr.Checkbox(
65
+ label='Only First Stage',
66
+ value=only_first_stage,
67
+ visible=not only_first_stage)
68
+ num_images = gr.Slider(1,
69
+ 16,
70
+ step=1,
71
+ value=4,
72
+ label='Number of Images')
73
+ run_button = gr.Button('Run')
74
+
75
+ with open('samples.txt') as f:
76
+ samples = [
77
+ line.strip().split('\t') for line in f.readlines()
78
+ ]
79
+ examples = gr.Dataset(components=[text, style],
80
+ samples=samples)
81
 
82
+ with gr.Column():
83
+ with gr.Group():
84
+ translated_text = gr.Textbox(label='Translated Text')
85
+ with gr.Tabs():
86
+ with gr.TabItem('Output (Grid View)'):
87
+ result_grid = gr.Image(show_label=False)
88
+ with gr.TabItem('Output (Gallery)'):
89
+ result_gallery = gr.Gallery(show_label=False)
90
 
91
+ gr.Markdown(NOTES)
92
+ gr.Markdown(FOOTER)
93
 
94
+ run_button.click(fn=model.run_with_translation,
95
+ inputs=[
96
+ text,
97
+ translate,
98
+ style,
99
+ seed,
100
+ only_first_stage,
101
+ num_images,
102
+ ],
103
+ outputs=[
104
+ translated_text,
105
+ result_grid,
106
+ result_gallery,
107
+ ])
108
+ examples.click(fn=set_example_text,
109
+ inputs=examples,
110
+ outputs=examples.components)
111
 
112
+ demo.launch(enable_queue=True)
113
 
114
 
115
+ if __name__ == '__main__':
116
+ main()
model.py ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This code is adapted from https://github.com/THUDM/CogView2/blob/4e55cce981eb94b9c8c1f19ba9f632fd3ee42ba8/cogview2_text2image.py
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import functools
7
+ import logging
8
+ import os
9
+ import pathlib
10
+ import subprocess
11
+ import sys
12
+ import time
13
+ import zipfile
14
+ from typing import Any
15
+
16
+ if os.getenv('SYSTEM') == 'spaces':
17
+ subprocess.run('pip install icetk==0.0.3'.split())
18
+ subprocess.run('pip install SwissArmyTransformer==0.2.4'.split())
19
+ subprocess.run(
20
+ 'pip install git+https://github.com/Sleepychord/Image-Local-Attention@43fee31'
21
+ .split())
22
+ #subprocess.run('git clone https://github.com/NVIDIA/apex'.split())
23
+ #subprocess.run('git checkout 1403c21'.split(), cwd='apex')
24
+ #with open('patch.apex') as f:
25
+ # subprocess.run('patch -p1'.split(), cwd='apex', stdin=f)
26
+ #subprocess.run(
27
+ # 'pip install -v --disable-pip-version-check --no-cache-dir --global-option --cpp_ext --global-option --cuda_ext ./'
28
+ # .split(),
29
+ # cwd='apex')
30
+ #subprocess.run('rm -rf apex'.split())
31
+ with open('patch') as f:
32
+ subprocess.run('patch -p1'.split(), cwd='CogView2', stdin=f)
33
+
34
+ from huggingface_hub import hf_hub_download
35
+
36
+ def download_and_extract_icetk_models() -> None:
37
+ icetk_model_dir = pathlib.Path('/home/user/.icetk_models')
38
+ icetk_model_dir.mkdir()
39
+ path = hf_hub_download('THUDM/icetk',
40
+ 'models.zip',
41
+ use_auth_token=os.getenv('HF_TOKEN'))
42
+ with zipfile.ZipFile(path) as f:
43
+ f.extractall(path=icetk_model_dir.as_posix())
44
+
45
+ def download_and_extract_cogview2_models(name: str) -> None:
46
+ path = hf_hub_download('THUDM/CogView2',
47
+ name,
48
+ use_auth_token=os.getenv('HF_TOKEN'))
49
+ with zipfile.ZipFile(path) as f:
50
+ f.extractall()
51
+ os.remove(path)
52
+
53
+ download_and_extract_icetk_models()
54
+ names = [
55
+ 'coglm.zip',
56
+ 'cogview2-dsr.zip',
57
+ #'cogview2-itersr.zip',
58
+ ]
59
+ for name in names:
60
+ download_and_extract_cogview2_models(name)
61
+
62
+ os.environ['SAT_HOME'] = '/home/user/app/sharefs/cogview-new'
63
+
64
+ import gradio as gr
65
+ import numpy as np
66
+ import torch
67
+ from icetk import icetk as tokenizer
68
+ from SwissArmyTransformer import get_args
69
+ from SwissArmyTransformer.arguments import set_random_seed
70
+ from SwissArmyTransformer.generation.autoregressive_sampling import \
71
+ filling_sequence
72
+ from SwissArmyTransformer.model import CachedAutoregressiveModel
73
+
74
+ app_dir = pathlib.Path(__file__).parent
75
+ submodule_dir = app_dir / 'CogView2'
76
+ sys.path.insert(0, submodule_dir.as_posix())
77
+
78
+ from coglm_strategy import CoglmStrategy
79
+ from sr_pipeline import SRGroup
80
+
81
+ formatter = logging.Formatter(
82
+ '[%(asctime)s] %(name)s %(levelname)s: %(message)s',
83
+ datefmt='%Y-%m-%d %H:%M:%S')
84
+ stream_handler = logging.StreamHandler(stream=sys.stdout)
85
+ stream_handler.setLevel(logging.INFO)
86
+ stream_handler.setFormatter(formatter)
87
+ logger = logging.getLogger(__name__)
88
+ logger.setLevel(logging.INFO)
89
+ logger.propagate = False
90
+ logger.addHandler(stream_handler)
91
+
92
+ tokenizer.add_special_tokens(
93
+ ['<start_of_image>', '<start_of_english>', '<start_of_chinese>'])
94
+
95
+
96
+ def get_masks_and_position_ids_coglm(
97
+ seq: torch.Tensor, context_length: int
98
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
99
+ tokens = seq.unsqueeze(0)
100
+
101
+ attention_mask = torch.ones((1, len(seq), len(seq)), device=tokens.device)
102
+ attention_mask.tril_()
103
+ attention_mask[..., :context_length] = 1
104
+ attention_mask.unsqueeze_(1)
105
+
106
+ position_ids = torch.zeros(len(seq),
107
+ device=tokens.device,
108
+ dtype=torch.long)
109
+ torch.arange(0, context_length, out=position_ids[:context_length])
110
+ torch.arange(512,
111
+ 512 + len(seq) - context_length,
112
+ out=position_ids[context_length:])
113
+
114
+ position_ids = position_ids.unsqueeze(0)
115
+ return tokens, attention_mask, position_ids
116
+
117
+
118
+ class InferenceModel(CachedAutoregressiveModel):
119
+ def final_forward(self, logits, **kwargs):
120
+ logits_parallel = logits
121
+ logits_parallel = torch.nn.functional.linear(
122
+ logits_parallel.float(),
123
+ self.transformer.word_embeddings.weight[:20000].float())
124
+ return logits_parallel
125
+
126
+
127
+ def get_recipe(name: str) -> dict[str, Any]:
128
+ r = {
129
+ 'attn_plus': 1.4,
130
+ 'temp_all_gen': 1.15,
131
+ 'topk_gen': 16,
132
+ 'temp_cluster_gen': 1.,
133
+ 'temp_all_dsr': 1.5,
134
+ 'topk_dsr': 100,
135
+ 'temp_cluster_dsr': 0.89,
136
+ 'temp_all_itersr': 1.3,
137
+ 'topk_itersr': 16,
138
+ 'query_template': '{}<start_of_image>',
139
+ }
140
+ if name == 'none':
141
+ pass
142
+ elif name == 'mainbody':
143
+ r['query_template'] = '{} 高清摄影 隔绝<start_of_image>'
144
+
145
+ elif name == 'photo':
146
+ r['query_template'] = '{} 高清摄影<start_of_image>'
147
+
148
+ elif name == 'flat':
149
+ r['query_template'] = '{} 平面风格<start_of_image>'
150
+ # r['attn_plus'] = 1.8
151
+ # r['temp_cluster_gen'] = 0.75
152
+ r['temp_all_gen'] = 1.1
153
+ r['topk_dsr'] = 5
154
+ r['temp_cluster_dsr'] = 0.4
155
+
156
+ r['temp_all_itersr'] = 1
157
+ r['topk_itersr'] = 5
158
+ elif name == 'comics':
159
+ r['query_template'] = '{} 漫画 隔绝<start_of_image>'
160
+ r['topk_dsr'] = 5
161
+ r['temp_cluster_dsr'] = 0.4
162
+ r['temp_all_gen'] = 1.1
163
+ r['temp_all_itersr'] = 1
164
+ r['topk_itersr'] = 5
165
+ elif name == 'oil':
166
+ r['query_template'] = '{} 油画风格<start_of_image>'
167
+ pass
168
+ elif name == 'sketch':
169
+ r['query_template'] = '{} 素描风格<start_of_image>'
170
+ r['temp_all_gen'] = 1.1
171
+ elif name == 'isometric':
172
+ r['query_template'] = '{} 等距矢量图<start_of_image>'
173
+ r['temp_all_gen'] = 1.1
174
+ elif name == 'chinese':
175
+ r['query_template'] = '{} 水墨国画<start_of_image>'
176
+ r['temp_all_gen'] = 1.12
177
+ elif name == 'watercolor':
178
+ r['query_template'] = '{} 水彩画风格<start_of_image>'
179
+ return r
180
+
181
+
182
+ def get_default_args() -> argparse.Namespace:
183
+ arg_list = ['--mode', 'inference', '--fp16']
184
+ args = get_args(arg_list)
185
+ known = argparse.Namespace(img_size=160,
186
+ only_first_stage=False,
187
+ inverse_prompt=False,
188
+ style='mainbody')
189
+ args = argparse.Namespace(**vars(args), **vars(known),
190
+ **get_recipe(known.style))
191
+ return args
192
+
193
+
194
+ class Model:
195
+ def __init__(self,
196
+ max_inference_batch_size: int,
197
+ only_first_stage: bool = False):
198
+ self.args = get_default_args()
199
+ self.args.only_first_stage = only_first_stage
200
+ self.args.max_inference_batch_size = max_inference_batch_size
201
+
202
+ self.model, self.args = self.load_model()
203
+ self.strategy = self.load_strategy()
204
+ self.srg = self.load_srg()
205
+
206
+ self.query_template = self.args.query_template
207
+ self.style = self.args.style
208
+ self.device = torch.device(self.args.device)
209
+ self.fp16 = self.args.fp16
210
+ self.max_batch_size = self.args.max_inference_batch_size
211
+ self.only_first_stage = self.args.only_first_stage
212
+
213
+ def load_model(self) -> tuple[InferenceModel, argparse.Namespace]:
214
+ logger.info('--- load_model ---')
215
+ start = time.perf_counter()
216
+
217
+ model, args = InferenceModel.from_pretrained(self.args, 'coglm')
218
+
219
+ elapsed = time.perf_counter() - start
220
+ logger.info(f'--- done ({elapsed=:.3f}) ---')
221
+ return model, args
222
+
223
+ def load_strategy(self) -> CoglmStrategy:
224
+ logger.info('--- load_strategy ---')
225
+ start = time.perf_counter()
226
+
227
+ invalid_slices = [slice(tokenizer.num_image_tokens, None)]
228
+ strategy = CoglmStrategy(invalid_slices,
229
+ temperature=self.args.temp_all_gen,
230
+ top_k=self.args.topk_gen,
231
+ top_k_cluster=self.args.temp_cluster_gen)
232
+
233
+ elapsed = time.perf_counter() - start
234
+ logger.info(f'--- done ({elapsed=:.3f}) ---')
235
+ return strategy
236
+
237
+ def load_srg(self) -> SRGroup:
238
+ logger.info('--- load_srg ---')
239
+ start = time.perf_counter()
240
+
241
+ srg = None if self.args.only_first_stage else SRGroup(self.args)
242
+
243
+ elapsed = time.perf_counter() - start
244
+ logger.info(f'--- done ({elapsed=:.3f}) ---')
245
+ return srg
246
+
247
+ def update_style(self, style: str) -> None:
248
+ if style == self.style:
249
+ return
250
+ logger.info('--- update_style ---')
251
+ start = time.perf_counter()
252
+
253
+ self.style = style
254
+ self.args = argparse.Namespace(**(vars(self.args) | get_recipe(style)))
255
+ self.query_template = self.args.query_template
256
+ logger.debug(f'{self.query_template=}')
257
+
258
+ self.strategy.temperature = self.args.temp_all_gen
259
+
260
+ if self.srg is not None:
261
+ self.srg.dsr.strategy.temperature = self.args.temp_all_dsr
262
+ self.srg.dsr.strategy.topk = self.args.topk_dsr
263
+ self.srg.dsr.strategy.temperature2 = self.args.temp_cluster_dsr
264
+
265
+ self.srg.itersr.strategy.temperature = self.args.temp_all_itersr
266
+ self.srg.itersr.strategy.topk = self.args.topk_itersr
267
+
268
+ elapsed = time.perf_counter() - start
269
+ logger.info(f'--- done ({elapsed=:.3f}) ---')
270
+
271
+ def run(self, text: str, style: str, seed: int, only_first_stage: bool,
272
+ num: int) -> list[np.ndarray] | None:
273
+ logger.info('==================== run ====================')
274
+ start = time.perf_counter()
275
+
276
+ self.update_style(style)
277
+ set_random_seed(seed)
278
+ seq, txt_len = self.preprocess_text(text)
279
+ if seq is None:
280
+ return None
281
+ self.only_first_stage = only_first_stage
282
+ tokens = self.generate_tokens(seq, txt_len, num)
283
+ res = self.generate_images(seq, txt_len, tokens)
284
+
285
+ elapsed = time.perf_counter() - start
286
+ logger.info(f'Elapsed: {elapsed}')
287
+ logger.info('==================== done ====================')
288
+ return res
289
+
290
+ @torch.inference_mode()
291
+ def preprocess_text(
292
+ self, text: str) -> tuple[torch.Tensor, int] | tuple[None, None]:
293
+ logger.info('--- preprocess_text ---')
294
+ start = time.perf_counter()
295
+
296
+ text = self.query_template.format(text)
297
+ logger.debug(f'{text=}')
298
+ seq = tokenizer.encode(text)
299
+ logger.info(f'{len(seq)=}')
300
+ if len(seq) > 110:
301
+ logger.info('The input text is too long.')
302
+ return None, None
303
+ txt_len = len(seq) - 1
304
+ seq = torch.tensor(seq + [-1] * 400, device=self.device)
305
+
306
+ elapsed = time.perf_counter() - start
307
+ logger.info(f'--- done ({elapsed=:.3f}) ---')
308
+ return seq, txt_len
309
+
310
+ @torch.inference_mode()
311
+ def generate_tokens(self,
312
+ seq: torch.Tensor,
313
+ txt_len: int,
314
+ num: int = 8) -> torch.Tensor:
315
+ logger.info('--- generate_tokens ---')
316
+ start = time.perf_counter()
317
+
318
+ # calibrate text length
319
+ log_attention_weights = torch.zeros(
320
+ len(seq),
321
+ len(seq),
322
+ device=self.device,
323
+ dtype=torch.half if self.fp16 else torch.float32)
324
+ log_attention_weights[:, :txt_len] = self.args.attn_plus
325
+ get_func = functools.partial(get_masks_and_position_ids_coglm,
326
+ context_length=txt_len)
327
+
328
+ output_list = []
329
+ remaining = num
330
+ for _ in range((num + self.max_batch_size - 1) // self.max_batch_size):
331
+ self.strategy.start_pos = txt_len + 1
332
+ coarse_samples = filling_sequence(
333
+ self.model,
334
+ seq.clone(),
335
+ batch_size=min(remaining, self.max_batch_size),
336
+ strategy=self.strategy,
337
+ log_attention_weights=log_attention_weights,
338
+ get_masks_and_position_ids=get_func)[0]
339
+ output_list.append(coarse_samples)
340
+ remaining -= self.max_batch_size
341
+ output_tokens = torch.cat(output_list, dim=0)
342
+ logger.debug(f'{output_tokens.shape=}')
343
+
344
+ elapsed = time.perf_counter() - start
345
+ logger.info(f'--- done ({elapsed=:.3f}) ---')
346
+ return output_tokens
347
+
348
+ @staticmethod
349
+ def postprocess(tensor: torch.Tensor) -> np.ndarray:
350
+ return tensor.cpu().mul(255).add_(0.5).clamp_(0, 255).permute(
351
+ 1, 2, 0).to(torch.uint8).numpy()
352
+
353
+ @torch.inference_mode()
354
+ def generate_images(self, seq: torch.Tensor, txt_len: int,
355
+ tokens: torch.Tensor) -> list[np.ndarray]:
356
+ logger.info('--- generate_images ---')
357
+ start = time.perf_counter()
358
+
359
+ logger.debug(f'{self.only_first_stage=}')
360
+ res = []
361
+ if self.only_first_stage:
362
+ for i in range(len(tokens)):
363
+ seq = tokens[i]
364
+ decoded_img = tokenizer.decode(image_ids=seq[-400:])
365
+ decoded_img = torch.nn.functional.interpolate(decoded_img,
366
+ size=(480, 480))
367
+ decoded_img = self.postprocess(decoded_img[0])
368
+ res.append(decoded_img) # only the last image (target)
369
+ else: # sr
370
+ iter_tokens = self.srg.sr_base(tokens[:, -400:], seq[:txt_len])
371
+ for seq in iter_tokens:
372
+ decoded_img = tokenizer.decode(image_ids=seq[-3600:])
373
+ decoded_img = torch.nn.functional.interpolate(decoded_img,
374
+ size=(480, 480))
375
+ decoded_img = self.postprocess(decoded_img[0])
376
+ res.append(decoded_img) # only the last image (target)
377
+
378
+ elapsed = time.perf_counter() - start
379
+ logger.info(f'--- done ({elapsed=:.3f}) ---')
380
+ return res
381
+
382
+
383
+ class AppModel(Model):
384
+ def __init__(self, max_inference_batch_size: int, only_first_stage: bool):
385
+ super().__init__(max_inference_batch_size, only_first_stage)
386
+ self.translator = gr.Interface.load(
387
+ 'spaces/chinhon/translation_eng2ch')
388
+
389
+ def make_grid(self, images: list[np.ndarray] | None) -> np.ndarray | None:
390
+ if images is None or len(images) == 0:
391
+ return None
392
+ ncols = 1
393
+ while True:
394
+ if ncols**2 >= len(images):
395
+ break
396
+ ncols += 1
397
+ nrows = (len(images) + ncols - 1) // ncols
398
+ h, w = images[0].shape[:2]
399
+ grid = np.zeros((h * nrows, w * ncols, 3), dtype=np.uint8)
400
+ for i in range(nrows):
401
+ for j in range(ncols):
402
+ index = ncols * i + j
403
+ if index >= len(images):
404
+ break
405
+ grid[h * i:h * (i + 1), w * j:w * (j + 1)] = images[index]
406
+ return grid
407
+
408
+ def run_with_translation(
409
+ self, text: str, translate: bool, style: str, seed: int,
410
+ only_first_stage: bool, num: int
411
+ ) -> tuple[str | None, np.ndarray | None, list[np.ndarray] | None]:
412
+ logger.info(
413
+ f'{text=}, {translate=}, {style=}, {seed=}, {only_first_stage=}, {num=}'
414
+ )
415
+ if translate:
416
+ text = translated_text = self.translator(text)
417
+ else:
418
+ translated_text = None
419
+ results = self.run(text, style, seed, only_first_stage, num)
420
+ grid_image = self.make_grid(results)
421
+ return translated_text, grid_image, results
packages.txt CHANGED
@@ -1 +1 @@
1
- p7zip-full
 
1
+ ninja-build
patch ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/coglm_strategy.py b/coglm_strategy.py
2
+ index cba87ce..40e4ece 100755
3
+ --- a/coglm_strategy.py
4
+ +++ b/coglm_strategy.py
5
+ @@ -8,6 +8,7 @@
6
+
7
+ # here put the import lib
8
+ import os
9
+ +import pathlib
10
+ import sys
11
+ import math
12
+ import random
13
+ @@ -57,7 +58,8 @@ class CoglmStrategy:
14
+ self._is_done = False
15
+ self.outlier_count_down = 5
16
+ self.vis_list = [[]for i in range(16)]
17
+ - self.cluster_labels = torch.tensor(np.load('cluster_label.npy'), device='cuda', dtype=torch.long)
18
+ + cluster_label_path = pathlib.Path(__file__).parent / 'cluster_label.npy'
19
+ + self.cluster_labels = torch.tensor(np.load(cluster_label_path), device='cuda', dtype=torch.long)
20
+ self.top_k_cluster = top_k_cluster
21
+
22
+ @property
23
+ @@ -91,4 +93,4 @@ class CoglmStrategy:
24
+
25
+ def finalize(self, tokens, mems):
26
+ self._is_done = False
27
+ - return tokens, mems
28
+
29
+ + return tokens, mems
30
+ diff --git a/sr_pipeline/dsr_sampling.py b/sr_pipeline/dsr_sampling.py
31
+ index a0d0298..f721573 100755
32
+ --- a/sr_pipeline/dsr_sampling.py
33
+ +++ b/sr_pipeline/dsr_sampling.py
34
+ @@ -8,6 +8,7 @@
35
+
36
+ # here put the import lib
37
+ import os
38
+ +import pathlib
39
+ import sys
40
+ import math
41
+ import random
42
+ @@ -27,7 +28,8 @@ class IterativeEntfilterStrategy:
43
+ self.invalid_slices = invalid_slices
44
+ self.temperature = temperature
45
+ self.topk = topk
46
+ - self.cluster_labels = torch.tensor(np.load('cluster_label.npy'), device='cuda', dtype=torch.long)
47
+ + cluster_label_path = pathlib.Path(__file__).parents[1] / 'cluster_label.npy'
48
+ + self.cluster_labels = torch.tensor(np.load(cluster_label_path), device='cuda', dtype=torch.long)
49
+ self.temperature2 = temperature2
50
+
51
+
patch.apex ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/setup.py b/setup.py
2
+ index 5f68ecf..b4d44a8 100644
3
+ --- a/setup.py
4
+ +++ b/setup.py
5
+ @@ -30,15 +30,15 @@ def check_cuda_torch_binary_vs_bare_metal(cuda_dir):
6
+ print("\nCompiling cuda extensions with")
7
+ print(raw_output + "from " + cuda_dir + "/bin\n")
8
+
9
+ - if (bare_metal_major != torch_binary_major) or (bare_metal_minor != torch_binary_minor):
10
+ - raise RuntimeError(
11
+ - "Cuda extensions are being compiled with a version of Cuda that does "
12
+ - "not match the version used to compile Pytorch binaries. "
13
+ - "Pytorch binaries were compiled with Cuda {}.\n".format(torch.version.cuda)
14
+ - + "In some cases, a minor-version mismatch will not cause later errors: "
15
+ - "https://github.com/NVIDIA/apex/pull/323#discussion_r287021798. "
16
+ - "You can try commenting out this check (at your own risk)."
17
+ - )
18
+ +# if (bare_metal_major != torch_binary_major) or (bare_metal_minor != torch_binary_minor):
19
+ +# raise RuntimeError(
20
+ +# "Cuda extensions are being compiled with a version of Cuda that does "
21
+ +# "not match the version used to compile Pytorch binaries. "
22
+ +# "Pytorch binaries were compiled with Cuda {}.\n".format(torch.version.cuda)
23
+ +# + "In some cases, a minor-version mismatch will not cause later errors: "
24
+ +# "https://github.com/NVIDIA/apex/pull/323#discussion_r287021798. "
25
+ +# "You can try commenting out this check (at your own risk)."
26
+ +# )
27
+
28
+
29
+ def raise_if_cuda_home_none(global_option: str) -> None:
requirements.txt CHANGED
@@ -1,3 +1,4 @@
1
- SwissArmyTransformer>=0.2
2
- icetk
3
- gdown
 
 
1
+ --extra-index-url https://download.pytorch.org/whl/cu113
2
+ numpy==1.22.4
3
+ torch==1.11.0+cu113
4
+ torchvision==0.12.0+cu113
samples.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ A lion teacher wearing a suit is in front of a blackboard. mainbody
2
+ A robot is riding under the blue and cloudy sky. mainbody
3
+ A lion man is typing in the office. mainbody
4
+ A pirate captain with a skull. mainbody
5
+ Earth in the eye. mainbody
6
+ A magnificent church. sketch
7
+ Mount Fuji, cherry blossom and Akita dog. oil
8
+ A tiger with angel's wings. mainbody
9
+ A fox is sitting on the books. mainbody
style.css ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ h1 {
2
+ text-align: center;
3
+ }
4
+ img#visitor-badge {
5
+ display: block;
6
+ margin: auto;
7
+ }