|
19 | 19 | from typing import Tuple |
20 | 20 |
|
21 | 21 | import flax |
| 22 | +from flax import nnx |
22 | 23 | import flax.linen as nn |
23 | 24 | import jax |
24 | 25 | from jax import tree_util |
@@ -958,3 +959,60 @@ def _wan_diag_gauss_dist_unflatten(aux, children): |
958 | 959 | _wan_diag_gauss_dist_flatten, |
959 | 960 | _wan_diag_gauss_dist_unflatten, |
960 | 961 | ) |
| 962 | + |
| 963 | + |
| 964 | +class NNXFlaxAutoencoderKL(nnx.Module): |
| 965 | + |
| 966 | + def __init__( |
| 967 | + self, |
| 968 | + rngs: nnx.Rngs, |
| 969 | + in_channels: int = 3, |
| 970 | + out_channels: int = 3, |
| 971 | + down_block_types: Tuple[str, ...] = ("FlaxDownEncoderBlock2D",), |
| 972 | + up_block_types: Tuple[str, ...] = ("FlaxUpDecoderBlock2D",), |
| 973 | + block_out_channels: Tuple[int, ...] = (64,), |
| 974 | + layers_per_block: int = 1, |
| 975 | + act_fn: str = "silu", |
| 976 | + latent_channels: int = 4, |
| 977 | + norm_num_groups: int = 32, |
| 978 | + sample_size: int = 32, |
| 979 | + dtype: jnp.dtype = jnp.float32, |
| 980 | + weights_dtype: jnp.dtype = jnp.float32, |
| 981 | + ): |
| 982 | + self.in_channels = in_channels |
| 983 | + self.out_channels = out_channels |
| 984 | + self.latent_channels = latent_channels |
| 985 | + self.dtype = dtype |
| 986 | + |
| 987 | + self.decoder = FlaxDecoder( |
| 988 | + in_channels=latent_channels, |
| 989 | + out_channels=out_channels, |
| 990 | + up_block_types=up_block_types, |
| 991 | + block_out_channels=block_out_channels, |
| 992 | + layers_per_block=layers_per_block, |
| 993 | + norm_num_groups=norm_num_groups, |
| 994 | + act_fn=act_fn, |
| 995 | + dtype=dtype, |
| 996 | + weights_dtype=weights_dtype, |
| 997 | + ) |
| 998 | + self.post_quant_conv = nn.Conv( |
| 999 | + latent_channels, |
| 1000 | + kernel_size=(1, 1), |
| 1001 | + strides=(1, 1), |
| 1002 | + padding="VALID", |
| 1003 | + dtype=dtype, |
| 1004 | + param_dtype=weights_dtype, |
| 1005 | + ) |
| 1006 | + |
| 1007 | + def decode(self, latents: jax.Array, deterministic: bool = True, return_dict: bool = True): |
| 1008 | + if latents.shape[-1] != self.latent_channels: |
| 1009 | + latents = jnp.transpose(latents, (0, 2, 3, 1)) |
| 1010 | + |
| 1011 | + hidden_states = self.post_quant_conv(latents) |
| 1012 | + hidden_states = self.decoder(hidden_states, deterministic=deterministic) |
| 1013 | + hidden_states = jnp.transpose(hidden_states, (0, 3, 1, 2)) |
| 1014 | + |
| 1015 | + if not return_dict: |
| 1016 | + return (hidden_states,) |
| 1017 | + |
| 1018 | + return FlaxDecoderOutput(sample=hidden_states) |
0 commit comments