(params, minibatch, sample_rng)
| 854 | batch = jax.tree_map(lambda x: x.reshape((grad_steps, x.shape[0] // grad_steps) + x.shape[1:]), batch) |
| 855 | |
| 856 | def compute_loss(params, minibatch, sample_rng): |
| 857 | # Convert images to latent space |
| 858 | vae_outputs = vae.apply( |
| 859 | {"params": vae_params}, minibatch["pixel_values"], deterministic=True, method=vae.encode |
| 860 | ) |
| 861 | latents = vae_outputs.latent_dist.sample(sample_rng) |
| 862 | # (NHWC) -> (NCHW) |
| 863 | latents = jnp.transpose(latents, (0, 3, 1, 2)) |
| 864 | latents = latents * vae.config.scaling_factor |
| 865 | |
| 866 | # Sample noise that we'll add to the latents |
| 867 | noise_rng, timestep_rng = jax.random.split(sample_rng) |
| 868 | noise = jax.random.normal(noise_rng, latents.shape) |
| 869 | # Sample a random timestep for each image |
| 870 | bsz = latents.shape[0] |
| 871 | timesteps = jax.random.randint( |
| 872 | timestep_rng, |
| 873 | (bsz,), |
| 874 | 0, |
| 875 | noise_scheduler.config.num_train_timesteps, |
| 876 | ) |
| 877 | |
| 878 | # Add noise to the latents according to the noise magnitude at each timestep |
| 879 | # (this is the forward diffusion process) |
| 880 | noisy_latents = noise_scheduler.add_noise(noise_scheduler_state, latents, noise, timesteps) |
| 881 | |
| 882 | # Get the text embedding for conditioning |
| 883 | encoder_hidden_states = text_encoder( |
| 884 | minibatch["input_ids"], |
| 885 | params=text_encoder_params, |
| 886 | train=False, |
| 887 | )[0] |
| 888 | |
| 889 | controlnet_cond = minibatch["conditioning_pixel_values"] |
| 890 | |
| 891 | # Predict the noise residual and compute loss |
| 892 | down_block_res_samples, mid_block_res_sample = controlnet.apply( |
| 893 | {"params": params}, |
| 894 | noisy_latents, |
| 895 | timesteps, |
| 896 | encoder_hidden_states, |
| 897 | controlnet_cond, |
| 898 | train=True, |
| 899 | return_dict=False, |
| 900 | ) |
| 901 | |
| 902 | model_pred = unet.apply( |
| 903 | {"params": unet_params}, |
| 904 | noisy_latents, |
| 905 | timesteps, |
| 906 | encoder_hidden_states, |
| 907 | down_block_additional_residuals=down_block_res_samples, |
| 908 | mid_block_additional_residual=mid_block_res_sample, |
| 909 | ).sample |
| 910 | |
| 911 | # Get the target for loss depending on the prediction type |
| 912 | if noise_scheduler.config.prediction_type == "epsilon": |
| 913 | target = noise |
nothing calls this directly
no test coverage detected