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 = xdev(Lux.setup(rng, cvae))
z = xdev(randn(Float32, num_latent_dims, num_samples))
decode_compiled = Reactant.with_config(;
dot_general_precision=PrecisionConfig.HIGH,
convolution_precision=PrecisionConfig.HIGH,
) do
@compile decode(cvae, z, ps, Lux.testmode(st))
end
x = xdev(randn(Float32, image_size..., 1, batchsize))
cvae_compiled = Reactant.with_config(;
dot_general_precision=PrecisionConfig.HIGH,
convolution_precision=PrecisionConfig.HIGH,
) do
@compile cvae(x, ps, Lux.testmode(st))
end
train_dataloader = xdev(loadmnist(batchsize, image_size))
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()
WARNING: All log messages before absl::InitializeLog() is called are written to STDERR
I0000 00:00:1757736070.856216 624082 service.cc:163] XLA service 0x38f0a1b0 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:
I0000 00:00:1757736070.856325 624082 service.cc:171] StreamExecutor device (0): NVIDIA A100-PCIE-40GB MIG 1g.5gb, Compute Capability 8.0
I0000 00:00:1757736070.857021 624082 se_gpu_pjrt_client.cc:1338] Using BFC allocator.
I0000 00:00:1757736070.857057 624082 gpu_helpers.cc:136] XLA backend allocating 3825205248 bytes on device 0 for BFCAllocator.
I0000 00:00:1757736070.857099 624082 gpu_helpers.cc:177] XLA backend will use up to 1275068416 bytes on device 0 for CollectiveBFCAllocator.
I0000 00:00:1757736070.869482 624082 cuda_dnn.cc:463] Loaded cuDNN version 91200
Total Trainable Parameters: 0.1493 M
┌ Warning: `training` is set to `Val{true}()` but is not being used within an autodiff call (gradient, jacobian, etc...). This will be slow. If you are using a `Lux.jl` model, set it to inference (test) mode using `LuxCore.testmode`. Reliance on this behavior is discouraged, and is not guaranteed by Semantic Versioning, and might be removed without a deprecation cycle. It is recommended to fix this issue in your code.
└ @ LuxLib.Utils /var/lib/buildkite-agent/builds/gpuci-11/julialang/lux-dot-jl/lib/LuxLib/src/utils.jl:334
Epoch 1, Iter 39, Loss: 24311.3867188, Throughput: 49.885563 im/s
Epoch 1, Train Loss: 39705.1054688, Time: 100.4607s, Throughput: 49.691077 im/s
Epoch 2, Iter 39, Loss: 17998.2910156, Throughput: 1857.106973 im/s
Epoch 2, Train Loss: 20246.1914062, Time: 2.6884s, Throughput: 1856.834735 im/s
Epoch 3, Iter 39, Loss: 15701.4667969, Throughput: 1895.785033 im/s
Epoch 3, Train Loss: 16584.9414062, Time: 2.6335s, Throughput: 1895.546641 im/s
Epoch 4, Iter 39, Loss: 14335.0859375, Throughput: 1892.902442 im/s
Epoch 4, Train Loss: 15077.8027344, Time: 2.6375s, Throughput: 1892.667683 im/s
Epoch 5, Iter 39, Loss: 13974.8535156, Throughput: 1897.202204 im/s
Epoch 5, Train Loss: 14102.5947266, Time: 2.6316s, Throughput: 1896.940426 im/s
Epoch 6, Iter 39, Loss: 13219.8271484, Throughput: 1899.397411 im/s
Epoch 6, Train Loss: 13409.3662109, Time: 2.6285s, Throughput: 1899.158971 im/s
Epoch 7, Iter 39, Loss: 13026.1601562, Throughput: 1899.637978 im/s
Epoch 7, Train Loss: 12983.9619141, Time: 2.6282s, Throughput: 1899.397411 im/s
Epoch 8, Iter 39, Loss: 12565.7958984, Throughput: 1893.274206 im/s
Epoch 8, Train Loss: 12569.2167969, Time: 2.6370s, Throughput: 1893.031482 im/s
Epoch 9, Iter 39, Loss: 12373.2617188, Throughput: 1902.374498 im/s
Epoch 9, Train Loss: 12290.4394531, Time: 2.6244s, Throughput: 1902.138075 im/s
Epoch 10, Iter 39, Loss: 11943.7558594, Throughput: 1899.797759 im/s
Epoch 10, Train Loss: 12003.4238281, Time: 2.6280s, Throughput: 1899.514413 im/s
Epoch 11, Iter 39, Loss: 11859.1132812, Throughput: 1895.428068 im/s
Epoch 11, Train Loss: 11811.0146484, Time: 2.6341s, Throughput: 1895.161119 im/s
Epoch 12, Iter 39, Loss: 11567.8261719, Throughput: 1900.138438 im/s
Epoch 12, Train Loss: 11711.7363281, Time: 2.6276s, Throughput: 1899.853611 im/s
Epoch 13, Iter 39, Loss: 11848.2167969, Throughput: 1890.566005 im/s
Epoch 13, Train Loss: 11479.1904297, Time: 2.6410s, Throughput: 1890.217487 im/s
Epoch 14, Iter 39, Loss: 11694.1513672, Throughput: 1883.103625 im/s
Epoch 14, Train Loss: 11377.9111328, Time: 2.6513s, Throughput: 1882.851480 im/s
Epoch 15, Iter 39, Loss: 11451.6513672, Throughput: 1899.986703 im/s
Epoch 15, Train Loss: 11232.9394531, Time: 2.6278s, Throughput: 1899.721226 im/s
Epoch 16, Iter 39, Loss: 10899.1445312, Throughput: 1883.283165 im/s
Epoch 16, Train Loss: 11141.1542969, Time: 2.6512s, Throughput: 1882.952905 im/s
Epoch 17, Iter 39, Loss: 11311.1679688, Throughput: 1896.552791 im/s
Epoch 17, Train Loss: 11018.9042969, Time: 2.6325s, Throughput: 1896.310084 im/s
Epoch 18, Iter 39, Loss: 10876.1513672, Throughput: 1897.400433 im/s
Epoch 18, Train Loss: 10976.6044922, Time: 2.6314s, Throughput: 1897.099753 im/s
Epoch 19, Iter 39, Loss: 10439.8623047, Throughput: 1903.417500 im/s
Epoch 19, Train Loss: 10838.1425781, Time: 2.6230s, Throughput: 1903.156253 im/s
Epoch 20, Iter 39, Loss: 10681.2587891, Throughput: 1893.747680 im/s
Epoch 20, Train Loss: 10735.7001953, Time: 2.6364s, Throughput: 1893.458773 im/s
Epoch 21, Iter 39, Loss: 10800.7783203, Throughput: 1901.278945 im/s
Epoch 21, Train Loss: 10674.7968750, Time: 2.6260s, Throughput: 1901.006030 im/s
Epoch 22, Iter 39, Loss: 10398.0566406, Throughput: 1901.300008 im/s
Epoch 22, Train Loss: 10599.8408203, Time: 2.6259s, Throughput: 1901.063161 im/s
Epoch 23, Iter 39, Loss: 11041.8916016, Throughput: 1901.244071 im/s
Epoch 23, Train Loss: 10553.6982422, Time: 2.6260s, Throughput: 1901.001543 im/s
Epoch 24, Iter 39, Loss: 9851.2187500, Throughput: 1915.674989 im/s
Epoch 24, Train Loss: 10466.6201172, Time: 2.6062s, Throughput: 1915.426663 im/s
Epoch 25, Iter 39, Loss: 9847.3974609, Throughput: 1957.776144 im/s
Epoch 25, Train Loss: 10421.5644531, Time: 2.5502s, Throughput: 1957.528862 im/s
Epoch 26, Iter 39, Loss: 10473.5517578, Throughput: 1893.689275 im/s
Epoch 26, Train Loss: 10307.8896484, Time: 2.6365s, Throughput: 1893.447985 im/s
Epoch 27, Iter 39, Loss: 10823.2363281, Throughput: 1890.668434 im/s
Epoch 27, Train Loss: 10290.3632812, Time: 2.6407s, Throughput: 1890.390706 im/s
Epoch 28, Iter 39, Loss: 10455.4335938, Throughput: 1898.662643 im/s
Epoch 28, Train Loss: 10177.6845703, Time: 2.6296s, Throughput: 1898.390479 im/s
Epoch 29, Iter 39, Loss: 10566.5214844, Throughput: 1898.945046 im/s
Epoch 29, Train Loss: 10164.7714844, Time: 2.6292s, Throughput: 1898.702415 im/s
Epoch 30, Iter 39, Loss: 10454.0830078, Throughput: 1891.672145 im/s
Epoch 30, Train Loss: 10100.0390625, Time: 2.6393s, Throughput: 1891.400614 im/s
Epoch 31, Iter 39, Loss: 9994.4980469, Throughput: 1897.163182 im/s
Epoch 31, Train Loss: 10049.4267578, Time: 2.6316s, Throughput: 1896.916022 im/s
Epoch 32, Iter 39, Loss: 9617.6718750, Throughput: 1897.414876 im/s
Epoch 32, Train Loss: 10161.1044922, Time: 2.6313s, Throughput: 1897.155962 im/s
Epoch 33, Iter 39, Loss: 9587.1894531, Throughput: 1892.847169 im/s
Epoch 33, Train Loss: 10035.1083984, Time: 2.6377s, Throughput: 1892.580262 im/s
Epoch 34, Iter 39, Loss: 10162.3886719, Throughput: 1900.220177 im/s
Epoch 34, Train Loss: 9952.9765625, Time: 2.6274s, Throughput: 1899.947567 im/s
Epoch 35, Iter 39, Loss: 9469.1191406, Throughput: 1899.797931 im/s
Epoch 35, Train Loss: 9857.8925781, Time: 2.6280s, Throughput: 1899.523891 im/s
Epoch 36, Iter 39, Loss: 9165.4853516, Throughput: 1893.817394 im/s
Epoch 36, Train Loss: 9847.7285156, Time: 2.6362s, Throughput: 1893.608952 im/s
Epoch 37, Iter 39, Loss: 10592.9765625, Throughput: 1892.946081 im/s
Epoch 37, Train Loss: 9796.2421875, Time: 2.6377s, Throughput: 1892.579407 im/s
Epoch 38, Iter 39, Loss: 9968.0097656, Throughput: 1902.649881 im/s
Epoch 38, Train Loss: 9868.8466797, Time: 2.6240s, Throughput: 1902.411315 im/s
Epoch 39, Iter 39, Loss: 10303.2714844, Throughput: 1884.464069 im/s
Epoch 39, Train Loss: 9764.3681641, Time: 2.6494s, Throughput: 1884.221564 im/s
Epoch 40, Iter 39, Loss: 10177.9882812, Throughput: 1882.909557 im/s
Epoch 40, Train Loss: 9727.2568359, Time: 2.6516s, Throughput: 1882.636812 im/s
Epoch 41, Iter 39, Loss: 9391.7929688, Throughput: 1901.473019 im/s
Epoch 41, Train Loss: 9694.1923828, Time: 2.6258s, Throughput: 1901.126165 im/s
Epoch 42, Iter 39, Loss: 9766.9843750, Throughput: 1904.791003 im/s
Epoch 42, Train Loss: 9692.5800781, Time: 2.6211s, Throughput: 1904.558483 im/s
Epoch 43, Iter 39, Loss: 10175.3505859, Throughput: 1891.638477 im/s
Epoch 43, Train Loss: 9645.0371094, Time: 2.6393s, Throughput: 1891.389850 im/s
Epoch 44, Iter 39, Loss: 9786.2509766, Throughput: 1900.662280 im/s
Epoch 44, Train Loss: 9611.7695312, Time: 2.6268s, Throughput: 1900.417658 im/s
Epoch 45, Iter 39, Loss: 9006.9160156, Throughput: 1896.838863 im/s
Epoch 45, Train Loss: 9571.6318359, Time: 2.6322s, Throughput: 1896.535440 im/s
Epoch 46, Iter 39, Loss: 8915.3906250, Throughput: 1864.934914 im/s
Epoch 46, Train Loss: 9536.3232422, Time: 2.6772s, Throughput: 1864.666687 im/s
Epoch 47, Iter 39, Loss: 9810.5771484, Throughput: 1939.560567 im/s
Epoch 47, Train Loss: 9553.5517578, Time: 2.5741s, Throughput: 1939.318584 im/s
Epoch 48, Iter 39, Loss: 9346.4804688, Throughput: 2009.446619 im/s
Epoch 48, Train Loss: 9480.3349609, Time: 2.4846s, Throughput: 2009.185342 im/s
Epoch 49, Iter 39, Loss: 9739.2958984, Throughput: 1933.403705 im/s
Epoch 49, Train Loss: 9462.1806641, Time: 2.5824s, Throughput: 1933.092935 im/s
Epoch 50, Iter 39, Loss: 9308.3544922, Throughput: 1900.021359 im/s
Epoch 50, Train Loss: 9462.9560547, Time: 2.6278s, Throughput: 1899.714849 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.6
Commit 9615af0f269 (2025-07-09 12:58 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.