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: 24208.6816406, Throughput: 30.151535 im/s
Epoch 1, Train Loss: 39499.8671875, Time: 165.9146s, Throughput: 30.087766 im/s
Epoch 2, Iter 39, Loss: 17794.3417969, Throughput: 88.305171 im/s
Epoch 2, Train Loss: 20109.8339844, Time: 56.5314s, Throughput: 88.304919 im/s
Epoch 3, Iter 39, Loss: 16543.3847656, Throughput: 90.161806 im/s
Epoch 3, Train Loss: 16525.2128906, Time: 55.3673s, Throughput: 90.161526 im/s
Epoch 4, Iter 39, Loss: 14204.5292969, Throughput: 88.348968 im/s
Epoch 4, Train Loss: 14880.0322266, Time: 56.5034s, Throughput: 88.348610 im/s
Epoch 5, Iter 39, Loss: 13485.8222656, Throughput: 89.440129 im/s
Epoch 5, Train Loss: 13974.3720703, Time: 55.8140s, Throughput: 89.439865 im/s
Epoch 6, Iter 39, Loss: 15335.3554688, Throughput: 88.532161 im/s
Epoch 6, Train Loss: 13313.4306641, Time: 56.3865s, Throughput: 88.531900 im/s
Epoch 7, Iter 39, Loss: 13041.5634766, Throughput: 88.690039 im/s
Epoch 7, Train Loss: 12814.7031250, Time: 56.2861s, Throughput: 88.689797 im/s
Epoch 8, Iter 39, Loss: 12548.4726562, Throughput: 87.913260 im/s
Epoch 8, Train Loss: 12454.7646484, Time: 56.7834s, Throughput: 87.913011 im/s
Epoch 9, Iter 39, Loss: 12400.0800781, Throughput: 88.055199 im/s
Epoch 9, Train Loss: 12099.4316406, Time: 56.6919s, Throughput: 88.054955 im/s
Epoch 10, Iter 39, Loss: 11584.9921875, Throughput: 88.887243 im/s
Epoch 10, Train Loss: 11937.0410156, Time: 56.1612s, Throughput: 88.886990 im/s
Epoch 11, Iter 39, Loss: 11606.3750000, Throughput: 88.281974 im/s
Epoch 11, Train Loss: 11678.0195312, Time: 56.5463s, Throughput: 88.281629 im/s
Epoch 12, Iter 39, Loss: 10999.1376953, Throughput: 87.658603 im/s
Epoch 12, Train Loss: 11493.1660156, Time: 56.9484s, Throughput: 87.658355 im/s
Epoch 13, Iter 39, Loss: 11959.7031250, Throughput: 87.803096 im/s
Epoch 13, Train Loss: 11380.8798828, Time: 56.8547s, Throughput: 87.802772 im/s
Epoch 14, Iter 39, Loss: 11458.4794922, Throughput: 88.123775 im/s
Epoch 14, Train Loss: 11258.5419922, Time: 56.6478s, Throughput: 88.123497 im/s
Epoch 15, Iter 39, Loss: 11094.9511719, Throughput: 88.042637 im/s
Epoch 15, Train Loss: 11064.6376953, Time: 56.7000s, Throughput: 88.042373 im/s
Epoch 16, Iter 39, Loss: 10810.0166016, Throughput: 87.180298 im/s
Epoch 16, Train Loss: 10975.5888672, Time: 57.2608s, Throughput: 87.180022 im/s
Epoch 17, Iter 39, Loss: 10476.3437500, Throughput: 87.288589 im/s
Epoch 17, Train Loss: 10857.1152344, Time: 57.1898s, Throughput: 87.288345 im/s
Epoch 18, Iter 39, Loss: 11056.2441406, Throughput: 89.524932 im/s
Epoch 18, Train Loss: 10681.4267578, Time: 55.7612s, Throughput: 89.524585 im/s
Epoch 19, Iter 39, Loss: 10685.6630859, Throughput: 89.105673 im/s
Epoch 19, Train Loss: 10673.1142578, Time: 56.0235s, Throughput: 89.105447 im/s
Epoch 20, Iter 39, Loss: 10414.9804688, Throughput: 88.161791 im/s
Epoch 20, Train Loss: 10675.3681641, Time: 56.6234s, Throughput: 88.161480 im/s
Epoch 21, Iter 39, Loss: 10222.1582031, Throughput: 87.914232 im/s
Epoch 21, Train Loss: 10583.3623047, Time: 56.7828s, Throughput: 87.913963 im/s
Epoch 22, Iter 39, Loss: 11106.8369141, Throughput: 87.826259 im/s
Epoch 22, Train Loss: 10515.4824219, Time: 56.8397s, Throughput: 87.826000 im/s
Epoch 23, Iter 39, Loss: 10083.8007812, Throughput: 87.916397 im/s
Epoch 23, Train Loss: 10402.7080078, Time: 56.7814s, Throughput: 87.916120 im/s
Epoch 24, Iter 39, Loss: 10165.7851562, Throughput: 87.211751 im/s
Epoch 24, Train Loss: 10297.3984375, Time: 57.2402s, Throughput: 87.211495 im/s
Epoch 25, Iter 39, Loss: 9200.6972656, Throughput: 89.355851 im/s
Epoch 25, Train Loss: 10281.8671875, Time: 55.8667s, Throughput: 89.355565 im/s
Epoch 26, Iter 39, Loss: 10080.0019531, Throughput: 87.857654 im/s
Epoch 26, Train Loss: 10178.9082031, Time: 56.8194s, Throughput: 87.857374 im/s
Epoch 27, Iter 39, Loss: 10140.9218750, Throughput: 86.250362 im/s
Epoch 27, Train Loss: 10135.3701172, Time: 57.8782s, Throughput: 86.250121 im/s
Epoch 28, Iter 39, Loss: 10618.9550781, Throughput: 85.515382 im/s
Epoch 28, Train Loss: 10016.1171875, Time: 58.3756s, Throughput: 85.515135 im/s
Epoch 29, Iter 39, Loss: 10176.5312500, Throughput: 86.968082 im/s
Epoch 29, Train Loss: 10075.1728516, Time: 57.4005s, Throughput: 86.967864 im/s
Epoch 30, Iter 39, Loss: 10070.4003906, Throughput: 86.907397 im/s
Epoch 30, Train Loss: 10025.4238281, Time: 57.4406s, Throughput: 86.907175 im/s
Epoch 31, Iter 39, Loss: 9662.9257812, Throughput: 86.001302 im/s
Epoch 31, Train Loss: 9904.6816406, Time: 58.0458s, Throughput: 86.001044 im/s
Epoch 32, Iter 39, Loss: 9331.5839844, Throughput: 87.769091 im/s
Epoch 32, Train Loss: 9938.0917969, Time: 56.8767s, Throughput: 87.768773 im/s
Epoch 33, Iter 39, Loss: 10068.0214844, Throughput: 87.071034 im/s
Epoch 33, Train Loss: 9860.8330078, Time: 57.3327s, Throughput: 87.070795 im/s
Epoch 34, Iter 39, Loss: 9481.9609375, Throughput: 88.876390 im/s
Epoch 34, Train Loss: 9903.2353516, Time: 56.1681s, Throughput: 88.876102 im/s
Epoch 35, Iter 39, Loss: 10332.1425781, Throughput: 88.397568 im/s
Epoch 35, Train Loss: 9794.6171875, Time: 56.4723s, Throughput: 88.397283 im/s
Epoch 36, Iter 39, Loss: 9192.6767578, Throughput: 87.352446 im/s
Epoch 36, Train Loss: 9767.7529297, Time: 57.1480s, Throughput: 87.352155 im/s
Epoch 37, Iter 39, Loss: 9634.1210938, Throughput: 86.483033 im/s
Epoch 37, Train Loss: 9726.4580078, Time: 57.7225s, Throughput: 86.482796 im/s
Epoch 38, Iter 39, Loss: 9794.1406250, Throughput: 88.005167 im/s
Epoch 38, Train Loss: 9720.1494141, Time: 56.7241s, Throughput: 88.004925 im/s
Epoch 39, Iter 39, Loss: 10461.9121094, Throughput: 87.783448 im/s
Epoch 39, Train Loss: 9682.8251953, Time: 56.8674s, Throughput: 87.783150 im/s
Epoch 40, Iter 39, Loss: 9375.9345703, Throughput: 85.949281 im/s
Epoch 40, Train Loss: 9584.2968750, Time: 58.0809s, Throughput: 85.949032 im/s
Epoch 41, Iter 39, Loss: 9769.8427734, Throughput: 87.191682 im/s
Epoch 41, Train Loss: 9556.0380859, Time: 57.2533s, Throughput: 87.191446 im/s
Epoch 42, Iter 39, Loss: 9416.3339844, Throughput: 86.736990 im/s
Epoch 42, Train Loss: 9584.0136719, Time: 57.5535s, Throughput: 86.736693 im/s
Epoch 43, Iter 39, Loss: 9789.6835938, Throughput: 86.289266 im/s
Epoch 43, Train Loss: 9520.1142578, Time: 57.8521s, Throughput: 86.289013 im/s
Epoch 44, Iter 39, Loss: 8934.1523438, Throughput: 86.972656 im/s
Epoch 44, Train Loss: 9517.0068359, Time: 57.3975s, Throughput: 86.972437 im/s
Epoch 45, Iter 39, Loss: 9238.2050781, Throughput: 87.845036 im/s
Epoch 45, Train Loss: 9466.7148438, Time: 56.8275s, Throughput: 87.844812 im/s
Epoch 46, Iter 39, Loss: 9593.7998047, Throughput: 87.831953 im/s
Epoch 46, Train Loss: 9392.4033203, Time: 56.8360s, Throughput: 87.831648 im/s
Epoch 47, Iter 39, Loss: 9294.5156250, Throughput: 87.002224 im/s
Epoch 47, Train Loss: 9347.0751953, Time: 57.3780s, Throughput: 87.002005 im/s
Epoch 48, Iter 39, Loss: 9585.4394531, Throughput: 87.316002 im/s
Epoch 48, Train Loss: 9382.9804688, Time: 57.1718s, Throughput: 87.315752 im/s
Epoch 49, Iter 39, Loss: 9541.1679688, Throughput: 86.013945 im/s
Epoch 49, Train Loss: 9357.1289062, Time: 58.0373s, Throughput: 86.013721 im/s
Epoch 50, Iter 39, Loss: 8986.6748047, Throughput: 86.535805 im/s
Epoch 50, Train Loss: 9414.0556641, Time: 57.6873s, Throughput: 86.535555 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.