-
Notifications
You must be signed in to change notification settings - Fork 3
/
loss.py
176 lines (144 loc) · 5.1 KB
/
loss.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import jax.numpy as jnp
import jax
from diffusers import FlaxDDPMScheduler
# Min-SNR
snr_gamma = 5.0 # SNR weighting gamma to be used when rebalancing the loss with Min-SNR. Recommended value is 5.0.
def compute_snr_loss_weights(noise_scheduler_state, timesteps):
"""
Computes SNR as per https://github.com/TiankaiHang/Min-SNR-Diffusion-Training/blob/521b624bd70c67cee4bdf49225915f5945a872e3/guided_diffusion/gaussian_diffusion.py#L847-L849
"""
alphas_cumprod = noise_scheduler_state.common.alphas_cumprod
sqrt_alphas_cumprod = alphas_cumprod ** 0.5
sqrt_one_minus_alphas_cumprod = (1.0 - alphas_cumprod) ** 0.5
alpha = sqrt_alphas_cumprod[timesteps]
sigma = sqrt_one_minus_alphas_cumprod[timesteps]
# Compute SNR.
snr = jnp.array((alpha / sigma) ** 2)
# Compute SNR loss weights
return jnp.where(snr < snr_gamma, snr, jnp.ones_like(snr) * snr_gamma) / snr
def get_vae_latent_distribution_samples(
latents,
sample_rng,
noise_scheduler,
noise_scheduler_state,
):
# Sample noise that we'll add to the latents
noise_rng, timestep_rng = jax.random.split(sample_rng)
noise = jax.random.normal(noise_rng, latents.shape)
# Sample a random timestep for each image
timesteps = jax.random.randint(
key=timestep_rng,
shape=(latents.shape[0],),
minval=0,
maxval=noise_scheduler.config.num_train_timesteps,
dtype=jnp.int32,
)
# Add noise to the latents according to the noise magnitude at each timestep
# (this is the forward diffusion process)
noisy_latents = noise_scheduler.add_noise(
state=noise_scheduler_state,
original_samples=latents,
noise=noise,
timesteps=timesteps,
)
return noisy_latents, timesteps, noise
def get_cacheable_samples(
text_encoder, text_encoder_params, input_ids, vae, vae_params, pixel_values, rng
):
# Get the text embedding
# TODO: Cache this
# TODO: use t5x library
text_encoder_hidden_states = text_encoder(
input_ids,
params=text_encoder_params,
train=False,
)[0]
# Get the image embedding
vae_outputs = vae.apply(
{"params": vae_params},
sample=pixel_values,
deterministic=True,
method=vae.encode,
)
# Sample the image embedding
# TODO: Cache this
image_latent_distribution_sampling = (
# (NHWC) -> (NCHW)
jnp.transpose(vae_outputs.latent_dist.sample(rng), (0, 3, 1, 2))
* vae.config.scaling_factor
)
return text_encoder_hidden_states, image_latent_distribution_sampling
def get_compute_losses_lambda(
text_encoder, # <-- TODO: take this out of here
text_encoder_params, # <-- TODO: take this out of here
vae, # <-- TODO: take this out of here
vae_params, # <-- TODO: take this out of here
unet,
):
# Instanciate training noise scheduler
# TODO: write pure function
noise_scheduler = FlaxDDPMScheduler(
beta_start=0.00085,
beta_end=0.012,
beta_schedule="scaled_linear",
prediction_type="epsilon",
num_train_timesteps=1000,
)
def __compute_losses_lambda(
state_params,
batch,
sample_rng,
):
# TODO: take this out of here
(
text_encoder_hidden_states,
image_latent_distribution_sampling,
) = get_cacheable_samples(
text_encoder,
text_encoder_params,
batch["input_ids"],
vae,
vae_params,
batch["pixel_values"],
sample_rng,
)
# initialize scheduler state
noise_scheduler_state = noise_scheduler.create_state()
# Get the vae latent distribution samples
(
image_sampling_noisy_input,
image_sampling_timesteps,
noise,
) = get_vae_latent_distribution_samples(
image_latent_distribution_sampling,
sample_rng,
noise_scheduler,
noise_scheduler_state,
)
# Predict the noise residual and compute loss
# TODO: write pure function
unet_predictions = unet.apply(
{"params": state_params},
sample=image_sampling_noisy_input,
timesteps=image_sampling_timesteps,
encoder_hidden_states=text_encoder_hidden_states,
train=True,
).sample
# Compute each batch sample's loss from noisy target
loss_tensors = (noise - unet_predictions) ** 2
# Compute Min-SNR loss weights
snr_loss_weights = compute_snr_loss_weights(
noise_scheduler_state,
image_sampling_timesteps,
)
# Get one loss scalar per batch sample
losses = (
loss_tensors.mean(
axis=tuple(range(1, loss_tensors.ndim)),
)
* snr_loss_weights
) # Balance losses with Min-SNR
# This must be an averaged scalar, otherwise, you get this:
# TypeError: Gradient only defined for scalar-output functions. Output had shape: (8,).
return losses.mean(axis=0)
return __compute_losses_lambda