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:1758303588.517628 1320874 service.cc:158] XLA service 0x142feba0 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:
I0000 00:00:1758303588.517700 1320874 service.cc:166] StreamExecutor device (0): NVIDIA A100-PCIE-40GB MIG 1g.5gb, Compute Capability 8.0
I0000 00:00:1758303588.518669 1320874 se_gpu_pjrt_client.cc:1338] Using BFC allocator.
I0000 00:00:1758303588.518738 1320874 gpu_helpers.cc:136] XLA backend allocating 3825205248 bytes on device 0 for BFCAllocator.
I0000 00:00:1758303588.518808 1320874 gpu_helpers.cc:177] XLA backend will use up to 1275068416 bytes on device 0 for CollectiveBFCAllocator.
I0000 00:00:1758303588.528638 1320874 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-14/julialang/lux-dot-jl/lib/LuxLib/src/utils.jl:334
Epoch 1, Iter 39, Loss: 23635.5605469, Throughput: 51.139038 im/s
Epoch 1, Train Loss: 39765.3437500, Time: 98.0018s, Throughput: 50.937833 im/s
Epoch 2, Iter 39, Loss: 17504.4589844, Throughput: 1946.402140 im/s
Epoch 2, Train Loss: 20094.3652344, Time: 2.5650s, Throughput: 1946.166225 im/s
Epoch 3, Iter 39, Loss: 15817.1552734, Throughput: 1996.466994 im/s
Epoch 3, Train Loss: 16693.5839844, Time: 2.5007s, Throughput: 1996.238771 im/s
Epoch 4, Iter 39, Loss: 14914.6904297, Throughput: 1988.899227 im/s
Epoch 4, Train Loss: 15157.4472656, Time: 2.5102s, Throughput: 1988.699553 im/s
Epoch 5, Iter 39, Loss: 14019.9921875, Throughput: 1996.558184 im/s
Epoch 5, Train Loss: 14338.7294922, Time: 2.5006s, Throughput: 1996.322517 im/s
Epoch 6, Iter 39, Loss: 13366.4609375, Throughput: 1988.656865 im/s
Epoch 6, Train Loss: 13690.8056641, Time: 2.5105s, Throughput: 1988.461205 im/s
Epoch 7, Iter 39, Loss: 13598.2919922, Throughput: 1950.465616 im/s
Epoch 7, Train Loss: 13177.8496094, Time: 2.5597s, Throughput: 1950.209460 im/s
Epoch 8, Iter 39, Loss: 12417.6875000, Throughput: 1991.176118 im/s
Epoch 8, Train Loss: 12765.5664062, Time: 2.5073s, Throughput: 1990.978448 im/s
Epoch 9, Iter 39, Loss: 12148.2695312, Throughput: 1994.195657 im/s
Epoch 9, Train Loss: 12479.2812500, Time: 2.5036s, Throughput: 1993.936812 im/s
Epoch 10, Iter 39, Loss: 12505.9296875, Throughput: 1991.009497 im/s
Epoch 10, Train Loss: 12187.3544922, Time: 2.5075s, Throughput: 1990.788766 im/s
Epoch 11, Iter 39, Loss: 13726.2285156, Throughput: 1990.581332 im/s
Epoch 11, Train Loss: 11944.4091797, Time: 2.5081s, Throughput: 1990.326640 im/s
Epoch 12, Iter 39, Loss: 10593.8339844, Throughput: 1996.964735 im/s
Epoch 12, Train Loss: 11715.9921875, Time: 2.5001s, Throughput: 1996.712216 im/s
Epoch 13, Iter 39, Loss: 11556.1601562, Throughput: 1985.297281 im/s
Epoch 13, Train Loss: 11650.3750000, Time: 2.5147s, Throughput: 1985.109433 im/s
Epoch 14, Iter 39, Loss: 11371.5214844, Throughput: 1990.295045 im/s
Epoch 14, Train Loss: 11475.6318359, Time: 2.5086s, Throughput: 1989.979902 im/s
Epoch 15, Iter 39, Loss: 11948.3281250, Throughput: 1991.008550 im/s
Epoch 15, Train Loss: 11283.7070312, Time: 2.5075s, Throughput: 1990.855208 im/s
Epoch 16, Iter 39, Loss: 11082.8125000, Throughput: 1993.811686 im/s
Epoch 16, Train Loss: 11297.5292969, Time: 2.5040s, Throughput: 1993.576667 im/s
Epoch 17, Iter 39, Loss: 11517.7343750, Throughput: 1992.161460 im/s
Epoch 17, Train Loss: 11119.1621094, Time: 2.5061s, Throughput: 1991.924745 im/s
Epoch 18, Iter 39, Loss: 11097.1943359, Throughput: 1991.403943 im/s
Epoch 18, Train Loss: 10904.4833984, Time: 2.5070s, Throughput: 1991.198274 im/s
Epoch 19, Iter 39, Loss: 11539.8027344, Throughput: 1987.308612 im/s
Epoch 19, Train Loss: 10854.6787109, Time: 2.5122s, Throughput: 1987.092662 im/s
Epoch 20, Iter 39, Loss: 10234.4375000, Throughput: 1991.324587 im/s
Epoch 20, Train Loss: 10820.7255859, Time: 2.5072s, Throughput: 1991.083148 im/s
Epoch 21, Iter 39, Loss: 10600.5136719, Throughput: 1988.731286 im/s
Epoch 21, Train Loss: 10700.4033203, Time: 2.5104s, Throughput: 1988.501429 im/s
Epoch 22, Iter 39, Loss: 11114.5136719, Throughput: 1975.395313 im/s
Epoch 22, Train Loss: 10616.4394531, Time: 2.5274s, Throughput: 1975.185111 im/s
Epoch 23, Iter 39, Loss: 10115.2558594, Throughput: 1986.437930 im/s
Epoch 23, Train Loss: 10492.5156250, Time: 2.5133s, Throughput: 1986.251373 im/s
Epoch 24, Iter 39, Loss: 10362.3925781, Throughput: 1980.024544 im/s
Epoch 24, Train Loss: 10416.9296875, Time: 2.5216s, Throughput: 1979.733049 im/s
Epoch 25, Iter 39, Loss: 10235.9375000, Throughput: 1863.504320 im/s
Epoch 25, Train Loss: 10407.0468750, Time: 2.6792s, Throughput: 1863.265687 im/s
Epoch 26, Iter 39, Loss: 9450.4804688, Throughput: 1839.531864 im/s
Epoch 26, Train Loss: 10342.4980469, Time: 2.7141s, Throughput: 1839.293998 im/s
Epoch 27, Iter 39, Loss: 10422.6962891, Throughput: 1806.700470 im/s
Epoch 27, Train Loss: 10184.8535156, Time: 2.7635s, Throughput: 1806.391847 im/s
Epoch 28, Iter 39, Loss: 10785.6279297, Throughput: 1787.214708 im/s
Epoch 28, Train Loss: 10121.7529297, Time: 2.7939s, Throughput: 1786.750916 im/s
Epoch 29, Iter 39, Loss: 11101.2128906, Throughput: 1753.307707 im/s
Epoch 29, Train Loss: 10102.5322266, Time: 2.8476s, Throughput: 1753.054041 im/s
Epoch 30, Iter 39, Loss: 10157.7265625, Throughput: 1810.509409 im/s
Epoch 30, Train Loss: 10062.0468750, Time: 2.7575s, Throughput: 1810.311075 im/s
Epoch 31, Iter 39, Loss: 10320.2373047, Throughput: 1811.297850 im/s
Epoch 31, Train Loss: 9968.0068359, Time: 2.7563s, Throughput: 1811.094017 im/s
Epoch 32, Iter 39, Loss: 9879.7958984, Throughput: 1809.498784 im/s
Epoch 32, Train Loss: 9954.3681641, Time: 2.7591s, Throughput: 1809.259397 im/s
Epoch 33, Iter 39, Loss: 10248.8906250, Throughput: 1811.929537 im/s
Epoch 33, Train Loss: 9903.0644531, Time: 2.7555s, Throughput: 1811.672577 im/s
Epoch 34, Iter 39, Loss: 9522.2656250, Throughput: 1823.879372 im/s
Epoch 34, Train Loss: 9837.5732422, Time: 2.7376s, Throughput: 1823.524989 im/s
Epoch 35, Iter 39, Loss: 9814.9316406, Throughput: 1818.266616 im/s
Epoch 35, Train Loss: 9820.2656250, Time: 2.7459s, Throughput: 1817.959238 im/s
Epoch 36, Iter 39, Loss: 9790.5429688, Throughput: 1827.270833 im/s
Epoch 36, Train Loss: 9832.3320312, Time: 2.7323s, Throughput: 1827.044896 im/s
Epoch 37, Iter 39, Loss: 9193.9531250, Throughput: 1840.285134 im/s
Epoch 37, Train Loss: 9827.5556641, Time: 2.7130s, Throughput: 1840.044324 im/s
Epoch 38, Iter 39, Loss: 9977.0605469, Throughput: 1835.856353 im/s
Epoch 38, Train Loss: 9673.9511719, Time: 2.7195s, Throughput: 1835.609942 im/s
Epoch 39, Iter 39, Loss: 9181.5722656, Throughput: 1835.832047 im/s
Epoch 39, Train Loss: 9663.4560547, Time: 2.7195s, Throughput: 1835.620080 im/s
Epoch 40, Iter 39, Loss: 9702.5781250, Throughput: 1839.885867 im/s
Epoch 40, Train Loss: 9625.9072266, Time: 2.7137s, Throughput: 1839.585360 im/s
Epoch 41, Iter 39, Loss: 10023.4296875, Throughput: 1916.837914 im/s
Epoch 41, Train Loss: 9567.2275391, Time: 2.6046s, Throughput: 1916.576655 im/s
Epoch 42, Iter 39, Loss: 9865.6435547, Throughput: 1848.142720 im/s
Epoch 42, Train Loss: 9589.0166016, Time: 2.7014s, Throughput: 1847.910125 im/s
Epoch 43, Iter 39, Loss: 9298.7783203, Throughput: 1858.330476 im/s
Epoch 43, Train Loss: 9524.5703125, Time: 2.6866s, Throughput: 1858.098112 im/s
Epoch 44, Iter 39, Loss: 9758.1718750, Throughput: 1866.005602 im/s
Epoch 44, Train Loss: 9498.4042969, Time: 2.6756s, Throughput: 1865.770650 im/s
Epoch 45, Iter 39, Loss: 9734.6015625, Throughput: 1886.793091 im/s
Epoch 45, Train Loss: 9442.8896484, Time: 2.6461s, Throughput: 1886.574293 im/s
Epoch 46, Iter 39, Loss: 9716.4550781, Throughput: 1843.164195 im/s
Epoch 46, Train Loss: 9519.1386719, Time: 2.7087s, Throughput: 1842.943071 im/s
Epoch 47, Iter 39, Loss: 9683.0908203, Throughput: 1832.209769 im/s
Epoch 47, Train Loss: 9448.2763672, Time: 2.7249s, Throughput: 1831.983731 im/s
Epoch 48, Iter 39, Loss: 9085.2109375, Throughput: 1836.523652 im/s
Epoch 48, Train Loss: 9365.8955078, Time: 2.7185s, Throughput: 1836.288496 im/s
Epoch 49, Iter 39, Loss: 9254.3144531, Throughput: 1824.949551 im/s
Epoch 49, Train Loss: 9355.5136719, Time: 2.7358s, Throughput: 1824.708763 im/s
Epoch 50, Iter 39, Loss: 9629.6064453, Throughput: 1843.981178 im/s
Epoch 50, Train Loss: 9358.2841797, Time: 2.7075s, Throughput: 1843.775444 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.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 = Literate
This page was generated using Literate.jl.