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)falseModel 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
endSimilarly 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)
endLoading 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
endHelper 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)
endreconstruct_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:1760851396.822818 146986 service.cc:158] XLA service 0x3e5dbfd0 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:
I0000 00:00:1760851396.822890 146986 service.cc:166] StreamExecutor device (0): NVIDIA A100-PCIE-40GB MIG 1g.5gb, Compute Capability 8.0
I0000 00:00:1760851396.823760 146986 se_gpu_pjrt_client.cc:1339] Using BFC allocator.
I0000 00:00:1760851396.823806 146986 gpu_helpers.cc:136] XLA backend allocating 3825205248 bytes on device 0 for BFCAllocator.
I0000 00:00:1760851396.823853 146986 gpu_helpers.cc:177] XLA backend will use up to 1275068416 bytes on device 0 for CollectiveBFCAllocator.
I0000 00:00:1760851396.835155 146986 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: 23864.5000000, Throughput: 51.580702 im/s
Epoch 1, Train Loss: 39524.8281250, Time: 97.1953s, Throughput: 51.360485 im/s
Epoch 2, Iter 39, Loss: 18308.7226562, Throughput: 1861.486239 im/s
Epoch 2, Train Loss: 20050.5625000, Time: 2.6821s, Throughput: 1861.246136 im/s
Epoch 3, Iter 39, Loss: 15585.7958984, Throughput: 1899.943946 im/s
Epoch 3, Train Loss: 16478.3652344, Time: 2.6278s, Throughput: 1899.667623 im/s
Epoch 4, Iter 39, Loss: 14314.7177734, Throughput: 1904.150238 im/s
Epoch 4, Train Loss: 14945.5302734, Time: 2.6220s, Throughput: 1903.904025 im/s
Epoch 5, Iter 39, Loss: 13695.8066406, Throughput: 1905.825207 im/s
Epoch 5, Train Loss: 14005.9501953, Time: 2.6197s, Throughput: 1905.580642 im/s
Epoch 6, Iter 39, Loss: 13419.0283203, Throughput: 1902.580552 im/s
Epoch 6, Train Loss: 13379.1386719, Time: 2.6241s, Throughput: 1902.355658 im/s
Epoch 7, Iter 39, Loss: 12532.1621094, Throughput: 1911.545769 im/s
Epoch 7, Train Loss: 12896.2119141, Time: 2.6118s, Throughput: 1911.332185 im/s
Epoch 8, Iter 39, Loss: 12521.6142578, Throughput: 1917.265663 im/s
Epoch 8, Train Loss: 12502.4785156, Time: 2.6040s, Throughput: 1917.035178 im/s
Epoch 9, Iter 39, Loss: 11946.9902344, Throughput: 1906.716060 im/s
Epoch 9, Train Loss: 12183.1582031, Time: 2.6184s, Throughput: 1906.496263 im/s
Epoch 10, Iter 39, Loss: 11748.6484375, Throughput: 1902.577440 im/s
Epoch 10, Train Loss: 11897.0859375, Time: 2.6241s, Throughput: 1902.361535 im/s
Epoch 11, Iter 39, Loss: 11954.4941406, Throughput: 1912.015856 im/s
Epoch 11, Train Loss: 11762.7031250, Time: 2.6112s, Throughput: 1911.781569 im/s
Epoch 12, Iter 39, Loss: 11923.5029297, Throughput: 1912.141053 im/s
Epoch 12, Train Loss: 11613.5371094, Time: 2.6111s, Throughput: 1911.866408 im/s
Epoch 13, Iter 39, Loss: 12092.8320312, Throughput: 1908.408593 im/s
Epoch 13, Train Loss: 11347.3066406, Time: 2.6161s, Throughput: 1908.161973 im/s
Epoch 14, Iter 39, Loss: 11377.1162109, Throughput: 1916.885822 im/s
Epoch 14, Train Loss: 11160.3623047, Time: 2.6045s, Throughput: 1916.677536 im/s
Epoch 15, Iter 39, Loss: 10185.3164062, Throughput: 1914.637598 im/s
Epoch 15, Train Loss: 11070.9482422, Time: 2.6076s, Throughput: 1914.395317 im/s
Epoch 16, Iter 39, Loss: 11031.4648438, Throughput: 1906.257947 im/s
Epoch 16, Train Loss: 10957.0419922, Time: 2.6191s, Throughput: 1906.021425 im/s
Epoch 17, Iter 39, Loss: 10786.4443359, Throughput: 1914.540609 im/s
Epoch 17, Train Loss: 10826.5791016, Time: 2.6078s, Throughput: 1914.287326 im/s
Epoch 18, Iter 39, Loss: 10823.1425781, Throughput: 1913.472969 im/s
Epoch 18, Train Loss: 10759.5058594, Time: 2.6093s, Throughput: 1913.191298 im/s
Epoch 19, Iter 39, Loss: 10245.1484375, Throughput: 1908.331366 im/s
Epoch 19, Train Loss: 10731.7705078, Time: 2.6163s, Throughput: 1908.034514 im/s
Epoch 20, Iter 39, Loss: 10462.9472656, Throughput: 1908.524621 im/s
Epoch 20, Train Loss: 10637.9355469, Time: 2.6159s, Throughput: 1908.341627 im/s
Epoch 21, Iter 39, Loss: 10104.9853516, Throughput: 1902.473198 im/s
Epoch 21, Train Loss: 10601.7343750, Time: 2.6243s, Throughput: 1902.252132 im/s
Epoch 22, Iter 39, Loss: 11261.8671875, Throughput: 1904.885448 im/s
Epoch 22, Train Loss: 10425.3134766, Time: 2.6211s, Throughput: 1904.565066 im/s
Epoch 23, Iter 39, Loss: 10518.8505859, Throughput: 1909.220211 im/s
Epoch 23, Train Loss: 10401.5957031, Time: 2.6150s, Throughput: 1908.984346 im/s
Epoch 24, Iter 39, Loss: 10558.5800781, Throughput: 1911.921401 im/s
Epoch 24, Train Loss: 10303.6269531, Time: 2.6113s, Throughput: 1911.682774 im/s
Epoch 25, Iter 39, Loss: 9636.5468750, Throughput: 1911.285252 im/s
Epoch 25, Train Loss: 10201.0253906, Time: 2.6122s, Throughput: 1911.038760 im/s
Epoch 26, Iter 39, Loss: 10174.8281250, Throughput: 1906.968732 im/s
Epoch 26, Train Loss: 10164.1953125, Time: 2.6181s, Throughput: 1906.721095 im/s
Epoch 27, Iter 39, Loss: 10252.5380859, Throughput: 1908.685204 im/s
Epoch 27, Train Loss: 10121.9892578, Time: 2.6157s, Throughput: 1908.445818 im/s
Epoch 28, Iter 39, Loss: 9931.5986328, Throughput: 1912.062650 im/s
Epoch 28, Train Loss: 10105.2607422, Time: 2.6112s, Throughput: 1911.791693 im/s
Epoch 29, Iter 39, Loss: 9623.5009766, Throughput: 1908.923083 im/s
Epoch 29, Train Loss: 10065.4531250, Time: 2.6154s, Throughput: 1908.662585 im/s
Epoch 30, Iter 39, Loss: 9128.0917969, Throughput: 1912.588721 im/s
Epoch 30, Train Loss: 9967.4550781, Time: 2.6104s, Throughput: 1912.319886 im/s
Epoch 31, Iter 39, Loss: 10495.8828125, Throughput: 1913.306334 im/s
Epoch 31, Train Loss: 9892.3769531, Time: 2.6095s, Throughput: 1913.042366 im/s
Epoch 32, Iter 39, Loss: 10600.7978516, Throughput: 1908.666934 im/s
Epoch 32, Train Loss: 9834.3144531, Time: 2.6159s, Throughput: 1908.355368 im/s
Epoch 33, Iter 39, Loss: 10823.7255859, Throughput: 2001.579008 im/s
Epoch 33, Train Loss: 9914.5673828, Time: 2.4944s, Throughput: 2001.315756 im/s
Epoch 34, Iter 39, Loss: 10043.8056641, Throughput: 1922.072806 im/s
Epoch 34, Train Loss: 9776.4218750, Time: 2.5976s, Throughput: 1921.810118 im/s
Epoch 35, Iter 39, Loss: 9840.3974609, Throughput: 1906.116860 im/s
Epoch 35, Train Loss: 9780.6250000, Time: 2.6193s, Throughput: 1905.874475 im/s
Epoch 36, Iter 39, Loss: 9668.8779297, Throughput: 1907.008854 im/s
Epoch 36, Train Loss: 9660.8945312, Time: 2.6180s, Throughput: 1906.766242 im/s
Epoch 37, Iter 39, Loss: 9819.2392578, Throughput: 1901.297073 im/s
Epoch 37, Train Loss: 9630.0986328, Time: 2.6259s, Throughput: 1901.079041 im/s
Epoch 38, Iter 39, Loss: 9999.2089844, Throughput: 1907.659713 im/s
Epoch 38, Train Loss: 9658.5048828, Time: 2.6172s, Throughput: 1907.396431 im/s
Epoch 39, Iter 39, Loss: 9950.3496094, Throughput: 1910.127484 im/s
Epoch 39, Train Loss: 9610.2578125, Time: 2.6137s, Throughput: 1909.945577 im/s
Epoch 40, Iter 39, Loss: 8904.5224609, Throughput: 1909.497753 im/s
Epoch 40, Train Loss: 9604.8203125, Time: 2.6147s, Throughput: 1909.188875 im/s
Epoch 41, Iter 39, Loss: 9562.1708984, Throughput: 1908.911423 im/s
Epoch 41, Train Loss: 9556.4980469, Time: 2.6154s, Throughput: 1908.678592 im/s
Epoch 42, Iter 39, Loss: 9883.5166016, Throughput: 1896.396304 im/s
Epoch 42, Train Loss: 9504.4667969, Time: 2.6327s, Throughput: 1896.156556 im/s
Epoch 43, Iter 39, Loss: 9156.3730469, Throughput: 1910.292869 im/s
Epoch 43, Train Loss: 9550.9130859, Time: 2.6136s, Throughput: 1910.023110 im/s
Epoch 44, Iter 39, Loss: 9355.2285156, Throughput: 1909.016546 im/s
Epoch 44, Train Loss: 9494.4326172, Time: 2.6153s, Throughput: 1908.773423 im/s
Epoch 45, Iter 39, Loss: 9991.3437500, Throughput: 1904.174136 im/s
Epoch 45, Train Loss: 9484.4394531, Time: 2.6219s, Throughput: 1903.935880 im/s
Epoch 46, Iter 39, Loss: 9199.1113281, Throughput: 1904.238039 im/s
Epoch 46, Train Loss: 9392.2558594, Time: 2.6219s, Throughput: 1903.961331 im/s
Epoch 47, Iter 39, Loss: 9185.7421875, Throughput: 1907.374712 im/s
Epoch 47, Train Loss: 9409.4003906, Time: 2.6176s, Throughput: 1907.086843 im/s
Epoch 48, Iter 39, Loss: 9203.8046875, Throughput: 1898.552976 im/s
Epoch 48, Train Loss: 9412.3769531, Time: 2.6297s, Throughput: 1898.280155 im/s
Epoch 49, Iter 39, Loss: 9254.4042969, Throughput: 1901.468011 im/s
Epoch 49, Train Loss: 9285.0683594, Time: 2.6258s, Throughput: 1901.155165 im/s
Epoch 50, Iter 39, Loss: 8934.8740234, Throughput: 1906.214386 im/s
Epoch 50, Train Loss: 9280.9619141, Time: 2.6192s, Throughput: 1905.904314 im/sAppendix
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
endJulia Version 1.11.7
Commit f2b3dbda30a (2025-09-08 12:10 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 = LiterateThis page was generated using Literate.jl.