Skip to content

Convolutional VAE for MNIST

Convolutional variational autoencoder (CVAE) implementation in MLX using MNIST. This is based on the CVAE implementation in MLX.

julia
using Lux,
    Reactant,
    MLDatasets,
    Random,
    Statistics,
    Enzyme,
    MLUtils,
    DataAugmentation,
    ConcreteStructs,
    OneHotArrays,
    ImageShow,
    Images,
    Printf,
    Optimisers

const xdev = reactant_device(; force=true)
const cdev = cpu_device()

const IN_VSCODE = isdefined(Main, :VSCodeServer)
false

Model Definition

First we will define the encoder.It maps the input to a normal distribution in latent space and sample a latent vector from that distribution.

julia
function cvae_encoder(
    rng=Random.default_rng();
    num_latent_dims::Int,
    image_shape::Dims{3},
    max_num_filters::Int,
)
    flattened_dim = prod(image_shape[1:2]  8) * max_num_filters
    return @compact(;
        embed=Chain(
            Chain(
                Conv((3, 3), image_shape[3] => max_num_filters ÷ 4; stride=2, pad=1),
                BatchNorm(max_num_filters ÷ 4, leakyrelu),
            ),
            Chain(
                Conv((3, 3), max_num_filters ÷ 4 => max_num_filters ÷ 2; stride=2, pad=1),
                BatchNorm(max_num_filters ÷ 2, leakyrelu),
            ),
            Chain(
                Conv((3, 3), max_num_filters ÷ 2 => max_num_filters; stride=2, pad=1),
                BatchNorm(max_num_filters, leakyrelu),
            ),
            FlattenLayer(),
        ),
        proj_mu=Dense(flattened_dim, num_latent_dims; init_bias=zeros32),
        proj_log_var=Dense(flattened_dim, num_latent_dims; init_bias=zeros32),
        rng
    ) do x
        y = embed(x)

        μ = proj_mu(y)
        logσ² = proj_log_var(y)

        T = eltype(logσ²)
        logσ² = clamp.(logσ², -T(20.0f0), T(10.0f0))
        σ = exp.(logσ² .* T(0.5))

        # Generate a tensor of random values from a normal distribution
        ϵ = randn_like(Lux.replicate(rng), σ)

        # Reparameterization trick to backpropagate through sampling
        z = ϵ .* σ .+ μ

        @return z, μ, logσ²
    end
end

Similarly we define the decoder.

julia
function cvae_decoder(; num_latent_dims::Int, image_shape::Dims{3}, max_num_filters::Int)
    flattened_dim = prod(image_shape[1:2]  8) * max_num_filters
    return @compact(;
        linear=Dense(num_latent_dims, flattened_dim),
        upchain=Chain(
            Chain(
                Upsample(2),
                Conv((3, 3), max_num_filters => max_num_filters ÷ 2; stride=1, pad=1),
                BatchNorm(max_num_filters ÷ 2, leakyrelu),
            ),
            Chain(
                Upsample(2),
                Conv((3, 3), max_num_filters ÷ 2 => max_num_filters ÷ 4; stride=1, pad=1),
                BatchNorm(max_num_filters ÷ 4, leakyrelu),
            ),
            Chain(
                Upsample(2),
                Conv(
                    (3, 3), max_num_filters ÷ 4 => image_shape[3], sigmoid; stride=1, pad=1
                ),
            ),
        ),
        max_num_filters
    ) do x
        y = linear(x)
        img = reshape(y, image_shape[1] ÷ 8, image_shape[2] ÷ 8, max_num_filters, :)
        @return upchain(img)
    end
end

@concrete struct CVAE <: AbstractLuxContainerLayer{(:encoder, :decoder)}
    encoder <: AbstractLuxLayer
    decoder <: AbstractLuxLayer
end

function CVAE(
    rng=Random.default_rng();
    num_latent_dims::Int,
    image_shape::Dims{3},
    max_num_filters::Int,
)
    decoder = cvae_decoder(; num_latent_dims, image_shape, max_num_filters)
    encoder = cvae_encoder(rng; num_latent_dims, image_shape, max_num_filters)
    return CVAE(encoder, decoder)
end

function (cvae::CVAE)(x, ps, st)
    (z, μ, logσ²), st_enc = cvae.encoder(x, ps.encoder, st.encoder)
    x_rec, st_dec = cvae.decoder(z, ps.decoder, st.decoder)
    return (x_rec, μ, logσ²), (; encoder=st_enc, decoder=st_dec)
end

function encode(cvae::CVAE, x, ps, st)
    (z, _, _), st_enc = cvae.encoder(x, ps.encoder, st.encoder)
    return z, (; encoder=st_enc, st.decoder)
end

function decode(cvae::CVAE, z, ps, st)
    x_rec, st_dec = cvae.decoder(z, ps.decoder, st.decoder)
    return x_rec, (; decoder=st_dec, st.encoder)
end

Loading MNIST

julia
@concrete struct TensorDataset
    dataset
    transform
    total_samples::Int
end

Base.length(ds::TensorDataset) = ds.total_samples

function Base.getindex(ds::TensorDataset, idxs::Union{Vector{<:Integer},AbstractRange})
    img = Image.(eachslice(convert2image(ds.dataset, idxs); dims=3))
    return stack(parent  itemdata  Base.Fix1(apply, ds.transform), img)
end

function loadmnist(batchsize, image_size::Dims{2})
    # Load MNIST: Only 1500 for demonstration purposes on CI
    train_dataset = MNIST(; split=:train)
    N = parse(Bool, get(ENV, "CI", "false")) ? 5000 : length(train_dataset)

    train_transform = ScaleKeepAspect(image_size) |> ImageToTensor()
    trainset = TensorDataset(train_dataset, train_transform, N)
    trainloader = DataLoader(trainset; batchsize, shuffle=true, partial=false)

    return trainloader
end

Helper Functions

Generate an Image Grid from a list of images

julia
function create_image_grid(imgs::AbstractArray, grid_rows::Int, grid_cols::Int)
    total_images = grid_rows * grid_cols
    imgs = map(eachslice(imgs[:, :, :, 1:total_images]; dims=4)) do img
        cimg = if size(img, 3) == 1
            colorview(Gray, view(img, :, :, 1))
        else
            colorview(RGB, permutedims(img, (3, 1, 2)))
        end
        return cimg'
    end
    return create_image_grid(imgs, grid_rows, grid_cols)
end

function create_image_grid(images::Vector, grid_rows::Int, grid_cols::Int)
    # Check if the number of images matches the grid
    total_images = grid_rows * grid_cols
    @assert length(images) == total_images

    # Get the size of a single image (assuming all images are the same size)
    img_height, img_width = size(images[1])

    # Create a blank grid canvas
    grid_height = img_height * grid_rows
    grid_width = img_width * grid_cols
    grid_canvas = similar(images[1], grid_height, grid_width)

    # Place each image in the correct position on the canvas
    for idx in 1:total_images
        row = div(idx - 1, grid_cols) + 1
        col = mod(idx - 1, grid_cols) + 1

        start_row = (row - 1) * img_height + 1
        start_col = (col - 1) * img_width + 1

        grid_canvas[start_row:(start_row + img_height - 1), start_col:(start_col + img_width - 1)] .= images[idx]
    end

    return grid_canvas
end

function loss_function(model, ps, st, X)
    (y, μ, logσ²), st = model(X, ps, st)
    reconstruction_loss = MSELoss(; agg=sum)(y, X)
    kldiv_loss = -sum(1 .+ logσ² .- μ .^ 2 .- exp.(logσ²)) / 2
    loss = reconstruction_loss + kldiv_loss
    return loss, st, (; y, μ, logσ², reconstruction_loss, kldiv_loss)
end

function generate_images(
    model, ps, st; num_samples::Int=128, num_latent_dims::Int, decode_compiled=nothing
)
    z = get_device((ps, st))(randn(Float32, num_latent_dims, num_samples))
    if decode_compiled === nothing
        images, _ = decode(model, z, ps, Lux.testmode(st))
    else
        images, _ = decode_compiled(model, z, ps, Lux.testmode(st))
        images = cpu_device()(images)
    end
    return create_image_grid(images, 8, num_samples ÷ 8)
end

function reconstruct_images(model, ps, st, X)
    (recon, _, _), _ = model(X, ps, Lux.testmode(st))
    recon = cpu_device()(recon)
    return create_image_grid(recon, 8, size(X, ndims(X)) ÷ 8)
end
reconstruct_images (generic function with 1 method)

Training the Model

julia
function main(;
    batchsize=128,
    image_size=(64, 64),
    num_latent_dims=8,
    max_num_filters=64,
    seed=0,
    epochs=50,
    weight_decay=1.0e-5,
    learning_rate=1.0e-3,
    num_samples=batchsize,
)
    rng = Xoshiro()
    Random.seed!(rng, seed)

    cvae = CVAE(rng; num_latent_dims, image_shape=(image_size..., 1), max_num_filters)
    ps, st = Lux.setup(rng, cvae) |> xdev

    z = xdev(randn(Float32, num_latent_dims, num_samples))
    decode_compiled = @compile decode(cvae, z, ps, Lux.testmode(st))
    x = randn(Float32, image_size..., 1, batchsize) |> xdev
    cvae_compiled = @compile cvae(x, ps, Lux.testmode(st))

    train_dataloader = loadmnist(batchsize, image_size) |> xdev

    opt = AdamW(; eta=learning_rate, lambda=weight_decay)

    train_state = Training.TrainState(cvae, ps, st, opt)

    @printf "Total Trainable Parameters: %0.4f M\n" (Lux.parameterlength(ps) / 1.0e6)

    empty_row, model_img_full = nothing, nothing

    for epoch in 1:epochs
        loss_total = 0.0f0
        total_samples = 0

        start_time = time()
        for (i, X) in enumerate(train_dataloader)
            (_, loss, _, train_state) = Training.single_train_step!(
                AutoEnzyme(), loss_function, X, train_state; return_gradients=Val(false)
            )

            loss_total += loss
            total_samples += size(X, ndims(X))

            if i % 250 == 0 || i == length(train_dataloader)
                throughput = total_samples / (time() - start_time)
                @printf "Epoch %d, Iter %d, Loss: %.7f, Throughput: %.6f im/s\n" epoch i loss throughput
            end
        end
        total_time = time() - start_time

        train_loss = loss_total / length(train_dataloader)
        throughput = total_samples / total_time
        @printf "Epoch %d, Train Loss: %.7f, Time: %.4fs, Throughput: %.6f im/s\n" epoch train_loss total_time throughput

        if IN_VSCODE || epoch == epochs
            recon_images = reconstruct_images(
                cvae_compiled,
                train_state.parameters,
                train_state.states,
                first(train_dataloader),
            )
            gen_images = generate_images(
                cvae,
                train_state.parameters,
                train_state.states;
                num_samples,
                num_latent_dims,
                decode_compiled,
            )
            if empty_row === nothing
                empty_row = similar(gen_images, image_size[1], size(gen_images, 2))
                fill!(empty_row, 0)
            end
            model_img_full = vcat(recon_images, empty_row, gen_images)
            IN_VSCODE && display(model_img_full)
        end
    end

    return model_img_full
end

img = main()
Total Trainable Parameters: 0.1493 M
Epoch 1, Iter 39, Loss: 24243.8828125, Throughput: 26.973052 im/s
Epoch 1, Train Loss: 39723.9179688, Time: 185.4460s, Throughput: 26.918882 im/s
Epoch 2, Iter 39, Loss: 18072.4062500, Throughput: 88.367646 im/s
Epoch 2, Train Loss: 20361.2714844, Time: 56.4914s, Throughput: 88.367408 im/s
Epoch 3, Iter 39, Loss: 14756.2246094, Throughput: 87.770333 im/s
Epoch 3, Train Loss: 16645.0761719, Time: 56.8759s, Throughput: 87.770094 im/s
Epoch 4, Iter 39, Loss: 14679.8125000, Throughput: 88.089177 im/s
Epoch 4, Train Loss: 15130.2851562, Time: 56.6700s, Throughput: 88.088914 im/s
Epoch 5, Iter 39, Loss: 13501.7607422, Throughput: 88.924283 im/s
Epoch 5, Train Loss: 14042.3300781, Time: 56.1378s, Throughput: 88.924030 im/s
Epoch 6, Iter 39, Loss: 13133.7744141, Throughput: 88.661610 im/s
Epoch 6, Train Loss: 13312.3857422, Time: 56.3041s, Throughput: 88.661363 im/s
Epoch 7, Iter 39, Loss: 12407.6210938, Throughput: 89.695456 im/s
Epoch 7, Train Loss: 12836.4902344, Time: 55.6551s, Throughput: 89.695213 im/s
Epoch 8, Iter 39, Loss: 12015.9345703, Throughput: 88.252228 im/s
Epoch 8, Train Loss: 12424.4902344, Time: 56.5653s, Throughput: 88.252003 im/s
Epoch 9, Iter 39, Loss: 11677.7158203, Throughput: 87.788608 im/s
Epoch 9, Train Loss: 12208.2832031, Time: 56.8640s, Throughput: 87.788358 im/s
Epoch 10, Iter 39, Loss: 12609.9960938, Throughput: 87.150675 im/s
Epoch 10, Train Loss: 11940.2587891, Time: 57.2803s, Throughput: 87.150438 im/s
Epoch 11, Iter 39, Loss: 11345.9609375, Throughput: 88.108470 im/s
Epoch 11, Train Loss: 11713.7919922, Time: 56.6576s, Throughput: 88.108228 im/s
Epoch 12, Iter 39, Loss: 11344.8359375, Throughput: 88.779154 im/s
Epoch 12, Train Loss: 11480.5908203, Time: 56.2296s, Throughput: 88.778865 im/s
Epoch 13, Iter 39, Loss: 11340.7128906, Throughput: 88.063794 im/s
Epoch 13, Train Loss: 11350.6064453, Time: 56.6863s, Throughput: 88.063538 im/s
Epoch 14, Iter 39, Loss: 10726.7539062, Throughput: 88.070006 im/s
Epoch 14, Train Loss: 11378.8291016, Time: 56.6823s, Throughput: 88.069760 im/s
Epoch 15, Iter 39, Loss: 10995.5546875, Throughput: 88.743738 im/s
Epoch 15, Train Loss: 11117.7656250, Time: 56.2520s, Throughput: 88.743499 im/s
Epoch 16, Iter 39, Loss: 11121.1201172, Throughput: 89.059124 im/s
Epoch 16, Train Loss: 11102.2470703, Time: 56.0528s, Throughput: 89.058873 im/s
Epoch 17, Iter 39, Loss: 10134.7089844, Throughput: 88.289815 im/s
Epoch 17, Train Loss: 10905.7919922, Time: 56.5412s, Throughput: 88.289584 im/s
Epoch 18, Iter 39, Loss: 10703.4843750, Throughput: 88.266029 im/s
Epoch 18, Train Loss: 10792.7773438, Time: 56.5564s, Throughput: 88.265807 im/s
Epoch 19, Iter 39, Loss: 11326.2333984, Throughput: 89.316859 im/s
Epoch 19, Train Loss: 10805.3984375, Time: 55.8911s, Throughput: 89.316600 im/s
Epoch 20, Iter 39, Loss: 11015.1210938, Throughput: 88.783902 im/s
Epoch 20, Train Loss: 10709.3261719, Time: 56.2266s, Throughput: 88.783678 im/s
Epoch 21, Iter 39, Loss: 10614.0644531, Throughput: 88.818539 im/s
Epoch 21, Train Loss: 10469.4033203, Time: 56.2046s, Throughput: 88.818299 im/s
Epoch 22, Iter 39, Loss: 11062.9921875, Throughput: 88.775534 im/s
Epoch 22, Train Loss: 10421.8623047, Time: 56.2318s, Throughput: 88.775312 im/s
Epoch 23, Iter 39, Loss: 10073.2324219, Throughput: 88.004053 im/s
Epoch 23, Train Loss: 10325.9951172, Time: 56.7248s, Throughput: 88.003819 im/s
Epoch 24, Iter 39, Loss: 10400.6064453, Throughput: 87.634412 im/s
Epoch 24, Train Loss: 10392.5566406, Time: 56.9641s, Throughput: 87.634175 im/s
Epoch 25, Iter 39, Loss: 9819.3789062, Throughput: 88.762499 im/s
Epoch 25, Train Loss: 10330.0576172, Time: 56.2401s, Throughput: 88.762278 im/s
Epoch 26, Iter 39, Loss: 9941.4648438, Throughput: 89.044185 im/s
Epoch 26, Train Loss: 10157.8466797, Time: 56.0622s, Throughput: 89.043926 im/s
Epoch 27, Iter 39, Loss: 9591.7421875, Throughput: 88.944929 im/s
Epoch 27, Train Loss: 10166.6123047, Time: 56.1248s, Throughput: 88.944682 im/s
Epoch 28, Iter 39, Loss: 10110.8046875, Throughput: 87.625362 im/s
Epoch 28, Train Loss: 10147.4736328, Time: 56.9700s, Throughput: 87.625127 im/s
Epoch 29, Iter 39, Loss: 10169.0488281, Throughput: 87.872987 im/s
Epoch 29, Train Loss: 10007.7421875, Time: 56.8094s, Throughput: 87.872748 im/s
Epoch 30, Iter 39, Loss: 9975.6083984, Throughput: 86.908096 im/s
Epoch 30, Train Loss: 10044.6943359, Time: 57.4401s, Throughput: 86.907877 im/s
Epoch 31, Iter 39, Loss: 9978.3105469, Throughput: 87.965246 im/s
Epoch 31, Train Loss: 9968.9179688, Time: 56.7498s, Throughput: 87.965030 im/s
Epoch 32, Iter 39, Loss: 9365.6494141, Throughput: 87.873471 im/s
Epoch 32, Train Loss: 9887.4697266, Time: 56.8091s, Throughput: 87.873247 im/s
Epoch 33, Iter 39, Loss: 9558.7304688, Throughput: 86.773309 im/s
Epoch 33, Train Loss: 9800.8027344, Time: 57.5294s, Throughput: 86.773078 im/s
Epoch 34, Iter 39, Loss: 9603.6748047, Throughput: 87.440337 im/s
Epoch 34, Train Loss: 9837.8857422, Time: 57.0905s, Throughput: 87.440104 im/s
Epoch 35, Iter 39, Loss: 9632.6796875, Throughput: 89.070166 im/s
Epoch 35, Train Loss: 9772.4355469, Time: 56.0459s, Throughput: 89.069915 im/s
Epoch 36, Iter 39, Loss: 9626.8691406, Throughput: 88.238524 im/s
Epoch 36, Train Loss: 9698.0976562, Time: 56.5741s, Throughput: 88.238309 im/s
Epoch 37, Iter 39, Loss: 9577.0664062, Throughput: 87.169337 im/s
Epoch 37, Train Loss: 9717.7070312, Time: 57.2680s, Throughput: 87.169122 im/s
Epoch 38, Iter 39, Loss: 9263.3574219, Throughput: 87.875473 im/s
Epoch 38, Train Loss: 9631.4648438, Time: 56.8078s, Throughput: 87.875252 im/s
Epoch 39, Iter 39, Loss: 9663.2656250, Throughput: 89.227317 im/s
Epoch 39, Train Loss: 9548.9404297, Time: 55.9471s, Throughput: 89.227077 im/s
Epoch 40, Iter 39, Loss: 9379.0849609, Throughput: 87.711701 im/s
Epoch 40, Train Loss: 9619.2119141, Time: 56.9139s, Throughput: 87.711490 im/s
Epoch 41, Iter 39, Loss: 9152.1494141, Throughput: 87.035668 im/s
Epoch 41, Train Loss: 9623.1113281, Time: 57.3559s, Throughput: 87.035445 im/s
Epoch 42, Iter 39, Loss: 9883.0625000, Throughput: 87.706167 im/s
Epoch 42, Train Loss: 9520.2519531, Time: 56.9175s, Throughput: 87.705944 im/s
Epoch 43, Iter 39, Loss: 9723.2226562, Throughput: 88.324337 im/s
Epoch 43, Train Loss: 9515.9082031, Time: 56.5191s, Throughput: 88.324077 im/s
Epoch 44, Iter 39, Loss: 9452.3251953, Throughput: 87.387989 im/s
Epoch 44, Train Loss: 9512.1591797, Time: 57.1247s, Throughput: 87.387740 im/s
Epoch 45, Iter 39, Loss: 9532.8496094, Throughput: 88.024520 im/s
Epoch 45, Train Loss: 9457.9228516, Time: 56.7116s, Throughput: 88.024307 im/s
Epoch 46, Iter 39, Loss: 9664.5859375, Throughput: 88.548780 im/s
Epoch 46, Train Loss: 9416.1376953, Time: 56.3759s, Throughput: 88.548545 im/s
Epoch 47, Iter 39, Loss: 9100.7402344, Throughput: 87.522185 im/s
Epoch 47, Train Loss: 9397.9609375, Time: 57.0371s, Throughput: 87.521943 im/s
Epoch 48, Iter 39, Loss: 10262.7060547, Throughput: 87.831848 im/s
Epoch 48, Train Loss: 9349.1718750, Time: 56.8360s, Throughput: 87.831633 im/s
Epoch 49, Iter 39, Loss: 9382.8916016, Throughput: 88.575254 im/s
Epoch 49, Train Loss: 9312.2587891, Time: 56.3590s, Throughput: 88.575006 im/s
Epoch 50, Iter 39, Loss: 9483.3388672, Throughput: 88.017157 im/s
Epoch 50, Train Loss: 9365.7734375, Time: 56.7164s, Throughput: 88.016927 im/s

Appendix

julia
using InteractiveUtils
InteractiveUtils.versioninfo()

if @isdefined(MLDataDevices)
    if @isdefined(CUDA) && MLDataDevices.functional(CUDADevice)
        println()
        CUDA.versioninfo()
    end

    if @isdefined(AMDGPU) && MLDataDevices.functional(AMDGPUDevice)
        println()
        AMDGPU.versioninfo()
    end
end
Julia Version 1.11.8
Commit cf1da5e20e3 (2025-11-06 17:49 UTC)
Build Info:
  Official https://julialang.org/ release
Platform Info:
  OS: Linux (x86_64-linux-gnu)
  CPU: 4 × AMD EPYC 7763 64-Core Processor
  WORD_SIZE: 64
  LLVM: libLLVM-16.0.6 (ORCJIT, znver3)
Threads: 4 default, 0 interactive, 2 GC (on 4 virtual cores)
Environment:
  JULIA_DEBUG = Literate
  LD_LIBRARY_PATH = 
  JULIA_NUM_THREADS = 4
  JULIA_CPU_HARD_MEMORY_LIMIT = 100%
  JULIA_PKG_PRECOMPILE_AUTO = 0

This page was generated using Literate.jl.