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: 23666.5351562, Throughput: 5.949670 im/s
Epoch 1, Train Loss: 39691.4414062, Time: 839.3400s, Throughput: 5.947530 im/s
Epoch 2, Iter 39, Loss: 17671.1347656, Throughput: 65.655160 im/s
Epoch 2, Train Loss: 20133.4531250, Time: 76.0338s, Throughput: 65.655029 im/s
Epoch 3, Iter 39, Loss: 16001.2607422, Throughput: 65.855053 im/s
Epoch 3, Train Loss: 16503.3691406, Time: 75.8030s, Throughput: 65.854892 im/s
Epoch 4, Iter 39, Loss: 14153.6455078, Throughput: 66.186950 im/s
Epoch 4, Train Loss: 14860.5595703, Time: 75.4229s, Throughput: 66.186815 im/s
Epoch 5, Iter 39, Loss: 13883.9042969, Throughput: 65.683407 im/s
Epoch 5, Train Loss: 13948.9248047, Time: 76.0011s, Throughput: 65.683239 im/s
Epoch 6, Iter 39, Loss: 13429.6015625, Throughput: 65.792292 im/s
Epoch 6, Train Loss: 13355.9765625, Time: 75.8753s, Throughput: 65.792153 im/s
Epoch 7, Iter 39, Loss: 12749.7304688, Throughput: 66.299752 im/s
Epoch 7, Train Loss: 12952.4433594, Time: 75.2946s, Throughput: 66.299593 im/s
Epoch 8, Iter 39, Loss: 12065.7578125, Throughput: 65.991197 im/s
Epoch 8, Train Loss: 12490.1777344, Time: 75.6466s, Throughput: 65.991062 im/s
Epoch 9, Iter 39, Loss: 11913.8876953, Throughput: 65.073283 im/s
Epoch 9, Train Loss: 12231.4082031, Time: 76.7137s, Throughput: 65.073163 im/s
Epoch 10, Iter 39, Loss: 11321.3027344, Throughput: 65.522009 im/s
Epoch 10, Train Loss: 11974.0781250, Time: 76.1883s, Throughput: 65.521868 im/s
Epoch 11, Iter 39, Loss: 12175.6035156, Throughput: 65.248146 im/s
Epoch 11, Train Loss: 11786.8955078, Time: 76.5081s, Throughput: 65.248005 im/s
Epoch 12, Iter 39, Loss: 11434.6445312, Throughput: 65.436755 im/s
Epoch 12, Train Loss: 11536.3759766, Time: 76.2876s, Throughput: 65.436622 im/s
Epoch 13, Iter 39, Loss: 11295.9345703, Throughput: 65.376607 im/s
Epoch 13, Train Loss: 11456.7207031, Time: 76.3577s, Throughput: 65.376475 im/s
Epoch 14, Iter 39, Loss: 12050.8593750, Throughput: 65.596998 im/s
Epoch 14, Train Loss: 11227.0146484, Time: 76.1012s, Throughput: 65.596861 im/s
Epoch 15, Iter 39, Loss: 11011.0351562, Throughput: 64.693413 im/s
Epoch 15, Train Loss: 11067.4267578, Time: 77.1641s, Throughput: 64.693284 im/s
Epoch 16, Iter 39, Loss: 10928.9628906, Throughput: 65.023709 im/s
Epoch 16, Train Loss: 11000.6933594, Time: 76.7722s, Throughput: 65.023566 im/s
Epoch 17, Iter 39, Loss: 10857.2363281, Throughput: 65.239034 im/s
Epoch 17, Train Loss: 10829.0000000, Time: 76.5188s, Throughput: 65.238909 im/s
Epoch 18, Iter 39, Loss: 11398.5957031, Throughput: 65.245746 im/s
Epoch 18, Train Loss: 10736.1943359, Time: 76.5109s, Throughput: 65.245614 im/s
Epoch 19, Iter 39, Loss: 10379.0996094, Throughput: 65.891688 im/s
Epoch 19, Train Loss: 10710.8525391, Time: 75.7609s, Throughput: 65.891545 im/s
Epoch 20, Iter 39, Loss: 11346.8027344, Throughput: 65.470992 im/s
Epoch 20, Train Loss: 10588.5830078, Time: 76.2477s, Throughput: 65.470838 im/s
Epoch 21, Iter 39, Loss: 9879.8730469, Throughput: 65.831249 im/s
Epoch 21, Train Loss: 10588.7382812, Time: 75.8304s, Throughput: 65.831122 im/s
Epoch 22, Iter 39, Loss: 10350.1796875, Throughput: 65.447363 im/s
Epoch 22, Train Loss: 10496.0742188, Time: 76.2752s, Throughput: 65.447228 im/s
Epoch 23, Iter 39, Loss: 9886.3896484, Throughput: 65.211785 im/s
Epoch 23, Train Loss: 10403.1503906, Time: 76.5507s, Throughput: 65.211648 im/s
Epoch 24, Iter 39, Loss: 9761.3388672, Throughput: 65.106301 im/s
Epoch 24, Train Loss: 10241.6806641, Time: 76.6748s, Throughput: 65.106161 im/s
Epoch 25, Iter 39, Loss: 10484.1035156, Throughput: 65.629724 im/s
Epoch 25, Train Loss: 10196.1904297, Time: 76.0632s, Throughput: 65.629592 im/s
Epoch 26, Iter 39, Loss: 9982.5791016, Throughput: 65.062620 im/s
Epoch 26, Train Loss: 10154.6054688, Time: 76.7262s, Throughput: 65.062491 im/s
Epoch 27, Iter 39, Loss: 10876.3320312, Throughput: 64.611409 im/s
Epoch 27, Train Loss: 10086.8671875, Time: 77.2621s, Throughput: 64.611273 im/s
Epoch 28, Iter 39, Loss: 10776.7548828, Throughput: 65.476166 im/s
Epoch 28, Train Loss: 10129.7744141, Time: 76.2416s, Throughput: 65.476040 im/s
Epoch 29, Iter 39, Loss: 10019.6201172, Throughput: 65.575829 im/s
Epoch 29, Train Loss: 10079.6191406, Time: 76.1258s, Throughput: 65.575696 im/s
Epoch 30, Iter 39, Loss: 10307.1718750, Throughput: 65.479970 im/s
Epoch 30, Train Loss: 9932.4599609, Time: 76.2372s, Throughput: 65.479830 im/s
Epoch 31, Iter 39, Loss: 9838.8535156, Throughput: 65.095675 im/s
Epoch 31, Train Loss: 9943.8769531, Time: 76.6873s, Throughput: 65.095551 im/s
Epoch 32, Iter 39, Loss: 10068.3291016, Throughput: 65.284827 im/s
Epoch 32, Train Loss: 9892.6669922, Time: 76.4651s, Throughput: 65.284693 im/s
Epoch 33, Iter 39, Loss: 9884.2773438, Throughput: 65.252975 im/s
Epoch 33, Train Loss: 9872.0087891, Time: 76.5024s, Throughput: 65.252835 im/s
Epoch 34, Iter 39, Loss: 9656.4492188, Throughput: 65.886224 im/s
Epoch 34, Train Loss: 9836.5361328, Time: 75.7671s, Throughput: 65.886074 im/s
Epoch 35, Iter 39, Loss: 9531.6484375, Throughput: 65.691201 im/s
Epoch 35, Train Loss: 9759.9687500, Time: 75.9921s, Throughput: 65.691067 im/s
Epoch 36, Iter 39, Loss: 10065.9541016, Throughput: 64.853018 im/s
Epoch 36, Train Loss: 9726.0849609, Time: 76.9742s, Throughput: 64.852879 im/s
Epoch 37, Iter 39, Loss: 9771.5849609, Throughput: 66.320704 im/s
Epoch 37, Train Loss: 9665.3066406, Time: 75.2708s, Throughput: 66.320562 im/s
Epoch 38, Iter 39, Loss: 9758.2167969, Throughput: 66.243575 im/s
Epoch 38, Train Loss: 9643.6123047, Time: 75.3584s, Throughput: 66.243427 im/s
Epoch 39, Iter 39, Loss: 9856.9550781, Throughput: 65.941873 im/s
Epoch 39, Train Loss: 9590.4931641, Time: 75.7032s, Throughput: 65.941732 im/s
Epoch 40, Iter 39, Loss: 9921.5332031, Throughput: 65.644742 im/s
Epoch 40, Train Loss: 9655.9863281, Time: 76.0459s, Throughput: 65.644592 im/s
Epoch 41, Iter 39, Loss: 9956.2548828, Throughput: 65.734744 im/s
Epoch 41, Train Loss: 9550.7968750, Time: 75.9417s, Throughput: 65.734621 im/s
Epoch 42, Iter 39, Loss: 9312.4990234, Throughput: 66.438763 im/s
Epoch 42, Train Loss: 9515.3271484, Time: 75.1370s, Throughput: 66.438610 im/s
Epoch 43, Iter 39, Loss: 9660.9033203, Throughput: 65.464505 im/s
Epoch 43, Train Loss: 9466.9003906, Time: 76.2552s, Throughput: 65.464372 im/s
Epoch 44, Iter 39, Loss: 9309.7519531, Throughput: 64.962213 im/s
Epoch 44, Train Loss: 9459.7148438, Time: 76.8448s, Throughput: 64.962081 im/s
Epoch 45, Iter 39, Loss: 9445.0371094, Throughput: 64.934295 im/s
Epoch 45, Train Loss: 9420.3330078, Time: 76.8779s, Throughput: 64.934143 im/s
Epoch 46, Iter 39, Loss: 9658.5722656, Throughput: 66.027920 im/s
Epoch 46, Train Loss: 9381.1533203, Time: 75.6045s, Throughput: 66.027776 im/s
Epoch 47, Iter 39, Loss: 8785.7089844, Throughput: 65.575276 im/s
Epoch 47, Train Loss: 9355.6259766, Time: 76.1264s, Throughput: 65.575127 im/s
Epoch 48, Iter 39, Loss: 8967.7675781, Throughput: 65.921014 im/s
Epoch 48, Train Loss: 9403.3125000, Time: 75.7271s, Throughput: 65.920876 im/s
Epoch 49, Iter 39, Loss: 9725.5703125, Throughput: 65.919367 im/s
Epoch 49, Train Loss: 9339.4980469, Time: 75.7291s, Throughput: 65.919214 im/s
Epoch 50, Iter 39, Loss: 9610.0214844, Throughput: 65.869121 im/s
Epoch 50, Train Loss: 9343.7451172, Time: 75.7868s, Throughput: 65.868989 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.