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: 23515.4609375, Throughput: 29.269318 im/s
Epoch 1, Train Loss: 39530.6171875, Time: 170.9118s, Throughput: 29.208039 im/s
Epoch 2, Iter 39, Loss: 17765.4472656, Throughput: 87.427033 im/s
Epoch 2, Train Loss: 20148.5917969, Time: 57.0993s, Throughput: 87.426713 im/s
Epoch 3, Iter 39, Loss: 15987.2187500, Throughput: 87.236710 im/s
Epoch 3, Train Loss: 16604.6660156, Time: 57.2238s, Throughput: 87.236450 im/s
Epoch 4, Iter 39, Loss: 14623.5673828, Throughput: 86.969615 im/s
Epoch 4, Train Loss: 15062.6845703, Time: 57.3995s, Throughput: 86.969364 im/s
Epoch 5, Iter 39, Loss: 13879.2548828, Throughput: 88.019358 im/s
Epoch 5, Train Loss: 14103.5019531, Time: 56.7150s, Throughput: 88.019046 im/s
Epoch 6, Iter 39, Loss: 13096.6445312, Throughput: 86.660069 im/s
Epoch 6, Train Loss: 13516.9804688, Time: 57.6046s, Throughput: 86.659820 im/s
Epoch 7, Iter 39, Loss: 12501.9550781, Throughput: 87.408020 im/s
Epoch 7, Train Loss: 13071.9394531, Time: 57.1116s, Throughput: 87.407757 im/s
Epoch 8, Iter 39, Loss: 12035.6289062, Throughput: 87.290295 im/s
Epoch 8, Train Loss: 12564.1318359, Time: 57.1887s, Throughput: 87.289979 im/s
Epoch 9, Iter 39, Loss: 11726.9228516, Throughput: 87.239066 im/s
Epoch 9, Train Loss: 12369.1152344, Time: 57.2222s, Throughput: 87.238811 im/s
Epoch 10, Iter 39, Loss: 12011.3427734, Throughput: 86.139206 im/s
Epoch 10, Train Loss: 12087.6611328, Time: 57.9529s, Throughput: 86.138965 im/s
Epoch 11, Iter 39, Loss: 11616.2031250, Throughput: 85.900602 im/s
Epoch 11, Train Loss: 11838.5126953, Time: 58.1139s, Throughput: 85.900318 im/s
Epoch 12, Iter 39, Loss: 11532.1552734, Throughput: 88.151053 im/s
Epoch 12, Train Loss: 11688.0556641, Time: 56.6302s, Throughput: 88.150771 im/s
Epoch 13, Iter 39, Loss: 11157.7480469, Throughput: 88.097593 im/s
Epoch 13, Train Loss: 11479.6855469, Time: 56.6647s, Throughput: 88.097239 im/s
Epoch 14, Iter 39, Loss: 11365.8222656, Throughput: 88.134860 im/s
Epoch 14, Train Loss: 11241.3642578, Time: 56.6407s, Throughput: 88.134566 im/s
Epoch 15, Iter 39, Loss: 11569.4062500, Throughput: 87.005365 im/s
Epoch 15, Train Loss: 11270.2968750, Time: 57.3760s, Throughput: 87.005095 im/s
Epoch 16, Iter 39, Loss: 11006.0781250, Throughput: 87.118722 im/s
Epoch 16, Train Loss: 11050.5527344, Time: 57.3013s, Throughput: 87.118450 im/s
Epoch 17, Iter 39, Loss: 11406.5175781, Throughput: 86.146141 im/s
Epoch 17, Train Loss: 11036.4492188, Time: 57.9482s, Throughput: 86.145900 im/s
Epoch 18, Iter 39, Loss: 11062.8193359, Throughput: 86.151760 im/s
Epoch 18, Train Loss: 10853.1757812, Time: 57.9444s, Throughput: 86.151534 im/s
Epoch 19, Iter 39, Loss: 10251.5585938, Throughput: 88.027200 im/s
Epoch 19, Train Loss: 10835.9628906, Time: 56.7099s, Throughput: 88.026927 im/s
Epoch 20, Iter 39, Loss: 10964.2285156, Throughput: 85.236746 im/s
Epoch 20, Train Loss: 10775.9033203, Time: 58.5665s, Throughput: 85.236512 im/s
Epoch 21, Iter 39, Loss: 10879.0527344, Throughput: 86.578725 im/s
Epoch 21, Train Loss: 10598.8691406, Time: 57.6587s, Throughput: 86.578463 im/s
Epoch 22, Iter 39, Loss: 9868.9052734, Throughput: 87.069056 im/s
Epoch 22, Train Loss: 10632.3505859, Time: 57.3340s, Throughput: 87.068791 im/s
Epoch 23, Iter 39, Loss: 10993.9843750, Throughput: 87.408489 im/s
Epoch 23, Train Loss: 10524.5205078, Time: 57.1113s, Throughput: 87.408253 im/s
Epoch 24, Iter 39, Loss: 10024.3808594, Throughput: 86.495422 im/s
Epoch 24, Train Loss: 10422.3798828, Time: 57.7142s, Throughput: 86.495151 im/s
Epoch 25, Iter 39, Loss: 10119.7988281, Throughput: 86.580868 im/s
Epoch 25, Train Loss: 10384.4746094, Time: 57.6573s, Throughput: 86.580605 im/s
Epoch 26, Iter 39, Loss: 9742.8281250, Throughput: 86.319454 im/s
Epoch 26, Train Loss: 10317.1269531, Time: 57.8319s, Throughput: 86.319196 im/s
Epoch 27, Iter 39, Loss: 10468.7578125, Throughput: 87.798098 im/s
Epoch 27, Train Loss: 10322.3046875, Time: 56.8579s, Throughput: 87.797837 im/s
Epoch 28, Iter 39, Loss: 10154.7480469, Throughput: 86.772095 im/s
Epoch 28, Train Loss: 10181.0781250, Time: 57.5302s, Throughput: 86.771841 im/s
Epoch 29, Iter 39, Loss: 10504.2988281, Throughput: 85.993756 im/s
Epoch 29, Train Loss: 10321.9326172, Time: 58.0509s, Throughput: 85.993515 im/s
Epoch 30, Iter 39, Loss: 10058.3183594, Throughput: 86.470048 im/s
Epoch 30, Train Loss: 10156.8349609, Time: 57.7312s, Throughput: 86.469772 im/s
Epoch 31, Iter 39, Loss: 10350.1289062, Throughput: 85.383555 im/s
Epoch 31, Train Loss: 10092.9277344, Time: 58.4658s, Throughput: 85.383305 im/s
Epoch 32, Iter 39, Loss: 10414.1572266, Throughput: 87.319084 im/s
Epoch 32, Train Loss: 10049.5029297, Time: 57.1698s, Throughput: 87.318807 im/s
Epoch 33, Iter 39, Loss: 9591.4091797, Throughput: 87.560639 im/s
Epoch 33, Train Loss: 9938.8632812, Time: 57.0121s, Throughput: 87.560395 im/s
Epoch 34, Iter 39, Loss: 9893.3457031, Throughput: 87.140540 im/s
Epoch 34, Train Loss: 9909.0244141, Time: 57.2870s, Throughput: 87.140256 im/s
Epoch 35, Iter 39, Loss: 9774.7402344, Throughput: 86.784457 im/s
Epoch 35, Train Loss: 9857.0849609, Time: 57.5220s, Throughput: 86.784203 im/s
Epoch 36, Iter 39, Loss: 9982.6855469, Throughput: 86.612233 im/s
Epoch 36, Train Loss: 9862.2968750, Time: 57.6364s, Throughput: 86.611952 im/s
Epoch 37, Iter 39, Loss: 9530.5410156, Throughput: 86.293768 im/s
Epoch 37, Train Loss: 9782.5976562, Time: 57.8491s, Throughput: 86.293525 im/s
Epoch 38, Iter 39, Loss: 9352.6689453, Throughput: 86.599055 im/s
Epoch 38, Train Loss: 9767.1191406, Time: 57.6452s, Throughput: 86.598772 im/s
Epoch 39, Iter 39, Loss: 10268.3808594, Throughput: 87.963947 im/s
Epoch 39, Train Loss: 9787.1582031, Time: 56.7507s, Throughput: 87.963678 im/s
Epoch 40, Iter 39, Loss: 9810.0097656, Throughput: 86.094821 im/s
Epoch 40, Train Loss: 9702.3769531, Time: 57.9828s, Throughput: 86.094567 im/s
Epoch 41, Iter 39, Loss: 9287.2285156, Throughput: 86.948110 im/s
Epoch 41, Train Loss: 9658.4628906, Time: 57.4137s, Throughput: 86.947874 im/s
Epoch 42, Iter 39, Loss: 9948.9062500, Throughput: 87.813202 im/s
Epoch 42, Train Loss: 9606.8203125, Time: 56.8481s, Throughput: 87.812938 im/s
Epoch 43, Iter 39, Loss: 9487.0615234, Throughput: 85.944451 im/s
Epoch 43, Train Loss: 9641.4072266, Time: 58.0842s, Throughput: 85.944191 im/s
Epoch 44, Iter 39, Loss: 9755.6484375, Throughput: 87.885829 im/s
Epoch 44, Train Loss: 9572.2343750, Time: 56.8011s, Throughput: 87.885574 im/s
Epoch 45, Iter 39, Loss: 9826.5810547, Throughput: 86.344474 im/s
Epoch 45, Train Loss: 9501.3945312, Time: 57.8151s, Throughput: 86.344244 im/s
Epoch 46, Iter 39, Loss: 8972.2246094, Throughput: 85.761549 im/s
Epoch 46, Train Loss: 9569.5869141, Time: 58.2081s, Throughput: 85.761291 im/s
Epoch 47, Iter 39, Loss: 9661.0937500, Throughput: 87.274309 im/s
Epoch 47, Train Loss: 9541.5595703, Time: 57.1991s, Throughput: 87.274053 im/s
Epoch 48, Iter 39, Loss: 10123.0341797, Throughput: 86.989065 im/s
Epoch 48, Train Loss: 9527.8955078, Time: 57.3867s, Throughput: 86.988826 im/s
Epoch 49, Iter 39, Loss: 10252.2089844, Throughput: 86.989766 im/s
Epoch 49, Train Loss: 9398.8779297, Time: 57.3862s, Throughput: 86.989490 im/s
Epoch 50, Iter 39, Loss: 8839.7910156, Throughput: 85.993888 im/s
Epoch 50, Train Loss: 9451.7392578, Time: 58.0508s, Throughput: 85.993637 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.