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: 23915.8164062, Throughput: 6.423346 im/s
Epoch 1, Train Loss: 39603.1328125, Time: 777.4522s, Throughput: 6.420974 im/s
Epoch 2, Iter 39, Loss: 17508.2539062, Throughput: 75.412271 im/s
Epoch 2, Train Loss: 20094.4765625, Time: 66.1963s, Throughput: 75.412057 im/s
Epoch 3, Iter 39, Loss: 16239.1308594, Throughput: 75.672143 im/s
Epoch 3, Train Loss: 16609.8183594, Time: 65.9690s, Throughput: 75.671927 im/s
Epoch 4, Iter 39, Loss: 14510.9912109, Throughput: 75.936355 im/s
Epoch 4, Train Loss: 15002.1230469, Time: 65.7394s, Throughput: 75.936191 im/s
Epoch 5, Iter 39, Loss: 14343.4511719, Throughput: 75.650578 im/s
Epoch 5, Train Loss: 14139.9326172, Time: 65.9878s, Throughput: 75.650384 im/s
Epoch 6, Iter 39, Loss: 13489.1269531, Throughput: 74.606870 im/s
Epoch 6, Train Loss: 13443.4482422, Time: 66.9109s, Throughput: 74.606700 im/s
Epoch 7, Iter 39, Loss: 12564.5488281, Throughput: 75.505226 im/s
Epoch 7, Train Loss: 12908.4580078, Time: 66.1148s, Throughput: 75.505037 im/s
Epoch 8, Iter 39, Loss: 12603.5595703, Throughput: 75.361190 im/s
Epoch 8, Train Loss: 12413.1542969, Time: 66.2411s, Throughput: 75.361017 im/s
Epoch 9, Iter 39, Loss: 11651.9199219, Throughput: 75.996799 im/s
Epoch 9, Train Loss: 12277.8593750, Time: 65.6871s, Throughput: 75.996627 im/s
Epoch 10, Iter 39, Loss: 11499.0537109, Throughput: 75.512919 im/s
Epoch 10, Train Loss: 12054.9570312, Time: 66.1080s, Throughput: 75.512762 im/s
Epoch 11, Iter 39, Loss: 11520.0478516, Throughput: 75.518823 im/s
Epoch 11, Train Loss: 11754.0195312, Time: 66.1029s, Throughput: 75.518667 im/s
Epoch 12, Iter 39, Loss: 11007.5078125, Throughput: 75.353280 im/s
Epoch 12, Train Loss: 11571.0244141, Time: 66.2481s, Throughput: 75.353106 im/s
Epoch 13, Iter 39, Loss: 12163.0029297, Throughput: 75.480232 im/s
Epoch 13, Train Loss: 11409.9570312, Time: 66.1367s, Throughput: 75.480053 im/s
Epoch 14, Iter 39, Loss: 11220.5937500, Throughput: 74.620971 im/s
Epoch 14, Train Loss: 11267.3974609, Time: 66.8982s, Throughput: 74.620803 im/s
Epoch 15, Iter 39, Loss: 11488.7021484, Throughput: 73.879172 im/s
Epoch 15, Train Loss: 11070.4531250, Time: 67.5700s, Throughput: 73.878987 im/s
Epoch 16, Iter 39, Loss: 11513.0810547, Throughput: 74.959419 im/s
Epoch 16, Train Loss: 11019.2001953, Time: 66.5962s, Throughput: 74.959276 im/s
Epoch 17, Iter 39, Loss: 11800.4023438, Throughput: 75.090556 im/s
Epoch 17, Train Loss: 10896.1230469, Time: 66.4799s, Throughput: 75.090393 im/s
Epoch 18, Iter 39, Loss: 11083.2714844, Throughput: 75.017883 im/s
Epoch 18, Train Loss: 10691.9580078, Time: 66.5443s, Throughput: 75.017701 im/s
Epoch 19, Iter 39, Loss: 11154.3027344, Throughput: 74.434867 im/s
Epoch 19, Train Loss: 10702.8857422, Time: 67.0655s, Throughput: 74.434708 im/s
Epoch 20, Iter 39, Loss: 10019.4980469, Throughput: 75.761761 im/s
Epoch 20, Train Loss: 10609.5498047, Time: 65.8909s, Throughput: 75.761586 im/s
Epoch 21, Iter 39, Loss: 10308.1904297, Throughput: 74.935574 im/s
Epoch 21, Train Loss: 10560.3281250, Time: 66.6174s, Throughput: 74.935407 im/s
Epoch 22, Iter 39, Loss: 10832.8984375, Throughput: 75.132431 im/s
Epoch 22, Train Loss: 10468.3408203, Time: 66.4428s, Throughput: 75.132277 im/s
Epoch 23, Iter 39, Loss: 10587.5410156, Throughput: 74.990531 im/s
Epoch 23, Train Loss: 10432.0205078, Time: 66.5686s, Throughput: 74.990359 im/s
Epoch 24, Iter 39, Loss: 10358.1757812, Throughput: 75.100278 im/s
Epoch 24, Train Loss: 10257.4941406, Time: 66.4713s, Throughput: 75.100116 im/s
Epoch 25, Iter 39, Loss: 10192.9453125, Throughput: 75.004468 im/s
Epoch 25, Train Loss: 10212.1718750, Time: 66.5562s, Throughput: 75.004301 im/s
Epoch 26, Iter 39, Loss: 10259.2802734, Throughput: 74.782459 im/s
Epoch 26, Train Loss: 10169.6308594, Time: 66.7538s, Throughput: 74.782287 im/s
Epoch 27, Iter 39, Loss: 10411.4218750, Throughput: 75.959679 im/s
Epoch 27, Train Loss: 10144.5527344, Time: 65.7192s, Throughput: 75.959495 im/s
Epoch 28, Iter 39, Loss: 10827.0429688, Throughput: 75.548950 im/s
Epoch 28, Train Loss: 10124.6318359, Time: 66.0765s, Throughput: 75.548772 im/s
Epoch 29, Iter 39, Loss: 9821.9570312, Throughput: 75.202660 im/s
Epoch 29, Train Loss: 10068.1494141, Time: 66.3808s, Throughput: 75.202457 im/s
Epoch 30, Iter 39, Loss: 10508.6406250, Throughput: 75.700592 im/s
Epoch 30, Train Loss: 9981.8505859, Time: 65.9441s, Throughput: 75.700427 im/s
Epoch 31, Iter 39, Loss: 10122.0000000, Throughput: 75.331210 im/s
Epoch 31, Train Loss: 9919.9169922, Time: 66.2675s, Throughput: 75.331037 im/s
Epoch 32, Iter 39, Loss: 9646.8984375, Throughput: 75.653497 im/s
Epoch 32, Train Loss: 10002.9843750, Time: 65.9852s, Throughput: 75.653329 im/s
Epoch 33, Iter 39, Loss: 9515.7236328, Throughput: 75.607101 im/s
Epoch 33, Train Loss: 9819.1259766, Time: 66.0257s, Throughput: 75.606926 im/s
Epoch 34, Iter 39, Loss: 9429.7714844, Throughput: 75.119270 im/s
Epoch 34, Train Loss: 9796.8291016, Time: 66.4545s, Throughput: 75.119096 im/s
Epoch 35, Iter 39, Loss: 9183.0585938, Throughput: 74.870265 im/s
Epoch 35, Train Loss: 9818.5781250, Time: 66.6755s, Throughput: 74.870091 im/s
Epoch 36, Iter 39, Loss: 10291.2578125, Throughput: 74.279414 im/s
Epoch 36, Train Loss: 9804.3779297, Time: 67.2058s, Throughput: 74.279250 im/s
Epoch 37, Iter 39, Loss: 9712.8886719, Throughput: 74.053901 im/s
Epoch 37, Train Loss: 9760.3281250, Time: 67.4105s, Throughput: 74.053729 im/s
Epoch 38, Iter 39, Loss: 9677.8105469, Throughput: 75.191390 im/s
Epoch 38, Train Loss: 9709.6943359, Time: 66.3907s, Throughput: 75.191221 im/s
Epoch 39, Iter 39, Loss: 10413.5732422, Throughput: 75.595445 im/s
Epoch 39, Train Loss: 9636.8349609, Time: 66.0359s, Throughput: 75.595280 im/s
Epoch 40, Iter 39, Loss: 10031.2519531, Throughput: 75.351561 im/s
Epoch 40, Train Loss: 9641.0615234, Time: 66.2496s, Throughput: 75.351377 im/s
Epoch 41, Iter 39, Loss: 9884.7041016, Throughput: 75.499246 im/s
Epoch 41, Train Loss: 9530.4716797, Time: 66.1200s, Throughput: 75.499085 im/s
Epoch 42, Iter 39, Loss: 10032.5234375, Throughput: 75.301079 im/s
Epoch 42, Train Loss: 9480.6718750, Time: 66.2940s, Throughput: 75.300926 im/s
Epoch 43, Iter 39, Loss: 9225.8125000, Throughput: 74.379583 im/s
Epoch 43, Train Loss: 9509.5644531, Time: 67.1153s, Throughput: 74.379434 im/s
Epoch 44, Iter 39, Loss: 9220.5166016, Throughput: 74.630545 im/s
Epoch 44, Train Loss: 9444.7968750, Time: 66.8897s, Throughput: 74.630377 im/s
Epoch 45, Iter 39, Loss: 9567.8164062, Throughput: 75.098953 im/s
Epoch 45, Train Loss: 9408.1806641, Time: 66.4724s, Throughput: 75.098790 im/s
Epoch 46, Iter 39, Loss: 9540.9882812, Throughput: 75.215465 im/s
Epoch 46, Train Loss: 9380.7431641, Time: 66.3695s, Throughput: 75.215292 im/s
Epoch 47, Iter 39, Loss: 9119.8398438, Throughput: 75.313463 im/s
Epoch 47, Train Loss: 9413.9443359, Time: 66.2831s, Throughput: 75.313291 im/s
Epoch 48, Iter 39, Loss: 9527.5722656, Throughput: 75.020239 im/s
Epoch 48, Train Loss: 9379.7099609, Time: 66.5422s, Throughput: 75.020060 im/s
Epoch 49, Iter 39, Loss: 9459.9980469, Throughput: 74.325339 im/s
Epoch 49, Train Loss: 9348.1777344, Time: 67.1643s, Throughput: 74.325174 im/s
Epoch 50, Iter 39, Loss: 9292.8681641, Throughput: 75.094220 im/s
Epoch 50, Train Loss: 9316.5976562, Time: 66.4766s, Throughput: 75.094057 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.4
Commit 01a2eadb047 (2026-01-06 16:56 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-18.1.7 (ORCJIT, znver3)
  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.