hysts HF staff commited on
Commit
9a5dc44
1 Parent(s): dc7f251
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ gradio_cached_examples
.gitmodules ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [submodule "multires_textual_inversion"]
2
+ path = multires_textual_inversion
3
+ url = https://github.com/giannisdaras/multires_textual_inversion
.pre-commit-config.yaml ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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']
.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
app.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+
7
+ import gradio as gr
8
+
9
+ from model import Model
10
+
11
+ TITLE = '# Multiresolution Textual Inversion'
12
+ DESCRIPTION = 'An unofficial demo for [https://github.com/giannisdaras/multires_textual_inversion](https://github.com/giannisdaras/multires_textual_inversion).'
13
+
14
+ DETAILS = '''
15
+ - To run the Semi Resolution-Dependent sampler, use the format: `<jane(number)>`.
16
+ - To run the Fully Resolution-Dependent sampler, use the format: `<jane[number]>`.
17
+ - To run the Fixed Resolution sampler, use the format: `<jane|number|>`.
18
+
19
+ For this demo, only `<jane>`, `<gta5-artwork>` and `<cat-toy>` are available.
20
+ Also, `number` should be an integer in [0, 9].
21
+ '''
22
+ FOOTER = '<img id="visitor-badge" src="https://visitor-badge.glitch.me/badge?page_id=hysts.multires-textual-inversion" alt="visitor badge" />'
23
+
24
+ CACHE_EXAMPLES = os.getenv('SYSTEM') == 'spaces'
25
+
26
+
27
+ def main():
28
+ model = Model()
29
+
30
+ with gr.Blocks(css='style.css') as demo:
31
+ gr.Markdown(TITLE)
32
+ gr.Markdown(DESCRIPTION)
33
+
34
+ with gr.Row():
35
+ with gr.Group():
36
+ with gr.Row():
37
+ prompt = gr.Textbox(label='Prompt')
38
+ with gr.Row():
39
+ num_images = gr.Slider(1,
40
+ 9,
41
+ value=1,
42
+ step=1,
43
+ label='Number of images')
44
+ with gr.Row():
45
+ num_steps = gr.Slider(1,
46
+ 50,
47
+ value=10,
48
+ step=1,
49
+ label='Number of inference steps')
50
+ with gr.Row():
51
+ seed = gr.Slider(0,
52
+ 100000,
53
+ value=100,
54
+ step=1,
55
+ label='Seed')
56
+ with gr.Row():
57
+ run_button = gr.Button('Run')
58
+
59
+ with gr.Column():
60
+ result = gr.Gallery(label='Result')
61
+
62
+ with gr.Row():
63
+ with gr.Group():
64
+ fn = lambda x: model.run(x, 2, 10, 100)
65
+ with gr.Row():
66
+ gr.Examples(
67
+ label='Examples 1',
68
+ examples=[
69
+ ['an image of <gta5-artwork(0)>'],
70
+ ['an image of <jane(0)>'],
71
+ ['an image of <jane(3)>'],
72
+ ['an image of <cat-toy(0)>'],
73
+ ],
74
+ inputs=[prompt],
75
+ outputs=[result],
76
+ fn=fn,
77
+ cache_examples=CACHE_EXAMPLES,
78
+ )
79
+ with gr.Row():
80
+ gr.Examples(
81
+ label='Examples 2',
82
+ examples=[
83
+ [
84
+ 'an image of a cat in the style of <gta5-artwork(0)>'
85
+ ],
86
+ ['a painting of a dog in the style of <jane(0)>'],
87
+ ['a painting of a dog in the style of <jane(5)>'],
88
+ [
89
+ 'a painting of a <cat-toy(0)> in the style of <jane(3)>'
90
+ ],
91
+ ],
92
+ inputs=[prompt],
93
+ outputs=[result],
94
+ fn=fn,
95
+ cache_examples=CACHE_EXAMPLES,
96
+ )
97
+ with gr.Row():
98
+ gr.Examples(
99
+ label='Examples 3',
100
+ examples=[
101
+ ['an image of <jane[0]>'],
102
+ ['an image of <jane|0|>'],
103
+ ['an image of <jane|3|>'],
104
+ ],
105
+ inputs=[prompt],
106
+ outputs=[result],
107
+ fn=fn,
108
+ cache_examples=CACHE_EXAMPLES,
109
+ )
110
+
111
+ prompt.submit(
112
+ fn=model.run,
113
+ inputs=[prompt, num_images, num_steps, seed],
114
+ outputs=[result],
115
+ )
116
+ run_button.click(
117
+ fn=model.run,
118
+ inputs=[prompt, num_images, num_steps, seed],
119
+ outputs=[result],
120
+ )
121
+
122
+ with gr.Accordion('About available prompts', open=False):
123
+ gr.Markdown(DETAILS)
124
+ gr.Markdown(FOOTER)
125
+ demo.launch(enable_queue=True, share=False)
126
+
127
+
128
+ if __name__ == '__main__':
129
+ main()
model.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import subprocess
5
+ import sys
6
+
7
+ import PIL.Image
8
+ import torch
9
+ from diffusers import DPMSolverMultistepScheduler
10
+
11
+ if os.getenv('SYSTEM') == 'spaces':
12
+ with open('patch') as f:
13
+ subprocess.run('patch -p1'.split(),
14
+ cwd='multires_textual_inversion',
15
+ stdin=f)
16
+
17
+ sys.path.insert(0, 'multires_textual_inversion')
18
+
19
+ from pipeline import MultiResPipeline, load_learned_concepts
20
+
21
+ HF_TOKEN = os.environ.get('HF_TOKEN')
22
+
23
+
24
+ class Model:
25
+ def __init__(self):
26
+ self.device = torch.device(
27
+ 'cuda:0' if torch.cuda.is_available() else 'cpu')
28
+ model_id = 'runwayml/stable-diffusion-v1-5'
29
+ if self.device.type == 'cpu':
30
+ pipe = MultiResPipeline.from_pretrained(model_id,
31
+ use_auth_token=HF_TOKEN)
32
+ else:
33
+ pipe = MultiResPipeline.from_pretrained(model_id,
34
+ torch_dtype=torch.float16,
35
+ revision='fp16',
36
+ use_auth_token=HF_TOKEN)
37
+ self.pipe = pipe.to(self.device)
38
+ self.pipe.scheduler = DPMSolverMultistepScheduler(
39
+ beta_start=0.00085,
40
+ beta_end=0.012,
41
+ beta_schedule='scaled_linear',
42
+ num_train_timesteps=1000,
43
+ trained_betas=None,
44
+ predict_epsilon=True,
45
+ thresholding=False,
46
+ algorithm_type='dpmsolver++',
47
+ solver_type='midpoint',
48
+ lower_order_final=True,
49
+ )
50
+ self.string_to_param_dict = load_learned_concepts(
51
+ self.pipe, 'textual_inversion_outputs/')
52
+
53
+ def run(self, prompt: str, n_images: int, n_steps: int,
54
+ seed: int) -> list[PIL.Image.Image]:
55
+ generator = torch.Generator(device=self.device).manual_seed(seed)
56
+ return self.pipe([prompt] * n_images,
57
+ self.string_to_param_dict,
58
+ num_inference_steps=n_steps,
59
+ generator=generator)
multires_textual_inversion ADDED
@@ -0,0 +1 @@
 
 
1
+ Subproject commit ebe79d70929f9f4fabde9d038d1e948a05b3027f
patch ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/pipeline.py b/pipeline.py
2
+ index 7c41e04..842c5b4 100644
3
+ --- a/pipeline.py
4
+ +++ b/pipeline.py
5
+ @@ -27,7 +27,7 @@ def load_learned_concepts(pipe, root_folder="selected_outputs/", num_scales=10):
6
+ for exp_name in os.listdir(root_folder):
7
+ # get everything up to the first numeric
8
+ pure_names.append(exp_name)
9
+ - encoder = torch.load(os.path.join(root_folder, exp_name, "text_encoder/pytorch_model.bin"))
10
+ + encoder = torch.load(os.path.join(root_folder, exp_name, "text_encoder/pytorch_model.bin"), map_location=pipe.device)
11
+ embeddings = encoder["text_model.embeddings.token_embedding.weight"]
12
+ param_value = embeddings[-10:]
13
+
14
+ @@ -36,23 +36,23 @@ def load_learned_concepts(pipe, root_folder="selected_outputs/", num_scales=10):
15
+ string_name = f"<{exp_name}|{t}|>"
16
+ tokens_to_add.append(string_name)
17
+ string_to_param_dict[string_name] = torch.nn.Parameter(param_value[t].unsqueeze(0).repeat([num_scales, 1]))
18
+ -
19
+ +
20
+ # Fully Resolution: use appropriate time embedding for the whole generation time.
21
+ string_name = f"<{exp_name}[{t}]>"
22
+ tokens_to_add.append(string_name)
23
+ repeats = t + 1
24
+ rep_param = param_value[t].unsqueeze(0).repeat([repeats, 1])
25
+ left = param_value[rep_param.shape[0]:]
26
+ - new_param = torch.cat([rep_param, left])
27
+ + new_param = torch.cat([rep_param, left])
28
+ string_to_param_dict[string_name] = torch.nn.Parameter(new_param)
29
+
30
+ # Semi Resolution: use appropriate time embedding up to a certain time and then no conditioning.
31
+ string_name = f"<{exp_name}({t})>"
32
+ tokens_to_add.append(string_name)
33
+ - null_embedding = torch.zeros((param_value.shape[1],), device=param_value.device, dtype=param_value.dtype)
34
+ + null_embedding = torch.zeros((param_value.shape[1],), device=pipe.device, dtype=param_value.dtype)
35
+ rep_param = null_embedding.unsqueeze(0).repeat([t + 1, 1])
36
+ left = param_value[rep_param.shape[0]:]
37
+ - new_param = torch.cat([rep_param, left])
38
+ + new_param = torch.cat([rep_param, left])
39
+ string_to_param_dict[string_name] = torch.nn.Parameter(new_param)
40
+
41
+ pipe.tokenizer.add_tokens(tokens_to_add)
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ accelerate==0.12.0
2
+ diffusers==0.9.0
3
+ ftfy==6.1.1
4
+ Pillow==9.2.0
5
+ torch==1.12.1
6
+ transformers==4.22.1
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
+ }
textual_inversion_outputs/cat-toy/text_encoder/config.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "runwayml/stable-diffusion-v1-5",
3
+ "architectures": [
4
+ "CLIPTextModel"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 0,
8
+ "dropout": 0.0,
9
+ "eos_token_id": 2,
10
+ "hidden_act": "quick_gelu",
11
+ "hidden_size": 768,
12
+ "initializer_factor": 1.0,
13
+ "initializer_range": 0.02,
14
+ "intermediate_size": 3072,
15
+ "layer_norm_eps": 1e-05,
16
+ "max_position_embeddings": 77,
17
+ "model_type": "clip_text_model",
18
+ "num_attention_heads": 12,
19
+ "num_hidden_layers": 12,
20
+ "pad_token_id": 1,
21
+ "projection_dim": 768,
22
+ "torch_dtype": "float32",
23
+ "transformers_version": "4.24.0",
24
+ "vocab_size": 49418
25
+ }
textual_inversion_outputs/cat-toy/text_encoder/pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:98b628c646c93aeb917cfaba0d1af0dbf2a7348cc614acce5f3fddda597cbd2e
3
+ size 492338807
textual_inversion_outputs/gta5-artwork/text_encoder/config.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "runwayml/stable-diffusion-v1-5",
3
+ "architectures": [
4
+ "CLIPTextModel"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 0,
8
+ "dropout": 0.0,
9
+ "eos_token_id": 2,
10
+ "hidden_act": "quick_gelu",
11
+ "hidden_size": 768,
12
+ "initializer_factor": 1.0,
13
+ "initializer_range": 0.02,
14
+ "intermediate_size": 3072,
15
+ "layer_norm_eps": 1e-05,
16
+ "max_position_embeddings": 77,
17
+ "model_type": "clip_text_model",
18
+ "num_attention_heads": 12,
19
+ "num_hidden_layers": 12,
20
+ "pad_token_id": 1,
21
+ "projection_dim": 768,
22
+ "torch_dtype": "float32",
23
+ "transformers_version": "4.24.0",
24
+ "vocab_size": 49418
25
+ }
textual_inversion_outputs/gta5-artwork/text_encoder/pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4812193a5df98edf62d3df13460f886572a71ab8585545520c44b92a7b8e1bd2
3
+ size 492338807
textual_inversion_outputs/jane/text_encoder/config.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "runwayml/stable-diffusion-v1-5",
3
+ "architectures": [
4
+ "CLIPTextModel"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 0,
8
+ "dropout": 0.0,
9
+ "eos_token_id": 2,
10
+ "hidden_act": "quick_gelu",
11
+ "hidden_size": 768,
12
+ "initializer_factor": 1.0,
13
+ "initializer_range": 0.02,
14
+ "intermediate_size": 3072,
15
+ "layer_norm_eps": 1e-05,
16
+ "max_position_embeddings": 77,
17
+ "model_type": "clip_text_model",
18
+ "num_attention_heads": 12,
19
+ "num_hidden_layers": 12,
20
+ "pad_token_id": 1,
21
+ "projection_dim": 768,
22
+ "torch_dtype": "float32",
23
+ "transformers_version": "4.21.0",
24
+ "vocab_size": 49418
25
+ }
textual_inversion_outputs/jane/text_encoder/pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8acb7b5f0e2b8c10a349cddec2ef577e34e91e74f9107683465508b8aab511da
3
+ size 492338807