First ML Applet¶
You build SineScope, a small MLP that learns y = sin(x) from noisy samples. It adds one capability at each step.
The applet shows a live loss curve, the model curve as it settles through the scattered points, and the weight matrix as a heatmap.
Synthetic data keeps the applet self-contained, so it needs no downloads.
flowchart LR
frame[Frame thread] -->|submits job| worker[Worker thread]
worker -->|publishes copies under mutex| state[Shared state]
state -->|generation changes| frame
The frame thread submits the training job, the worker publishes results, and the frame thread draws them when the generation changes.
SineScope is in examples/sine_scope/. Every code block below comes verbatim from that source.
The release preset builds a copy beside the executable, so you can run the finished applet first:
cmake --preset release
cmake --build --preset release
CALIPER_AUTOLAUNCH=dev.example.sine-scope ./cmake-build-release/caliper
Before you start, read Development basics and Your first applet.
Build and Manifest¶
The manifest requires what training needs and marks visualization as optional. Thus the applet still runs without the bridge:
[applet]
id = "dev.example.sine-scope"
name = "SineScope"
version = "0.1.0"
summary = "Tutorial applet: a tiny MLP learns sin(x) live — loss curve, prediction vs target, first-layer weights as a heatmap."
tag = "Demo"
[compat]
abi_epoch = 3
min_host = "0.6.0"
[services]
required = ["caliper.ui.v1", "caliper.log.v1",
"caliper.jobs.v1", "caliper.device.v1"]
optional = ["caliper.tensor_bridge.v1", "caliper.metrics.v1"]
The CMake file is the hello file plus one word, TORCH, and this is the entire ML build change.
TORCH links the libtorch that the host uses, which the SDK names. It also stamps the libtorch version into the built manifest.
As a result, the host refuses the applet if it runs beside another libtorch:
# SineScope, the ML tutorial applet. On its own it builds against an installed
# SDK that was built with libtorch:
# cmake -S . -B build -DCMAKE_PREFIX_PATH=<sdk prefix>
# cmake --build build
if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
cmake_minimum_required(VERSION 3.18)
project(sine_scope LANGUAGES CXX)
find_package(caliper-sdk 0.2 CONFIG REQUIRED)
endif()
caliper_add_applet(sine_scope
SOURCES sine_scope.cpp
MANIFEST sine_scope.caliper.toml
TORCH)
Local Copy¶
Build your copy in a folder of its own against the installed SDK, as Your first applet does for hello.
Set CALIPER to the host you built. The SDK must come from a core build with libtorch, as the release preset is:
mkdir -p "$HOME/caliper-applets"
cp -R examples/sine_scope "$HOME/caliper-applets/sine_scope"
cd "$HOME/caliper-applets/sine_scope"
cmake -S . -B build -DCMAKE_PREFIX_PATH="$HOME/caliper-sdk" -DCMAKE_BUILD_TYPE=Release
cmake --build build
"$CALIPER" check build/applets
CALIPER_AUTOLAUNCH=dev.example.sine-scope "$CALIPER" dev build/applets
caliper dev searches your build folder first. At equal versions, the host loads your copy and not the copy beside the executable.
The host keeps a library loaded until it quits, so quit Caliper after each rebuild and run caliper dev again.
Model and State Spine¶
Two layers are enough to bend a line into a sine:
// Two layers are enough to bend a line into a sine.
struct SineNetImpl : torch::nn::Module {
torch::nn::Linear fc1{nullptr}, fc2{nullptr};
SineNetImpl() {
fc1 = register_module("fc1", torch::nn::Linear(1, 32));
fc2 = register_module("fc2", torch::nn::Linear(32, 1));
}
torch::Tensor forward(torch::Tensor x) {
return fc2->forward(torch::tanh(fc1->forward(x)));
}
};
TORCH_MODULE(SineNet);
Every live applet uses the same state skeleton: service wrappers, one mutex, published copies and a generation counter:
// The spine every live applet shares: service wrappers, one mutex,
// published copies, a generation counter (cookbook §1).
struct SineState {
caliper::Host* host = nullptr;
caliper::Jobs jobs; // required (manifest-enforced)
caliper::Bridge bridge; // optional — falsy-inert when absent
uint64_t job_id = 0;
// -- cross-thread, under mtx --
std::mutex mtx;
std::vector<float> loss_hist;
std::vector<float> pred_ys; // model(x) on the fixed 256-point grid
std::vector<float> data_xs, data_ys; // the noisy training samples
torch::Tensor disp_w; // weight display tensor (handle swap)
float w_max = 1e-6f;
uint64_t gen = 0; // bumped per publish (0 = none yet)
// -- frame-thread only --
uint64_t seen_gen = 0, tex_gen = 0;
CaliperTextureId w_tex = 0;
bool follow = true;
};
on_init probes the services. The manifest already guarantees that the required services exist, so jobs need no null checks.
The optional bridge is falsy-inert: you can call it unconditionally, and it does nothing when absent.
A good demo still shows the degradation, as the Tensor Texture step does:
bool on_init(caliper::Host& host) override {
auto* st = s_.get();
st->host = &host;
st->jobs = caliper::Jobs(host); // required — manifest enforced
st->bridge = caliper::Bridge(host); // optional — may be falsy
host.log_info("sine_scope: on_init");
return true;
}
Training Job¶
Never compute on the frame thread. A job is a plain function that the host runs on a worker thread. The job checks for cancel at each step, because jobs must respond to cancel within 100 ms. It also reports progress, which appears in the jobs tray of the host:
// The training job: a plain function the host runs on a worker thread.
void train_job(void* user, const CaliperJobControl* ctl) {
auto* st = static_cast<SineState*>(user);
// device.v1 -> torch device: METAL means MPS on Apple, CUDA on Windows/Linux.
auto d = caliper::Device::query(*st->host);
torch::Device dev =
(d.kind == CALIPER_DEV_CUDA && torch::cuda::is_available())
? torch::Device(torch::kCUDA)
: (d.kind == CALIPER_DEV_METAL) ? torch::Device(torch::kMPS)
: torch::Device(torch::kCPU);
// Synthetic dataset: 256 noisy samples of y = sin(x) at random x in
// [-pi, pi], drawn once (fixed seed). The model is drawn on an even grid.
torch::manual_seed(0);
auto X = ((torch::rand({256, 1}) * 2 - 1) * M_PI).to(dev);
auto Y = torch::sin(X) + 0.15 * torch::randn({256, 1}).to(dev);
auto grid = torch::linspace(-M_PI, M_PI, 256,
torch::TensorOptions().device(dev))
.unsqueeze(1);
{
auto xc = X.to(torch::kCPU).contiguous();
auto yc = Y.to(torch::kCPU).contiguous();
std::lock_guard<std::mutex> lk(st->mtx);
st->data_xs.assign(xc.data_ptr<float>(), xc.data_ptr<float>() + 256);
st->data_ys.assign(yc.data_ptr<float>(), yc.data_ptr<float>() + 256);
}
SineNet model;
model->to(dev);
torch::optim::Adam opt(model->parameters(),
torch::optim::AdamOptions(1e-2));
for (int step = 0; step < 2000; step++) {
if (ctl->cancelled(ctl)) return; // <=100 ms contract
opt.zero_grad();
auto loss = torch::mse_loss(model->forward(X), Y);
loss.backward();
opt.step();
publish(st, model, grid, loss.item<float>());
ctl->progress(ctl, step / 2000.f, "fitting sin(x)");
}
ctl->progress(ctl, 1.f, "done");
}
The frame side submits the job on click, shows progress and offers cancel:
if (!running) {
if (ImGui::Button("Train"))
st->job_id = st->jobs.submit("sine_scope: fit",
&train_job, st);
} else {
if (ImGui::Button("Cancel")) st->jobs.request_cancel(st->job_id);
ImGui::SameLine();
ImGui::ProgressBar(st->jobs.progress_of(st->job_id), {-1, 0});
}
Live Plotting¶
The worker publishes owned copies of the plot data and a tensor handle for the weight display. It does this under the mutex and then bumps the generation:
// WORKER side: compute outside the lock, swap inside it, bump the gen.
void publish(SineState* st, SineNet& model, const torch::Tensor& X,
float loss) {
torch::NoGradGuard ng;
auto pred = model->forward(X).to(torch::kCPU).contiguous(); // (256,1)
// First-layer weights (32,1) -> 8x4 grid -> x16 hard blocks (cookbook
// §4), staged to CPU for tutorial simplicity — the exemplar shows the
// zero-copy device pull (cookbook §3).
auto w = model->fc1->weight.detach()
.reshape({8, 4})
.repeat_interleave(16, 0).repeat_interleave(16, 1)
.to(torch::kCPU).contiguous(); // (128,64)
const float wmax = w.abs().max().item<float>();
std::lock_guard<std::mutex> lk(st->mtx);
st->loss_hist.push_back(loss);
st->pred_ys.assign(pred.data_ptr<float>(),
pred.data_ptr<float>() + 256);
st->disp_w = w; // handle swap — no data copy
st->w_max = std::max(wmax, 1e-6f);
st->gen++;
}
The frame consumes the data when the generation moves, then draws it.
The prediction curve settles through the noisy samples with a PlotScatter and a PlotLine.
The loss curve also uses the follow-toggle idiom:
// These plots are for *viewing*, not editing: ImPlot is interactive by
// default (drag-pan, scroll-zoom, box-select, right-click menu), so
// lock every input off. Read-only plots always want these four flags.
constexpr ImPlotFlags kLockedPlot =
ImPlotFlags_NoInputs | ImPlotFlags_NoMenus |
ImPlotFlags_NoBoxSelect | ImPlotFlags_NoMouseText;
// The display grid is a frame-side constant.
static std::vector<float> xs;
if (xs.empty()) {
xs.resize(256);
for (int i = 0; i < 256; i++)
xs[i] = -3.14159265f + i / 255.0f * 6.2831853f;
}
if (ImPlot::BeginPlot("fit", {-1, 240}, kLockedPlot)) {
ImPlot::SetupAxes("x", "y", 0, 0);
ImPlot::SetupAxesLimits(-3.3, 3.3, -1.6, 1.6, ImPlotCond_Always);
if (!data_xs.empty()) {
ImPlot::PlotScatter("data: sin(x) + noise", data_xs.data(),
data_ys.data(), (int)data_xs.size(),
{ImPlotProp_Marker, ImPlotMarker_Circle,
ImPlotProp_MarkerSize, 2.5f});
}
if (!pred.empty())
ImPlot::PlotLine("model(x)", xs.data(), pred.data(), 256);
ImPlot::EndPlot();
}
ImGui::Checkbox("follow", &st->follow); // viewport policy, §6
const ImPlotAxisFlags f =
st->follow ? ImPlotAxisFlags_AutoFit : 0;
if (ImPlot::BeginPlot("loss", {-1, 160}, kLockedPlot)) {
ImPlot::SetupAxes("step", "MSE", f, f);
if (!loss.empty())
ImPlot::PlotLine("mse", loss.data(), (int)loss.size());
ImPlot::EndPlot();
}
Tensor Texture¶
The weight matrix appears as a colormapped texture. The code runs on the frame thread only, is gated by the generation, and releases the texture in cleanup. When the bridge is absent, the panel says so instead of failing:
// The weight matrix as pixels — gen-gated rebuild, frame thread only.
if (st->bridge && gen != 0 && gen != st->tex_gen &&
disp_w.defined()) {
if (st->w_tex) st->bridge.release_texture(st->w_tex);
auto ct = caliper::adapters::to_tensor(disp_w);
st->w_tex = ct ? st->bridge.texture_from_tensor_mapped(
&*ct, CALIPER_CMAP_RDBU, -w_max, w_max)
: 0;
st->tex_gen = gen;
}
if (st->w_tex) {
ImGui::TextDisabled("fc1 weights (32x1 as 8x4 blocks, RdBu)");
ImGui::Image(caliper::Bridge::imtex(st->w_tex), ImVec2(128, 256));
} else if (!st->bridge) {
ImGui::TextDisabled("tensor_bridge.v1 absent: no weight heatmap");
} else {
ImGui::TextDisabled("fc1 weights appear once training starts");
}
This tutorial copies the weights to the CPU for simplicity. tensor_bridge.v1 also draws device tensors without them leaving the GPU.
Cleanup adds its symmetric duties: cancel, bounded wait and release:
void on_cleanup() override {
auto* st = s_.get();
if (st->job_id) {
st->jobs.request_cancel(st->job_id);
for (int i = 0; i < 1000 && st->jobs.is_running(st->job_id); i++)
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
if (st->w_tex) { st->bridge.release_texture(st->w_tex);
st->w_tex = 0; }
if (st->host) st->host->log_info("sine_scope: on_cleanup");
}
Run it with CALIPER_AUTOLAUNCH=dev.example.sine-scope "$CALIPER" dev build/applets.
Within seconds, the flat line snaps into a sine while the heatmap blocks reorganize.
Real Data¶
Everything above still holds, and only the data acquisition changes. Follow these rules:
- Fetch inside the job.
- Cache in
host.data_dir(). - Write atomically with a
.tmpfile and a rename. - Self-heal corrupt caches.
- Make the transfer cancellable with the progress callback of curl.
- Add
CURL::libcurlandZLIB::ZLIBto the CMake links, found withfind_package(CURL)andfind_package(ZLIB).
Remaining Services¶
Each remaining service is a small change from here:
metrics.v1: Callrun = metrics.begin_run("sine", "mlp32")once, thenmetrics.scalar(run, "train/loss", step, loss)in the loop. The run then survives restarts in the metrics store of the host. The host has no view of stored runs.artifacts.v1: Add Save and Load buttons so a trained model outlives the process. Load and then evaluate without retraining.data.v1: When your published state is tabular, register it and ask SQL questions.