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: 24105.8164062, Throughput: 10.947930 im/s
Epoch 1, Train Loss: 39585.2773438, Time: 456.2995s, Throughput: 10.940183 im/s
Epoch 2, Iter 39, Loss: 18082.8984375, Throughput: 82.699545 im/s
Epoch 2, Train Loss: 19946.3476562, Time: 60.3633s, Throughput: 82.699215 im/s
Epoch 3, Iter 39, Loss: 16205.8867188, Throughput: 83.697036 im/s
Epoch 3, Train Loss: 16594.6230469, Time: 59.6439s, Throughput: 83.696743 im/s
Epoch 4, Iter 39, Loss: 13799.1894531, Throughput: 83.340001 im/s
Epoch 4, Train Loss: 14959.5156250, Time: 59.8994s, Throughput: 83.339727 im/s
Epoch 5, Iter 39, Loss: 13042.5048828, Throughput: 83.343608 im/s
Epoch 5, Train Loss: 13971.4453125, Time: 59.8968s, Throughput: 83.343307 im/s
Epoch 6, Iter 39, Loss: 13434.6757812, Throughput: 83.392634 im/s
Epoch 6, Train Loss: 13391.5322266, Time: 59.8616s, Throughput: 83.392350 im/s
Epoch 7, Iter 39, Loss: 13281.9423828, Throughput: 83.710461 im/s
Epoch 7, Train Loss: 12897.3857422, Time: 59.6343s, Throughput: 83.710174 im/s
Epoch 8, Iter 39, Loss: 12624.3105469, Throughput: 83.215725 im/s
Epoch 8, Train Loss: 12468.8955078, Time: 59.9889s, Throughput: 83.215414 im/s
Epoch 9, Iter 39, Loss: 11300.0849609, Throughput: 84.182756 im/s
Epoch 9, Train Loss: 12245.2744141, Time: 59.2998s, Throughput: 84.182452 im/s
Epoch 10, Iter 39, Loss: 11744.6611328, Throughput: 84.161659 im/s
Epoch 10, Train Loss: 11921.1289062, Time: 59.3146s, Throughput: 84.161341 im/s
Epoch 11, Iter 39, Loss: 12131.6542969, Throughput: 84.036918 im/s
Epoch 11, Train Loss: 11754.1982422, Time: 59.4027s, Throughput: 84.036584 im/s
Epoch 12, Iter 39, Loss: 12180.2539062, Throughput: 84.175795 im/s
Epoch 12, Train Loss: 11537.8730469, Time: 59.3047s, Throughput: 84.175517 im/s
Epoch 13, Iter 39, Loss: 11230.5830078, Throughput: 83.175038 im/s
Epoch 13, Train Loss: 11379.1650391, Time: 60.0182s, Throughput: 83.174747 im/s
Epoch 14, Iter 39, Loss: 11113.9189453, Throughput: 84.212608 im/s
Epoch 14, Train Loss: 11245.1806641, Time: 59.2787s, Throughput: 84.212326 im/s
Epoch 15, Iter 39, Loss: 11493.0937500, Throughput: 82.897810 im/s
Epoch 15, Train Loss: 11049.4423828, Time: 60.2189s, Throughput: 82.897557 im/s
Epoch 16, Iter 39, Loss: 10461.7949219, Throughput: 83.179371 im/s
Epoch 16, Train Loss: 10952.6123047, Time: 60.0151s, Throughput: 83.179112 im/s
Epoch 17, Iter 39, Loss: 10596.8808594, Throughput: 83.552799 im/s
Epoch 17, Train Loss: 10895.8955078, Time: 59.7468s, Throughput: 83.552524 im/s
Epoch 18, Iter 39, Loss: 10986.5703125, Throughput: 83.687990 im/s
Epoch 18, Train Loss: 10750.9443359, Time: 59.6503s, Throughput: 83.687718 im/s
Epoch 19, Iter 39, Loss: 11365.5644531, Throughput: 84.614118 im/s
Epoch 19, Train Loss: 10620.9716797, Time: 58.9975s, Throughput: 84.613822 im/s
Epoch 20, Iter 39, Loss: 10621.5156250, Throughput: 84.023237 im/s
Epoch 20, Train Loss: 10588.4931641, Time: 59.4123s, Throughput: 84.022939 im/s
Epoch 21, Iter 39, Loss: 10053.2148438, Throughput: 84.009482 im/s
Epoch 21, Train Loss: 10514.9443359, Time: 59.4221s, Throughput: 84.009214 im/s
Epoch 22, Iter 39, Loss: 11073.2080078, Throughput: 83.754702 im/s
Epoch 22, Train Loss: 10348.8457031, Time: 59.6028s, Throughput: 83.754435 im/s
Epoch 23, Iter 39, Loss: 10746.5048828, Throughput: 84.155900 im/s
Epoch 23, Train Loss: 10399.0927734, Time: 59.3187s, Throughput: 84.155611 im/s
Epoch 24, Iter 39, Loss: 10436.0722656, Throughput: 84.115622 im/s
Epoch 24, Train Loss: 10359.7294922, Time: 59.3471s, Throughput: 84.115363 im/s
Epoch 25, Iter 39, Loss: 10074.0253906, Throughput: 83.670800 im/s
Epoch 25, Train Loss: 10224.0654297, Time: 59.6626s, Throughput: 83.670511 im/s
Epoch 26, Iter 39, Loss: 10053.7216797, Throughput: 83.492469 im/s
Epoch 26, Train Loss: 10237.4326172, Time: 59.7900s, Throughput: 83.492191 im/s
Epoch 27, Iter 39, Loss: 9544.2988281, Throughput: 83.161632 im/s
Epoch 27, Train Loss: 10128.0371094, Time: 60.0279s, Throughput: 83.161366 im/s
Epoch 28, Iter 39, Loss: 10489.5205078, Throughput: 84.420658 im/s
Epoch 28, Train Loss: 10047.3681641, Time: 59.1326s, Throughput: 84.420377 im/s
Epoch 29, Iter 39, Loss: 9825.6474609, Throughput: 83.812599 im/s
Epoch 29, Train Loss: 9980.2558594, Time: 59.5617s, Throughput: 83.812302 im/s
Epoch 30, Iter 39, Loss: 10163.9335938, Throughput: 84.210254 im/s
Epoch 30, Train Loss: 9913.6513672, Time: 59.2804s, Throughput: 84.209981 im/s
Epoch 31, Iter 39, Loss: 9916.3896484, Throughput: 83.599623 im/s
Epoch 31, Train Loss: 9884.8046875, Time: 59.7134s, Throughput: 83.599321 im/s
Epoch 32, Iter 39, Loss: 10366.9843750, Throughput: 84.053914 im/s
Epoch 32, Train Loss: 9981.4052734, Time: 59.3906s, Throughput: 84.053652 im/s
Epoch 33, Iter 39, Loss: 9639.4033203, Throughput: 84.143229 im/s
Epoch 33, Train Loss: 9911.8398438, Time: 59.3276s, Throughput: 84.142947 im/s
Epoch 34, Iter 39, Loss: 10117.0937500, Throughput: 83.955970 im/s
Epoch 34, Train Loss: 9795.6005859, Time: 59.4599s, Throughput: 83.955698 im/s
Epoch 35, Iter 39, Loss: 9432.5830078, Throughput: 83.825127 im/s
Epoch 35, Train Loss: 9750.6513672, Time: 59.5528s, Throughput: 83.824834 im/s
Epoch 36, Iter 39, Loss: 9656.9707031, Throughput: 84.082213 im/s
Epoch 36, Train Loss: 9660.9453125, Time: 59.3707s, Throughput: 84.081947 im/s
Epoch 37, Iter 39, Loss: 9775.6044922, Throughput: 83.959628 im/s
Epoch 37, Train Loss: 9630.8847656, Time: 59.4574s, Throughput: 83.959328 im/s
Epoch 38, Iter 39, Loss: 9403.2109375, Throughput: 84.447016 im/s
Epoch 38, Train Loss: 9559.5263672, Time: 59.1142s, Throughput: 84.446731 im/s
Epoch 39, Iter 39, Loss: 9224.4062500, Throughput: 83.456223 im/s
Epoch 39, Train Loss: 9587.6054688, Time: 59.8160s, Throughput: 83.455942 im/s
Epoch 40, Iter 39, Loss: 9445.1494141, Throughput: 83.128617 im/s
Epoch 40, Train Loss: 9504.6992188, Time: 60.0517s, Throughput: 83.128338 im/s
Epoch 41, Iter 39, Loss: 9564.5390625, Throughput: 84.193341 im/s
Epoch 41, Train Loss: 9532.4023438, Time: 59.2923s, Throughput: 84.193064 im/s
Epoch 42, Iter 39, Loss: 10397.0917969, Throughput: 83.808953 im/s
Epoch 42, Train Loss: 9438.7724609, Time: 59.5642s, Throughput: 83.808660 im/s
Epoch 43, Iter 39, Loss: 9463.2236328, Throughput: 83.642170 im/s
Epoch 43, Train Loss: 9509.8417969, Time: 59.6830s, Throughput: 83.641921 im/s
Epoch 44, Iter 39, Loss: 9551.9033203, Throughput: 83.469967 im/s
Epoch 44, Train Loss: 9449.2031250, Time: 59.8061s, Throughput: 83.469710 im/s
Epoch 45, Iter 39, Loss: 9370.0664062, Throughput: 83.927592 im/s
Epoch 45, Train Loss: 9478.2968750, Time: 59.4801s, Throughput: 83.927287 im/s
Epoch 46, Iter 39, Loss: 9151.3007812, Throughput: 83.916633 im/s
Epoch 46, Train Loss: 9341.2294922, Time: 59.4878s, Throughput: 83.916363 im/s
Epoch 47, Iter 39, Loss: 9743.4619141, Throughput: 83.751321 im/s
Epoch 47, Train Loss: 9344.9501953, Time: 59.6052s, Throughput: 83.751031 im/s
Epoch 48, Iter 39, Loss: 9034.9531250, Throughput: 83.750784 im/s
Epoch 48, Train Loss: 9364.2724609, Time: 59.6056s, Throughput: 83.750527 im/s
Epoch 49, Iter 39, Loss: 9649.0898438, Throughput: 83.689692 im/s
Epoch 49, Train Loss: 9380.2255859, Time: 59.6491s, Throughput: 83.689399 im/s
Epoch 50, Iter 39, Loss: 9853.7412109, Throughput: 84.015573 im/s
Epoch 50, Train Loss: 9368.7773438, Time: 59.4177s, Throughput: 84.015320 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.12.6
Commit 15346901f00 (2026-04-09 19:20 UTC)
Build Info:
  Official https://julialang.org release
Platform Info:
  OS: Linux (x86_64-linux-gnu)
  CPU: 4 × AMD EPYC 9V74 80-Core Processor
  WORD_SIZE: 64
  LLVM: libLLVM-18.1.7 (ORCJIT, znver4)
  GC: Built with stock GC
Threads: 4 default, 1 interactive, 4 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.