Skip to content

Convolutional VAE for MNIST using Reactant

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()
(::MLDataDevices.CPUDevice) (generic function with 1 method)

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
        rng = Lux.replicate(rng)
        ϵ = randn_like(rng, σ)

        # Reparameterization trick to brackpropagate through sampling
        z = ϵ .* σ .+ μ

        @return z, μ, logσ²
    end
end
cvae_encoder (generic function with 2 methods)

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 <: Lux.AbstractLuxContainerLayer{(:encoder, :decoder)}
    encoder <: Lux.AbstractLuxLayer
    decoder <: Lux.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
decode (generic function with 1 method)

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")) ? 1500 : 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
loadmnist (generic function with 1 method)

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 = size(img, 3) == 1 ? colorview(Gray, view(img, :, :, 1)) :
               colorview(RGB, permutedims(img, (3, 1, 2)))
        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 = randn(Float32, num_latent_dims, num_samples) |> get_device((ps, st))
    if decode_compiled === nothing
        images, _ = decode(model, z, ps, Lux.testmode(st))
    else
        images, _ = decode_compiled(model, z, ps, Lux.testmode(st))
        images = images |> cpu_device()
    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 = recon |> cpu_device()
    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=1e-5, learning_rate=1e-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 = randn(Float32, num_latent_dims, num_samples) |> xdev
    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)/1e6)

    is_vscode = isdefined(Main, :VSCodeServer)
    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 is_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)
            is_vscode && display(model_img_full)
        end
    end

    return model_img_full
end

img = main()
┌ Warning: `training` is set to `Val{false}()` but is being used within an autodiff call (gradient, jacobian, etc...). This might lead to incorrect results. If you are using a `Lux.jl` model, set it to training mode using `LuxCore.trainmode`.
└ @ LuxLib.Utils /var/lib/buildkite-agent/builds/gpuci-2/julialang/lux-dot-jl/lib/LuxLib/src/utils.jl:324
2025-02-05 19:50:33.370034: I external/xla/xla/service/llvm_ir/llvm_command_line_options.cc:51] XLA (re)initializing LLVM with options fingerprint: 10037359582517723836
Total Trainable Parameters: 0.1493 M
Epoch 1, Iter 11, Loss: 62214.4453125, Throughput: 25.227346 im/s
Epoch 1, Train Loss: 77379.1015625, Time: 56.2268s, Throughput: 25.041430 im/s
Epoch 2, Iter 11, Loss: 51389.0937500, Throughput: 1799.083040 im/s
Epoch 2, Train Loss: 55760.8984375, Time: 0.7830s, Throughput: 1798.269517 im/s
Epoch 3, Iter 11, Loss: 50964.7031250, Throughput: 1793.820518 im/s
Epoch 3, Train Loss: 49938.4765625, Time: 0.7854s, Throughput: 1792.748848 im/s
Epoch 4, Iter 11, Loss: 49395.6367188, Throughput: 1824.526529 im/s
Epoch 4, Train Loss: 50370.9140625, Time: 0.7720s, Throughput: 1823.768122 im/s
Epoch 5, Iter 11, Loss: 51547.4531250, Throughput: 1827.676202 im/s
Epoch 5, Train Loss: 50635.4726562, Time: 0.7707s, Throughput: 1826.867702 im/s
Epoch 6, Iter 11, Loss: 50681.3046875, Throughput: 1791.050308 im/s
Epoch 6, Train Loss: 51684.3007812, Time: 0.7864s, Throughput: 1790.385146 im/s
Epoch 7, Iter 11, Loss: 52420.0117188, Throughput: 1818.254601 im/s
Epoch 7, Train Loss: 52001.0468750, Time: 0.7747s, Throughput: 1817.482381 im/s
Epoch 8, Iter 11, Loss: 52750.8750000, Throughput: 1829.978402 im/s
Epoch 8, Train Loss: 52594.3750000, Time: 0.7698s, Throughput: 1829.162766 im/s
Epoch 9, Iter 11, Loss: 50628.5507812, Throughput: 1831.845367 im/s
Epoch 9, Train Loss: 51856.0625000, Time: 0.7690s, Throughput: 1830.946887 im/s
Epoch 10, Iter 11, Loss: 52825.9140625, Throughput: 1797.275662 im/s
Epoch 10, Train Loss: 52482.5898438, Time: 0.7838s, Throughput: 1796.432077 im/s
Epoch 11, Iter 11, Loss: 55256.0273438, Throughput: 1778.783808 im/s
Epoch 11, Train Loss: 53789.1914062, Time: 0.7919s, Throughput: 1777.984254 im/s
Epoch 12, Iter 11, Loss: 55019.2343750, Throughput: 1831.306287 im/s
Epoch 12, Train Loss: 54669.4531250, Time: 0.7692s, Throughput: 1830.539397 im/s
Epoch 13, Iter 11, Loss: 56518.6093750, Throughput: 1827.363459 im/s
Epoch 13, Train Loss: 55116.2226562, Time: 0.7709s, Throughput: 1826.488576 im/s
Epoch 14, Iter 11, Loss: 54920.6132812, Throughput: 1817.201075 im/s
Epoch 14, Train Loss: 54499.0742188, Time: 0.7752s, Throughput: 1816.296231 im/s
Epoch 15, Iter 11, Loss: 50421.9492188, Throughput: 1830.908854 im/s
Epoch 15, Train Loss: 53236.0976562, Time: 0.7694s, Throughput: 1830.057227 im/s
Epoch 16, Iter 11, Loss: 51916.3125000, Throughput: 1785.293118 im/s
Epoch 16, Train Loss: 51800.6132812, Time: 0.7889s, Throughput: 1784.729844 im/s
Epoch 17, Iter 11, Loss: 48918.2304688, Throughput: 1771.177903 im/s
Epoch 17, Train Loss: 50944.4023438, Time: 0.7952s, Throughput: 1770.683489 im/s
Epoch 18, Iter 11, Loss: 53824.6406250, Throughput: 1798.356586 im/s
Epoch 18, Train Loss: 51046.2500000, Time: 0.7832s, Throughput: 1797.647134 im/s
Epoch 19, Iter 11, Loss: 50470.6171875, Throughput: 1778.937054 im/s
Epoch 19, Train Loss: 51326.2617188, Time: 0.7918s, Throughput: 1778.166272 im/s
Epoch 20, Iter 11, Loss: 52985.1054688, Throughput: 1775.117027 im/s
Epoch 20, Train Loss: 51757.1367188, Time: 0.7934s, Throughput: 1774.586816 im/s
Epoch 21, Iter 11, Loss: 49223.8906250, Throughput: 1819.448357 im/s
Epoch 21, Train Loss: 50931.8007812, Time: 0.7743s, Throughput: 1818.456718 im/s
Epoch 22, Iter 11, Loss: 50523.8867188, Throughput: 1802.939321 im/s
Epoch 22, Train Loss: 50634.7890625, Time: 0.7812s, Throughput: 1802.396764 im/s
Epoch 23, Iter 11, Loss: 49557.5429688, Throughput: 1635.651437 im/s
Epoch 23, Train Loss: 50516.9218750, Time: 0.8613s, Throughput: 1634.650871 im/s
Epoch 24, Iter 11, Loss: 49213.4921875, Throughput: 1796.654514 im/s
Epoch 24, Train Loss: 50548.8359375, Time: 0.7840s, Throughput: 1795.843186 im/s
Epoch 25, Iter 11, Loss: 49222.9960938, Throughput: 1829.034734 im/s
Epoch 25, Train Loss: 50100.3750000, Time: 0.7701s, Throughput: 1828.407294 im/s
Epoch 26, Iter 11, Loss: 51265.9843750, Throughput: 1810.012981 im/s
Epoch 26, Train Loss: 50469.0039062, Time: 0.7782s, Throughput: 1809.329227 im/s
Epoch 27, Iter 11, Loss: 50290.8203125, Throughput: 1830.249498 im/s
Epoch 27, Train Loss: 50835.5039062, Time: 0.7696s, Throughput: 1829.516932 im/s
Epoch 28, Iter 11, Loss: 47262.8242188, Throughput: 1793.909336 im/s
Epoch 28, Train Loss: 50593.3750000, Time: 0.7852s, Throughput: 1793.276355 im/s
Epoch 29, Iter 11, Loss: 48089.9453125, Throughput: 1703.470132 im/s
Epoch 29, Train Loss: 50083.4960938, Time: 0.8268s, Throughput: 1703.041767 im/s
Epoch 30, Iter 11, Loss: 48890.6484375, Throughput: 1783.978825 im/s
Epoch 30, Train Loss: 49610.8789062, Time: 0.7896s, Throughput: 1783.253746 im/s
Epoch 31, Iter 11, Loss: 50286.9296875, Throughput: 1802.359908 im/s
Epoch 31, Train Loss: 49557.6757812, Time: 0.7815s, Throughput: 1801.596180 im/s
Epoch 32, Iter 11, Loss: 49488.7929688, Throughput: 1795.508487 im/s
Epoch 32, Train Loss: 49139.5585938, Time: 0.7845s, Throughput: 1794.785462 im/s
Epoch 33, Iter 11, Loss: 46463.5820312, Throughput: 1826.112430 im/s
Epoch 33, Train Loss: 48826.3007812, Time: 0.7714s, Throughput: 1825.347626 im/s
Epoch 34, Iter 11, Loss: 48981.5156250, Throughput: 1819.490399 im/s
Epoch 34, Train Loss: 48617.1132812, Time: 0.7742s, Throughput: 1818.752416 im/s
Epoch 35, Iter 11, Loss: 48749.2265625, Throughput: 1816.882404 im/s
Epoch 35, Train Loss: 48669.3750000, Time: 0.7753s, Throughput: 1815.984578 im/s
Epoch 36, Iter 11, Loss: 46606.2968750, Throughput: 1805.329688 im/s
Epoch 36, Train Loss: 48774.8164062, Time: 0.7801s, Throughput: 1804.816027 im/s
Epoch 37, Iter 11, Loss: 49104.4882812, Throughput: 1826.472194 im/s
Epoch 37, Train Loss: 48506.1210938, Time: 0.7712s, Throughput: 1825.645570 im/s
Epoch 38, Iter 11, Loss: 47323.9687500, Throughput: 1804.364401 im/s
Epoch 38, Train Loss: 48387.1523438, Time: 0.7806s, Throughput: 1803.816578 im/s
Epoch 39, Iter 11, Loss: 49174.3906250, Throughput: 1829.854792 im/s
Epoch 39, Train Loss: 48223.0859375, Time: 0.7697s, Throughput: 1829.196194 im/s
Epoch 40, Iter 11, Loss: 49201.2812500, Throughput: 1830.496843 im/s
Epoch 40, Train Loss: 49422.0000000, Time: 0.7694s, Throughput: 1829.923399 im/s
Epoch 41, Iter 11, Loss: 48727.5898438, Throughput: 1819.140105 im/s
Epoch 41, Train Loss: 49821.6015625, Time: 0.7743s, Throughput: 1818.514954 im/s
Epoch 42, Iter 11, Loss: 49570.2734375, Throughput: 1802.184452 im/s
Epoch 42, Train Loss: 49842.2773438, Time: 0.7816s, Throughput: 1801.444501 im/s
Epoch 43, Iter 11, Loss: 50112.1445312, Throughput: 1810.517948 im/s
Epoch 43, Train Loss: 50188.3750000, Time: 0.7780s, Throughput: 1809.801089 im/s
Epoch 44, Iter 11, Loss: 52497.2304688, Throughput: 1834.647553 im/s
Epoch 44, Train Loss: 50962.6210938, Time: 0.7677s, Throughput: 1833.949620 im/s
Epoch 45, Iter 11, Loss: 53062.3398438, Throughput: 1833.572103 im/s
Epoch 45, Train Loss: 51465.4843750, Time: 0.7682s, Throughput: 1832.791939 im/s
Epoch 46, Iter 11, Loss: 53706.3671875, Throughput: 1818.303867 im/s
Epoch 46, Train Loss: 52488.9101562, Time: 0.7747s, Throughput: 1817.388416 im/s
Epoch 47, Iter 11, Loss: 53440.9492188, Throughput: 1828.650178 im/s
Epoch 47, Train Loss: 52539.5898438, Time: 0.7703s, Throughput: 1827.843079 im/s
Epoch 48, Iter 11, Loss: 53608.4062500, Throughput: 1829.010942 im/s
Epoch 48, Train Loss: 53809.5468750, Time: 0.7702s, Throughput: 1828.072798 im/s
Epoch 49, Iter 11, Loss: 55261.7617188, Throughput: 1783.954036 im/s
Epoch 49, Train Loss: 53523.3359375, Time: 0.7896s, Throughput: 1783.147135 im/s
Epoch 50, Iter 11, Loss: 53826.8085938, Throughput: 1799.354378 im/s
Epoch 50, Train Loss: 51842.9492188, Time: 0.7828s, Throughput: 1798.719739 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.3
Commit d63adeda50d (2025-01-21 19:42 UTC)
Build Info:
  Official https://julialang.org/ release
Platform Info:
  OS: Linux (x86_64-linux-gnu)
  CPU: 48 × AMD EPYC 7402 24-Core Processor
  WORD_SIZE: 64
  LLVM: libLLVM-16.0.6 (ORCJIT, znver2)
Threads: 48 default, 0 interactive, 24 GC (on 2 virtual cores)
Environment:
  JULIA_CPU_THREADS = 2
  JULIA_DEPOT_PATH = /root/.cache/julia-buildkite-plugin/depots/01872db4-8c79-43af-ab7d-12abac4f24f6
  LD_LIBRARY_PATH = /usr/local/nvidia/lib:/usr/local/nvidia/lib64
  JULIA_PKG_SERVER = 
  JULIA_NUM_THREADS = 48
  JULIA_CUDA_HARD_MEMORY_LIMIT = 100%
  JULIA_PKG_PRECOMPILE_AUTO = 0
  JULIA_DEBUG = Literate

This page was generated using Literate.jl.