Distributed Calibration Tutorial Using Julia Workers
This example will teach you how to use ClimaCalibrate to parallelize your calibration with workers. Workers are additional processes spun up to run code in a distributed fashion. In this tutorial, we will run ensemble members' forward models on different workers.
The example calibration uses CliMA's atmosphere model, ClimaAtmos.jl, in a column spatial configuration for 30 days to simulate outgoing radiative fluxes. Radiative fluxes are used in the observation map to calibrate the astronomical unit.
First, we load in some necessary packages.
using Distributed
import ClimaCalibrate as CAL
import ClimaAnalysis: SimDir, get, slice, average_xy
using ClimaUtilities.ClimaArtifacts
import EnsembleKalmanProcesses as EKP
import EnsembleKalmanProcesses: I, ParameterDistributions.constrained_gaussianNext, we add workers. These are primarily added by Distributed.addprocs or by starting Julia with multiple processes: julia -p <nprocs>.
addprocs itself initializes the workers and registers them with the main Julia process, but there are multiple ways to call it. The simplest is just addprocs(nprocs), which will create new local processes on your machine. The other is to use SlurmManager, which will acquire and start workers on Slurm resources. You can use keyword arguments to specify the Slurm resources:
addprocs(ClimaCalibrate.SlurmManager(nprocs), gpus_per_task = 1, time = "01:00:00")
For this example, we would add one worker if it was compatible with Documenter.jl:
addprocs(1)We can see the number of workers and their ID numbers:
nworkers()1workers()1-element Vector{Int64}:
1We can call functions on the worker using remotecall. We pass in the function name and the worker ID followed by the function arguments.
remotecall_fetch(*, 1, 4, 4)16ClimaCalibrate uses this functionality to run the forward model on workers.
Since the workers start in their own Julia sessions, we need to import packages and declare variables. Distributed.@everywhere executes code on all workers, allowing us to load the code that they need.
@everywhere begin
output_dir = joinpath("output", "climaatmos_calibration")
import ClimaCalibrate as CAL
import ClimaAtmos as CA
import ClimaComms
end
output_dir = joinpath("output", "climaatmos_calibration")
mkpath(output_dir)"output/climaatmos_calibration"First, we define RadiativeFluxModelInterface which will subtype the ClimaCalibrate.AbstractModelInterface. The RadiativeFluxModelInterface will define how to run the forward model and observation map.
The forward model takes in the sampled parameters, runs the simulation, and saves the diagnostic output that can be processed and compared to observations. This is defined by ClimaCalibrate.forward_model(interface, iteration, member). This function is ran in parallel by the WorkerBackend and the HPCBackends.
Since forward_model(interface, iteration, member) only takes in the iteration and member numbers, so we need to use these as hooks to set the model parameters and output directory. Two useful functions:
path_to_ensemble_member: Returns the ensemble member's output directoryparameter_path: Returns the ensemble member's parameter file as specified byEKP.TOMLInterface
The forward model below is running ClimaAtmos.jl in a minimal column spatial configuration.
@everywhere @eval $(@__MODULE__) struct RadiativeFluxModelInterface <:
CAL.AbstractModelInterface end
@everywhere @eval $(@__MODULE__) function CAL.forward_model(
::RadiativeFluxModelInterface,
iteration,
member,
)
config_dict = Dict(
"dt" => "2000secs",
"t_end" => "30days",
"config" => "column",
"h_elem" => 1,
"insolation" => "timevarying",
"output_dir" => output_dir,
"output_default_diagnostics" => false,
"dt_rad" => "6hours",
"rad" => "clearsky",
"co2_model" => "fixed",
"log_progress" => false,
"diagnostics" => [
Dict(
"reduction_time" => "average",
"short_name" => "rsut",
"period" => "30days",
"writer" => "nc",
),
],
)
# Set the output path for the current member
member_path = CAL.path_to_ensemble_member(output_dir, iteration, member)
config_dict["output_dir"] = member_path
# Set the parameters for the current member
parameter_path = CAL.parameter_path(output_dir, iteration, member)
if haskey(config_dict, "toml")
push!(config_dict["toml"], parameter_path)
else
config_dict["toml"] = [parameter_path]
end
# Turn off default diagnostics
config_dict["output_default_diagnostics"] = false
comms_ctx = ClimaComms.SingletonCommsContext()
atmos_config = CA.AtmosConfig(config_dict; comms_ctx)
simulation = CA.get_simulation(atmos_config)
CA.solve_atmos!(simulation)
return simulation
endNext, the observation map is required to process a full ensemble of model output for the ensemble update step. The observation map just takes in the iteration number, and always outputs an array. For observation map output G_ensemble, G_ensemble[:, m] must the output of ensemble member m. This is needed for compatibility with EnsembleKalmanProcesses.jl.
const days = 86_400
function CAL.observation_map(::RadiativeFluxModelInterface, iteration)
single_member_dims = (1,)
G_ensemble = Array{Float64}(undef, single_member_dims..., ensemble_size)
for m in 1:ensemble_size
member_path = CAL.path_to_ensemble_member(output_dir, iteration, m)
simdir_path = joinpath(member_path, "output_active")
if isdir(simdir_path)
simdir = SimDir(simdir_path)
G_ensemble[:, m] .= process_member_data(simdir)
else
G_ensemble[:, m] .= NaN
end
end
return G_ensemble
endSeparating out the individual ensemble member output processing often results in more readable code.
function process_member_data(simdir::SimDir)
isempty(simdir.vars) && return NaN
rsut =
get(simdir; short_name = "rsut", reduction = "average", period = "30d")
return slice(average_xy(rsut); time = 30days).data
endprocess_member_data (generic function with 1 method)Now, we can set up the remaining experiment details:
- ensemble size, number of iterations
- the prior distribution
- the observational data
ensemble_size = 30
n_iterations = 7
noise = 0.1 * I
prior = constrained_gaussian("astronomical_unit", 6e10, 1e11, 2e5, Inf)ParameterDistribution with 1 entries:
'astronomical_unit' with EnsembleKalmanProcesses.ParameterDistributions.Constraint{EnsembleKalmanProcesses.ParameterDistributions.BoundedBelow}[Bounds: (200000.0, ∞)] over distribution EnsembleKalmanProcesses.ParameterDistributions.Parameterized(Distributions.Normal{Float64}(μ=24.153036641203013, σ=1.1528837102037748))
For a perfect model, we generate observations from the forward model itself. This is most easily done by creating an empty parameter file and running the 0th ensemble member:
@info "Generating observations"
parameter_file = CAL.parameter_path(output_dir, 0, 0)
mkpath(dirname(parameter_file))
touch(parameter_file)
simulation = CAL.forward_model(RadiativeFluxModelInterface(), 0, 0)Simulation
├── Running on: CPUSingleThreaded
├── Output folder: output/climaatmos_calibration/iteration_000/member_000/output_0000
├── Start date: 2010-01-01T00:00:00
├── Current time: 2.592e6 seconds
└── Stop time: 2.592e6 secondsLastly, we use the observation map itself to generate the observations.
observations = Vector{Float64}(undef, 1)
observations .= process_member_data(SimDir(simulation.output_dir))1-element Vector{Float64}:
126.61408233642578Now we are ready to run our calibration, putting it all together using the calibrate function. The WorkerBackend will automatically use all workers available to the main Julia process. Other backends are available for forward models that can't use workers or need to be parallelized internally. The simplest backend is the JuliaBackend, which runs all ensemble members sequentially and does not require Distributed.jl. For more information, see the Backends page.
user_initial_ensemble = EKP.construct_initial_ensemble(prior, ensemble_size)
ekp = EKP.EnsembleKalmanProcess(
user_initial_ensemble,
observations,
noise,
EKP.Inversion(),
EKP.default_options_dict(EKP.Inversion()),
)
eki = CAL.calibrate(
CAL.WorkerBackend(),
ekp,
RadiativeFluxModelInterface(),
n_iterations,
prior,
output_dir,
)EnsembleKalmanProcesses.EnsembleKalmanProcess{Float64, Int64, EnsembleKalmanProcesses.Inversion{Float64, Nothing, Nothing}, EnsembleKalmanProcesses.DataMisfitController{Float64, String}, EnsembleKalmanProcesses.NesterovAccelerator{Float64}, Vector{EnsembleKalmanProcesses.UpdateGroup}, Nothing}(EnsembleKalmanProcesses.DataContainers.DataContainer{Float64}[EnsembleKalmanProcesses.DataContainers.DataContainer{Float64}([24.99671355102559 25.54734380949775 … 23.921425495793812 26.47329653309471]), EnsembleKalmanProcesses.DataContainers.DataContainer{Float64}([25.206356560591036 25.631110055412456 … 24.186494825583818 25.54771501344902]), EnsembleKalmanProcesses.DataContainers.DataContainer{Float64}([25.690940180301517 25.766360931485156 … 24.89830069701687 25.776682036610918]), EnsembleKalmanProcesses.DataContainers.DataContainer{Float64}([25.796155162931075 25.723762965359576 … 25.584720160170708 25.726005959050603]), EnsembleKalmanProcesses.DataContainers.DataContainer{Float64}([25.729186451786486 25.732477239238193 … 25.905248109777542 25.733528071959093]), EnsembleKalmanProcesses.DataContainers.DataContainer{Float64}([25.730425680310944 25.73235015686471 … 25.83570823430849 25.73295730578049]), EnsembleKalmanProcesses.DataContainers.DataContainer{Float64}([25.730915716203945 25.732125377086714 … 25.804957919965553 25.732518086517896]), EnsembleKalmanProcesses.DataContainers.DataContainer{Float64}([25.731243095420652 25.731727245518908 … 25.76660450072734 25.73188816308125])], EnsembleKalmanProcesses.ObservationSeries{Vector{EnsembleKalmanProcesses.Observation{Vector{Vector{Float64}}, Vector{LinearAlgebra.Diagonal{Float64, Vector{Float64}}}, Vector{LinearAlgebra.Diagonal{Float64, Vector{Float64}}}, Vector{String}, Vector{UnitRange{Int64}}, Nothing}}, EnsembleKalmanProcesses.FixedMinibatcher{Vector{Vector{Int64}}, String, Random.TaskLocalRNG}, Vector{String}, Vector{Vector{Vector{Int64}}}, Nothing}(EnsembleKalmanProcesses.Observation{Vector{Vector{Float64}}, Vector{LinearAlgebra.Diagonal{Float64, Vector{Float64}}}, Vector{LinearAlgebra.Diagonal{Float64, Vector{Float64}}}, Vector{String}, Vector{UnitRange{Int64}}, Nothing}[EnsembleKalmanProcesses.Observation{Vector{Vector{Float64}}, Vector{LinearAlgebra.Diagonal{Float64, Vector{Float64}}}, Vector{LinearAlgebra.Diagonal{Float64, Vector{Float64}}}, Vector{String}, Vector{UnitRange{Int64}}, Nothing}([[126.61408233642578]], LinearAlgebra.Diagonal{Float64, Vector{Float64}}[[0.1;;]], LinearAlgebra.Diagonal{Float64, Vector{Float64}}[[10.0;;]], ["observation"], UnitRange{Int64}[1:1], nothing)], EnsembleKalmanProcesses.FixedMinibatcher{Vector{Vector{Int64}}, String, Random.TaskLocalRNG}([[1]], "order", Random.TaskLocalRNG()), ["series_1"], Dict("minibatch" => 1, "epoch" => 8), [[[1]], [[1]], [[1]], [[1]], [[1]], [[1]], [[1]], [[1]]], nothing), 30, EnsembleKalmanProcesses.DataContainers.DataContainer{Float64}[EnsembleKalmanProcesses.DataContainers.DataContainer{Float64}([29.16079330444336 87.675048828125 … 3.3956737518310547 556.8739013671875]), EnsembleKalmanProcesses.DataContainers.DataContainer{Float64}([44.34566879272461 103.65235900878906 … 5.769841194152832 87.7420425415039]), EnsembleKalmanProcesses.DataContainers.DataContainer{Float64}([116.82423400878906 135.8266143798828 … 23.951738357543945 138.651611328125]), EnsembleKalmanProcesses.DataContainers.DataContainer{Float64}([144.1542205810547 124.74158477783203 … 94.4792251586914 125.29816436767578]), EnsembleKalmanProcesses.DataContainers.DataContainer{Float64}([126.1023941040039 126.92815399169922 … 179.2600555419922 127.201904296875]), EnsembleKalmanProcesses.DataContainers.DataContainer{Float64}([126.41056823730469 126.89692687988281 … 156.00917053222656 127.05037689208984]), EnsembleKalmanProcesses.DataContainers.DataContainer{Float64}([126.53478240966797 126.8437728881836 … 146.71568298339844 126.94615173339844])], Dict("unweighted_loss" => [6068.944031266017, 8112.455401696289, 3226.815406952049, 186.63346475705305, 61.42029930035389, 225.09660613165127, 274.5175522011268], "crps" => [46.76754510979179, 66.72066877427937, 35.09145982592661, 12.36901670813655, 7.679321818152943, 8.975029692466945, 10.05414784495322], "bayes_loss" => [60689.47130983691, 81125.09191566095, 32269.467677991994, 1868.0633561034772, 616.0360624879327, 2252.809796920445, 2746.963277202658], "unweighted_avg_rmse" => [116.28616431107123, 92.60966488718987, 60.59377296368281, 32.714101457595824, 19.30810089111328, 15.31281763712565, 16.590499114990234], "avg_rmse" => [367.72913958757005, 292.8574743884405, 191.6143345883689, 103.45107221183707, 61.05757610824471, 48.423381128114784, 52.463764722376865], "loss" => [60689.440312660176, 81124.5540169629, 32268.154069520493, 1866.3346475705305, 614.2029930035388, 2250.966061316513, 2745.175522011268]), EnsembleKalmanProcesses.DataMisfitController{Float64, String}([7], 1.0, "stop"), EnsembleKalmanProcesses.NesterovAccelerator{Float64}([25.731016746634005 25.731832744594186 … 25.77934789179468 25.73209502037702], 0.20434762801820305), [5.720277390297905e-6, 2.5477811836794056e-5, 2.4874431775278118e-5, 4.469150509780221e-5, 0.0001121713169904586, 0.00016081799765916565, 0.000115091145673008], EnsembleKalmanProcesses.UpdateGroup[EnsembleKalmanProcesses.UpdateGroup([1], [1], Dict("[1,...,1]" => "[1,...,1]"))], EnsembleKalmanProcesses.Inversion{Float64, Nothing, Nothing}(nothing, nothing, false, 0.0), Random._GLOBAL_RNG(), EnsembleKalmanProcesses.FailureHandler{EnsembleKalmanProcesses.Inversion, EnsembleKalmanProcesses.SampleSuccGauss}(EnsembleKalmanProcesses.var"#failsafe_update#174"()), EnsembleKalmanProcesses.Localizers.Localizer{EnsembleKalmanProcesses.Localizers.SECNice, Float64}(EnsembleKalmanProcesses.Localizers.var"#13#14"{EnsembleKalmanProcesses.Localizers.SECNice{Float64}}(EnsembleKalmanProcesses.Localizers.SECNice{Float64}(1000, 1.0, 1.0))), 0.1, nothing, false)This page was generated using Literate.jl.