thefreeham commited on
Commit
9a7dea4
1 Parent(s): 232330c

Create dalle_model.py

Browse files
Files changed (1) hide show
  1. dalle_model.py +114 -0
dalle_model.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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