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()
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()
2025-08-05 23:58:17.507438: I external/xla/xla/service/service.cc:163] XLA service 0x9e0b460 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:
2025-08-05 23:58:17.507477: I external/xla/xla/service/service.cc:171] StreamExecutor device (0): Quadro RTX 5000, Compute Capability 7.5
WARNING: All log messages before absl::InitializeLog() is called are written to STDERR
I0000 00:00:1754438297.508673 615317 se_gpu_pjrt_client.cc:1373] Using BFC allocator.
I0000 00:00:1754438297.508744 615317 gpu_helpers.cc:136] XLA backend allocating 12528893952 bytes on device 0 for BFCAllocator.
I0000 00:00:1754438297.508802 615317 gpu_helpers.cc:177] XLA backend will use up to 4176297984 bytes on device 0 for CollectiveBFCAllocator.
2025-08-05 23:58:17.522694: I external/xla/xla/stream_executor/cuda/cuda_dnn.cc:473] Loaded cuDNN version 90800
┌ 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-15/julialang/lux-dot-jl/lib/LuxLib/src/utils.jl:344
Total Trainable Parameters: 0.1493 M
Epoch 1, Iter 39, Loss: 24128.9941406, Throughput: 50.120706 im/s
Epoch 1, Train Loss: 39754.8007812, Time: 100.0054s, Throughput: 49.917320 im/s
Epoch 2, Iter 39, Loss: 18940.0859375, Throughput: 2111.892306 im/s
Epoch 2, Train Loss: 20444.1406250, Time: 2.3642s, Throughput: 2111.466150 im/s
Epoch 3, Iter 39, Loss: 15681.9667969, Throughput: 2182.967960 im/s
Epoch 3, Train Loss: 16736.5390625, Time: 2.2870s, Throughput: 2182.739707 im/s
Epoch 4, Iter 39, Loss: 14280.3115234, Throughput: 2182.557458 im/s
Epoch 4, Train Loss: 15175.8750000, Time: 2.2875s, Throughput: 2182.265604 im/s
Epoch 5, Iter 39, Loss: 14150.4462891, Throughput: 2183.397514 im/s
Epoch 5, Train Loss: 14262.3232422, Time: 2.2866s, Throughput: 2183.116817 im/s
Epoch 6, Iter 39, Loss: 13192.2167969, Throughput: 2191.230497 im/s
Epoch 6, Train Loss: 13542.0947266, Time: 2.2784s, Throughput: 2190.988133 im/s
Epoch 7, Iter 39, Loss: 12817.9980469, Throughput: 2182.936325 im/s
Epoch 7, Train Loss: 12965.7958984, Time: 2.2870s, Throughput: 2182.731971 im/s
Epoch 8, Iter 39, Loss: 12760.8681641, Throughput: 2198.295847 im/s
Epoch 8, Train Loss: 12566.3925781, Time: 2.2710s, Throughput: 2198.126452 im/s
Epoch 9, Iter 39, Loss: 11433.6855469, Throughput: 2158.974263 im/s
Epoch 9, Train Loss: 12324.0605469, Time: 2.3125s, Throughput: 2158.738091 im/s
Epoch 10, Iter 39, Loss: 11551.2753906, Throughput: 2174.980533 im/s
Epoch 10, Train Loss: 11970.1513672, Time: 2.2955s, Throughput: 2174.664049 im/s
Epoch 11, Iter 39, Loss: 11289.6425781, Throughput: 2184.596469 im/s
Epoch 11, Train Loss: 11813.2275391, Time: 2.2856s, Throughput: 2184.128166 im/s
Epoch 12, Iter 39, Loss: 11183.4052734, Throughput: 2157.304139 im/s
Epoch 12, Train Loss: 11641.5839844, Time: 2.3143s, Throughput: 2157.045888 im/s
Epoch 13, Iter 39, Loss: 11937.7939453, Throughput: 2178.606438 im/s
Epoch 13, Train Loss: 11498.1689453, Time: 2.2917s, Throughput: 2178.340115 im/s
Epoch 14, Iter 39, Loss: 11952.1699219, Throughput: 2162.987499 im/s
Epoch 14, Train Loss: 11282.2910156, Time: 2.3081s, Throughput: 2162.793341 im/s
Epoch 15, Iter 39, Loss: 11636.2939453, Throughput: 2164.126782 im/s
Epoch 15, Train Loss: 11118.6103516, Time: 2.3069s, Throughput: 2163.913858 im/s
Epoch 16, Iter 39, Loss: 10058.4394531, Throughput: 2185.488965 im/s
Epoch 16, Train Loss: 11032.6308594, Time: 2.2844s, Throughput: 2185.240343 im/s
Epoch 17, Iter 39, Loss: 10526.2871094, Throughput: 2193.812237 im/s
Epoch 17, Train Loss: 10871.5849609, Time: 2.2757s, Throughput: 2193.574128 im/s
Epoch 18, Iter 39, Loss: 10164.0498047, Throughput: 2191.260309 im/s
Epoch 18, Train Loss: 10898.0566406, Time: 2.2783s, Throughput: 2191.094061 im/s
Epoch 19, Iter 39, Loss: 10621.8388672, Throughput: 2196.743192 im/s
Epoch 19, Train Loss: 10720.8593750, Time: 2.2726s, Throughput: 2196.568275 im/s
Epoch 20, Iter 39, Loss: 10834.6933594, Throughput: 2187.608425 im/s
Epoch 20, Train Loss: 10593.5859375, Time: 2.2822s, Throughput: 2187.395654 im/s
Epoch 21, Iter 39, Loss: 10787.9394531, Throughput: 2186.721963 im/s
Epoch 21, Train Loss: 10661.6054688, Time: 2.2831s, Throughput: 2186.538134 im/s
Epoch 22, Iter 39, Loss: 10498.9101562, Throughput: 2181.137594 im/s
Epoch 22, Train Loss: 10437.9013672, Time: 2.2890s, Throughput: 2180.899275 im/s
Epoch 23, Iter 39, Loss: 10727.5859375, Throughput: 2167.332636 im/s
Epoch 23, Train Loss: 10434.1992188, Time: 2.3038s, Throughput: 2166.863183 im/s
Epoch 24, Iter 39, Loss: 11244.7080078, Throughput: 2162.823501 im/s
Epoch 24, Train Loss: 10327.4580078, Time: 2.3083s, Throughput: 2162.583806 im/s
Epoch 25, Iter 39, Loss: 10366.7402344, Throughput: 2153.934627 im/s
Epoch 25, Train Loss: 10289.7607422, Time: 2.3178s, Throughput: 2153.733008 im/s
Epoch 26, Iter 39, Loss: 9734.5419922, Throughput: 2177.500096 im/s
Epoch 26, Train Loss: 10092.1943359, Time: 2.2927s, Throughput: 2177.298796 im/s
Epoch 27, Iter 39, Loss: 9478.2958984, Throughput: 2180.489778 im/s
Epoch 27, Train Loss: 10120.3857422, Time: 2.2896s, Throughput: 2180.307904 im/s
Epoch 28, Iter 39, Loss: 9556.8750000, Throughput: 2177.411782 im/s
Epoch 28, Train Loss: 10081.5742188, Time: 2.2929s, Throughput: 2177.149826 im/s
Epoch 29, Iter 39, Loss: 9844.8222656, Throughput: 2176.091778 im/s
Epoch 29, Train Loss: 10015.6943359, Time: 2.2944s, Throughput: 2175.762536 im/s
Epoch 30, Iter 39, Loss: 10015.6142578, Throughput: 2170.558353 im/s
Epoch 30, Train Loss: 10062.2050781, Time: 2.3002s, Throughput: 2170.281847 im/s
Epoch 31, Iter 39, Loss: 10030.4072266, Throughput: 2174.702899 im/s
Epoch 31, Train Loss: 9917.5839844, Time: 2.2958s, Throughput: 2174.360980 im/s
Epoch 32, Iter 39, Loss: 9953.1533203, Throughput: 2174.388302 im/s
Epoch 32, Train Loss: 9942.7939453, Time: 2.2961s, Throughput: 2174.117592 im/s
Epoch 33, Iter 39, Loss: 10254.4199219, Throughput: 2183.683066 im/s
Epoch 33, Train Loss: 9946.2646484, Time: 2.2864s, Throughput: 2183.315323 im/s
Epoch 34, Iter 39, Loss: 10178.6474609, Throughput: 2169.724324 im/s
Epoch 34, Train Loss: 9792.3349609, Time: 2.3011s, Throughput: 2169.408469 im/s
Epoch 35, Iter 39, Loss: 10160.7636719, Throughput: 2161.459088 im/s
Epoch 35, Train Loss: 9742.9052734, Time: 2.3098s, Throughput: 2161.257843 im/s
Epoch 36, Iter 39, Loss: 9989.6826172, Throughput: 2160.845430 im/s
Epoch 36, Train Loss: 9737.1181641, Time: 2.3106s, Throughput: 2160.518109 im/s
Epoch 37, Iter 39, Loss: 9439.8076172, Throughput: 2167.794886 im/s
Epoch 37, Train Loss: 9702.5107422, Time: 2.3031s, Throughput: 2167.507864 im/s
Epoch 38, Iter 39, Loss: 10293.2685547, Throughput: 2173.257140 im/s
Epoch 38, Train Loss: 9656.9199219, Time: 2.2974s, Throughput: 2172.938226 im/s
Epoch 39, Iter 39, Loss: 9784.6884766, Throughput: 2177.930672 im/s
Epoch 39, Train Loss: 9682.3652344, Time: 2.2923s, Throughput: 2177.685578 im/s
Epoch 40, Iter 39, Loss: 9395.8046875, Throughput: 2187.917257 im/s
Epoch 40, Train Loss: 9601.4042969, Time: 2.2819s, Throughput: 2187.637224 im/s
Epoch 41, Iter 39, Loss: 9685.0566406, Throughput: 2174.380851 im/s
Epoch 41, Train Loss: 9598.8798828, Time: 2.2961s, Throughput: 2174.103370 im/s
Epoch 42, Iter 39, Loss: 9728.1357422, Throughput: 2173.657381 im/s
Epoch 42, Train Loss: 9589.1015625, Time: 2.2968s, Throughput: 2173.424754 im/s
Epoch 43, Iter 39, Loss: 9916.3320312, Throughput: 2183.799677 im/s
Epoch 43, Train Loss: 9546.8544922, Time: 2.2862s, Throughput: 2183.555993 im/s
Epoch 44, Iter 39, Loss: 9741.0683594, Throughput: 2184.158925 im/s
Epoch 44, Train Loss: 9520.0156250, Time: 2.2858s, Throughput: 2183.907644 im/s
Epoch 45, Iter 39, Loss: 9428.1621094, Throughput: 2183.127287 im/s
Epoch 45, Train Loss: 9394.9892578, Time: 2.2869s, Throughput: 2182.904918 im/s
Epoch 46, Iter 39, Loss: 10130.6035156, Throughput: 2181.783977 im/s
Epoch 46, Train Loss: 9375.4062500, Time: 2.2883s, Throughput: 2181.520741 im/s
Epoch 47, Iter 39, Loss: 10000.0546875, Throughput: 2163.038222 im/s
Epoch 47, Train Loss: 9401.7832031, Time: 2.3085s, Throughput: 2162.479724 im/s
Epoch 48, Iter 39, Loss: 9607.8007812, Throughput: 2170.137659 im/s
Epoch 48, Train Loss: 9340.1894531, Time: 2.3005s, Throughput: 2169.941317 im/s
Epoch 49, Iter 39, Loss: 9549.7304688, Throughput: 2179.164679 im/s
Epoch 49, Train Loss: 9315.3115234, Time: 2.2910s, Throughput: 2178.988696 im/s
Epoch 50, Iter 39, Loss: 9173.6132812, Throughput: 2182.734929 im/s
Epoch 50, Train Loss: 9345.9707031, Time: 2.2874s, Throughput: 2182.437113 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
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
JULIA_DEPOT_PATH = /root/.cache/julia-buildkite-plugin/depots/01872db4-8c79-43af-ab7d-12abac4f24f6
This page was generated using Literate.jl.