thefreeham commited on
Commit
3194719
1 Parent(s): 7ac0161

Update dalle_models.py

Browse files
Files changed (1) hide show
  1. dalle_models.py +108 -18
dalle_models.py CHANGED
@@ -1,24 +1,114 @@
1
- from enum import Enum
 
 
2
 
3
- IMAGES_OUTPUT_DIR = 'generations'
 
 
 
4
 
5
- DALLE_MODEL_MINI = "dalle-mini/dalle-mini/mini-1:v0" # the original DALL-E Mini. Fastest yet suboptimal results
6
- DALLE_MODEL_MEGA = "dalle-mini/dalle-mini/mega-1-fp16:latest" # the advanced version of DALL-E Mini. Requires more compute and VRAM
7
- DALLE_MODEL_MEGA_FULL = "dalle-mini/dalle-mini/mega-1:latest" # DALL-E Mega. Warning: requires significantly more storage and GPU RAM
8
- DALLE_COMMIT_ID = None
9
 
10
- # VQGAN model
11
- VQGAN_REPO = "dalle-mini/vqgan_imagenet_f16_16384"
12
- VQGAN_COMMIT_ID = "e93a26e7707683d349bf5d5c41c5b0ef69b677a9"
13
 
 
 
14
 
15
- # We can customize generation parameters (see https://huggingface.co/blog/how-to-generate)
16
- GEN_TOP_K = None
17
- GEN_TOP_P = None
18
- TEMPERATURE = None
19
- COND_SCALE = 10.0
20
 
21
- class ModelSize(Enum):
22
- MINI = "Mini"
23
- MEGA = "Mega"
24
- MEGA_FULL = "Mega_full"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+ from functools import partial
4
 
5
+ import jax
6
+ import numpy as np
7
+ import jax.numpy as jnp
8
+ from PIL import Image
9
 
10
+ from dalle_mini import DalleBart, DalleBartProcessor
11
+ from vqgan_jax.modeling_flax_vqgan import VQModel
 
 
12
 
 
 
 
13
 
14
+ from flax.jax_utils import replicate
15
+ from flax.training.common_utils import shard_prng_key
16
 
17
+ import wandb
 
 
 
 
18
 
19
+ from consts import COND_SCALE, DALLE_COMMIT_ID, DALLE_MODEL_MEGA_FULL, DALLE_MODEL_MEGA, DALLE_MODEL_MINI, GEN_TOP_K, GEN_TOP_P, TEMPERATURE, VQGAN_COMMIT_ID, VQGAN_REPO, ModelSize
20
+
21
+ os.environ["XLA_PYTHON_CLIENT_ALLOCATOR"] = "platform" # https://github.com/saharmor/dalle-playground/issues/14#issuecomment-1147849318
22
+ os.environ["WANDB_SILENT"] = "true"
23
+ wandb.init(anonymous="must")
24
+
25
+ # model inference
26
+ @partial(jax.pmap, axis_name="batch", static_broadcasted_argnums=(3, 4, 5, 6, 7))
27
+ def p_generate(
28
+ tokenized_prompt, key, params, top_k, top_p, temperature, condition_scale, model
29
+ ):
30
+ return model.generate(
31
+ **tokenized_prompt,
32
+ prng_key=key,
33
+ params=params,
34
+ top_k=top_k,
35
+ top_p=top_p,
36
+ temperature=temperature,
37
+ condition_scale=condition_scale,
38
+ )
39
+
40
+
41
+ # decode images
42
+ @partial(jax.pmap, axis_name="batch", static_broadcasted_argnums=(0))
43
+ def p_decode(vqgan, indices, params):
44
+ return vqgan.decode_code(indices, params=params)
45
+
46
+
47
+ class DalleModel:
48
+ def __init__(self, model_version: ModelSize) -> None:
49
+ if model_version == ModelSize.MEGA_FULL:
50
+ dalle_model = DALLE_MODEL_MEGA_FULL
51
+ dtype = jnp.float16
52
+ elif model_version == ModelSize.MEGA:
53
+ dalle_model = DALLE_MODEL_MEGA
54
+ dtype = jnp.float16
55
+ else:
56
+ dalle_model = DALLE_MODEL_MINI
57
+ dtype = jnp.float32
58
+
59
+
60
+ # Load dalle-mini
61
+ self.model, params = DalleBart.from_pretrained(
62
+ dalle_model, revision=DALLE_COMMIT_ID, dtype=dtype, _do_init=False
63
+ )
64
+
65
+ # Load VQGAN
66
+ self.vqgan, vqgan_params = VQModel.from_pretrained(
67
+ VQGAN_REPO, revision=VQGAN_COMMIT_ID, _do_init=False
68
+ )
69
+
70
+ self.params = replicate(params)
71
+ self.vqgan_params = replicate(vqgan_params)
72
+
73
+ self.processor = DalleBartProcessor.from_pretrained(dalle_model, revision=DALLE_COMMIT_ID)
74
+
75
+
76
+ def tokenize_prompt(self, prompt: str):
77
+ tokenized_prompt = self.processor([prompt])
78
+ return replicate(tokenized_prompt)
79
+
80
+
81
+ def generate_images(self, prompt: str, num_predictions: int):
82
+ tokenized_prompt = self.tokenize_prompt(prompt)
83
+
84
+ # create a random key
85
+ seed = random.randint(0, 2 ** 32 - 1)
86
+ key = jax.random.PRNGKey(seed)
87
+
88
+ # generate images
89
+ images = []
90
+ for i in range(max(num_predictions // jax.device_count(), 1)):
91
+ # get a new key
92
+ key, subkey = jax.random.split(key)
93
+
94
+ encoded_images = p_generate(
95
+ tokenized_prompt,
96
+ shard_prng_key(subkey),
97
+ self.params,
98
+ GEN_TOP_K,
99
+ GEN_TOP_P,
100
+ TEMPERATURE,
101
+ COND_SCALE,
102
+ self.model
103
+ )
104
+
105
+ # remove BOS
106
+ encoded_images = encoded_images.sequences[..., 1:]
107
+
108
+ # decode images
109
+ decoded_images = p_decode(self.vqgan, encoded_images, self.vqgan_params)
110
+ decoded_images = decoded_images.clip(0.0, 1.0).reshape((-1, 256, 256, 3))
111
+ for img in decoded_images:
112
+ images.append(Image.fromarray(np.asarray(img * 255, dtype=np.uint8)))
113
+
114
+ return images