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: 24103.2246094, Throughput: 4.256182 im/s
Epoch 1, Train Loss: 39669.5820312, Time: 1173.1682s, Throughput: 4.255144 im/s
Epoch 2, Iter 39, Loss: 17992.7597656, Throughput: 70.610926 im/s
Epoch 2, Train Loss: 20113.4687500, Time: 70.6975s, Throughput: 70.610694 im/s
Epoch 3, Iter 39, Loss: 17049.8847656, Throughput: 70.390551 im/s
Epoch 3, Train Loss: 16843.8632812, Time: 70.9188s, Throughput: 70.390352 im/s
Epoch 4, Iter 39, Loss: 15357.3564453, Throughput: 70.546175 im/s
Epoch 4, Train Loss: 15247.3330078, Time: 70.7624s, Throughput: 70.545984 im/s
Epoch 5, Iter 39, Loss: 14778.0947266, Throughput: 70.381460 im/s
Epoch 5, Train Loss: 14302.2373047, Time: 70.9279s, Throughput: 70.381282 im/s
Epoch 6, Iter 39, Loss: 13817.2998047, Throughput: 70.710553 im/s
Epoch 6, Train Loss: 13646.4453125, Time: 70.5979s, Throughput: 70.710357 im/s
Epoch 7, Iter 39, Loss: 13233.8574219, Throughput: 70.273477 im/s
Epoch 7, Train Loss: 13053.5761719, Time: 71.0370s, Throughput: 70.273266 im/s
Epoch 8, Iter 39, Loss: 12012.6992188, Throughput: 70.409789 im/s
Epoch 8, Train Loss: 12668.7714844, Time: 70.8994s, Throughput: 70.409619 im/s
Epoch 9, Iter 39, Loss: 11801.4785156, Throughput: 70.193224 im/s
Epoch 9, Train Loss: 12324.0761719, Time: 71.1182s, Throughput: 70.193045 im/s
Epoch 10, Iter 39, Loss: 11626.4316406, Throughput: 70.482906 im/s
Epoch 10, Train Loss: 12034.8144531, Time: 70.8259s, Throughput: 70.482716 im/s
Epoch 11, Iter 39, Loss: 11972.6298828, Throughput: 70.172560 im/s
Epoch 11, Train Loss: 11832.1582031, Time: 71.1391s, Throughput: 70.172385 im/s
Epoch 12, Iter 39, Loss: 11322.0195312, Throughput: 70.225251 im/s
Epoch 12, Train Loss: 11712.0419922, Time: 71.0857s, Throughput: 70.225064 im/s
Epoch 13, Iter 39, Loss: 11445.9140625, Throughput: 70.384589 im/s
Epoch 13, Train Loss: 11552.6660156, Time: 70.9248s, Throughput: 70.384414 im/s
Epoch 14, Iter 39, Loss: 11222.8554688, Throughput: 70.557438 im/s
Epoch 14, Train Loss: 11358.8320312, Time: 70.7510s, Throughput: 70.557269 im/s
Epoch 15, Iter 39, Loss: 10535.9882812, Throughput: 70.444420 im/s
Epoch 15, Train Loss: 11192.4101562, Time: 70.8645s, Throughput: 70.444250 im/s
Epoch 16, Iter 39, Loss: 11169.4785156, Throughput: 70.639672 im/s
Epoch 16, Train Loss: 11089.0039062, Time: 70.6687s, Throughput: 70.639487 im/s
Epoch 17, Iter 39, Loss: 10504.7373047, Throughput: 70.567541 im/s
Epoch 17, Train Loss: 10940.9794922, Time: 70.7409s, Throughput: 70.567378 im/s
Epoch 18, Iter 39, Loss: 11127.7392578, Throughput: 70.371274 im/s
Epoch 18, Train Loss: 10797.5068359, Time: 70.9382s, Throughput: 70.371120 im/s
Epoch 19, Iter 39, Loss: 10484.2802734, Throughput: 70.070207 im/s
Epoch 19, Train Loss: 10758.7529297, Time: 71.2430s, Throughput: 70.070040 im/s
Epoch 20, Iter 39, Loss: 10749.1435547, Throughput: 70.292152 im/s
Epoch 20, Train Loss: 10640.7226562, Time: 71.0180s, Throughput: 70.291996 im/s
Epoch 21, Iter 39, Loss: 11088.7988281, Throughput: 70.792346 im/s
Epoch 21, Train Loss: 10686.0205078, Time: 70.5163s, Throughput: 70.792179 im/s
Epoch 22, Iter 39, Loss: 11372.0517578, Throughput: 70.544159 im/s
Epoch 22, Train Loss: 10509.5781250, Time: 70.7644s, Throughput: 70.543987 im/s
Epoch 23, Iter 39, Loss: 9910.3281250, Throughput: 70.634507 im/s
Epoch 23, Train Loss: 10446.5654297, Time: 70.6738s, Throughput: 70.634332 im/s
Epoch 24, Iter 39, Loss: 10622.8222656, Throughput: 70.614602 im/s
Epoch 24, Train Loss: 10393.3789062, Time: 70.6938s, Throughput: 70.614443 im/s
Epoch 25, Iter 39, Loss: 10515.2597656, Throughput: 70.677372 im/s
Epoch 25, Train Loss: 10300.9619141, Time: 70.6310s, Throughput: 70.677195 im/s
Epoch 26, Iter 39, Loss: 10333.3652344, Throughput: 70.580372 im/s
Epoch 26, Train Loss: 10322.0048828, Time: 70.7280s, Throughput: 70.580202 im/s
Epoch 27, Iter 39, Loss: 10259.3408203, Throughput: 70.491554 im/s
Epoch 27, Train Loss: 10225.8173828, Time: 70.8172s, Throughput: 70.491384 im/s
Epoch 28, Iter 39, Loss: 9915.3710938, Throughput: 70.640358 im/s
Epoch 28, Train Loss: 10126.9326172, Time: 70.6680s, Throughput: 70.640164 im/s
Epoch 29, Iter 39, Loss: 9643.7441406, Throughput: 69.679248 im/s
Epoch 29, Train Loss: 10150.8955078, Time: 71.6427s, Throughput: 69.679078 im/s
Epoch 30, Iter 39, Loss: 10249.1406250, Throughput: 69.758139 im/s
Epoch 30, Train Loss: 10141.6298828, Time: 71.5617s, Throughput: 69.757956 im/s
Epoch 31, Iter 39, Loss: 10328.5605469, Throughput: 70.017735 im/s
Epoch 31, Train Loss: 10008.3974609, Time: 71.2964s, Throughput: 70.017542 im/s
Epoch 32, Iter 39, Loss: 10493.3261719, Throughput: 70.319464 im/s
Epoch 32, Train Loss: 9955.7968750, Time: 70.9905s, Throughput: 70.319279 im/s
Epoch 33, Iter 39, Loss: 10159.3525391, Throughput: 70.623498 im/s
Epoch 33, Train Loss: 9992.3769531, Time: 70.6849s, Throughput: 70.623326 im/s
Epoch 34, Iter 39, Loss: 10598.3896484, Throughput: 70.386652 im/s
Epoch 34, Train Loss: 9853.7080078, Time: 70.9227s, Throughput: 70.386478 im/s
Epoch 35, Iter 39, Loss: 9924.6357422, Throughput: 70.345673 im/s
Epoch 35, Train Loss: 9818.8955078, Time: 70.9640s, Throughput: 70.345507 im/s
Epoch 36, Iter 39, Loss: 9567.5712891, Throughput: 70.399828 im/s
Epoch 36, Train Loss: 9835.0371094, Time: 70.9094s, Throughput: 70.399659 im/s
Epoch 37, Iter 39, Loss: 10216.3789062, Throughput: 70.481635 im/s
Epoch 37, Train Loss: 9797.8857422, Time: 70.8271s, Throughput: 70.481460 im/s
Epoch 38, Iter 39, Loss: 9814.8027344, Throughput: 70.500596 im/s
Epoch 38, Train Loss: 9747.6289062, Time: 70.8081s, Throughput: 70.500428 im/s
Epoch 39, Iter 39, Loss: 9174.5478516, Throughput: 70.230434 im/s
Epoch 39, Train Loss: 9700.7470703, Time: 71.0805s, Throughput: 70.230244 im/s
Epoch 40, Iter 39, Loss: 9148.4550781, Throughput: 70.767968 im/s
Epoch 40, Train Loss: 9661.7841797, Time: 70.5406s, Throughput: 70.767793 im/s
Epoch 41, Iter 39, Loss: 9324.3789062, Throughput: 70.247796 im/s
Epoch 41, Train Loss: 9605.0195312, Time: 71.0629s, Throughput: 70.247624 im/s
Epoch 42, Iter 39, Loss: 9687.5000000, Throughput: 70.646067 im/s
Epoch 42, Train Loss: 9606.8154297, Time: 70.6623s, Throughput: 70.645903 im/s
Epoch 43, Iter 39, Loss: 9596.2822266, Throughput: 70.617417 im/s
Epoch 43, Train Loss: 9616.5888672, Time: 70.6909s, Throughput: 70.617243 im/s
Epoch 44, Iter 39, Loss: 9995.4726562, Throughput: 70.290561 im/s
Epoch 44, Train Loss: 9624.6884766, Time: 71.0197s, Throughput: 70.290393 im/s
Epoch 45, Iter 39, Loss: 9040.1591797, Throughput: 70.316502 im/s
Epoch 45, Train Loss: 9469.7207031, Time: 70.9935s, Throughput: 70.316305 im/s
Epoch 46, Iter 39, Loss: 9227.1953125, Throughput: 70.404540 im/s
Epoch 46, Train Loss: 9469.8623047, Time: 70.9047s, Throughput: 70.404368 im/s
Epoch 47, Iter 39, Loss: 9623.4433594, Throughput: 70.428206 im/s
Epoch 47, Train Loss: 9490.9804688, Time: 70.8809s, Throughput: 70.428031 im/s
Epoch 48, Iter 39, Loss: 10132.0742188, Throughput: 70.465284 im/s
Epoch 48, Train Loss: 9429.9433594, Time: 70.8436s, Throughput: 70.465103 im/s
Epoch 49, Iter 39, Loss: 8938.2421875, Throughput: 70.525546 im/s
Epoch 49, Train Loss: 9408.6425781, Time: 70.7830s, Throughput: 70.525369 im/s
Epoch 50, Iter 39, Loss: 9478.2519531, Throughput: 70.642495 im/s
Epoch 50, Train Loss: 9351.7119141, Time: 70.6659s, Throughput: 70.642324 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 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.