Skip to content

Embedding API

Caliper Embed is the framework core. It holds the applet loader, the service registry, the host-neutral services, HostRenderer (Metal or Vulkan) and the tensor bridge. Its code is the static library libcaliper. The caliper-embed package installs it as one shared library, libcaliper_embed.dylib on macOS and caliper_embed.dll on Windows. A small C ABI sits in front of the library. Thus a host binary can run the applet canvas inside a view it owns without linking ImGui, torch or any renderer type.

The caliper executable is the first embedder. The second is examples/embed_host/, an AppKit host with a Win32 counterpart and an offscreen mode, and this page mirrors it. A program outside this repository builds against the installed caliper-embed package. The guide Embed Caliper in a program shows the steps.

This page describes the embedder-facing contract, not the applet-facing ABI. Applets link caliper::sdk and use caliper/abi.h and the C++ sugar. The header caliper/embed.h sits on a separate include root, so an applet cannot #include <caliper/embed.h>. If both packages share one prefix, the header is still reachable as <caliper-embed/caliper/embed.h> through the include/ root of the SDK. Install the two packages into separate prefixes when the separation must be complete.

The ABI runs with Metal on Apple Silicon and with Vulkan and an HWND on Windows. CALIPER_EMBED_API_VERSION is 1. The labels v1.1 to v1.4 in this page and in the headers name additive sections of that version, and they are also its minor numbers. The interface is version 1.4.0 (Versions). No struct changed in these sections, so a caller built against the first header still links and runs.

Core Calls

An embedder drives the core with five calls and pumps frames from its own event loop. The core never owns the process loop, which is the difference between a library and a host.

  1. caliper_core_create creates the core: renderer, services and loader.
  2. caliper_core_attach_canvas gives the core the native view (NSView* or HWND) to paint, or selects an offscreen target.
  3. caliper_core_load_applet launches one applet by manifest id, for example dev.caliper.embed-scope. Attach a canvas first, because the first frame of an applet touches the ImGui backend of the renderer. Loading before attach is a refusal, not a crash.
  4. caliper_core_frame and caliper_core_event pump exactly one frame from your loop (a timer, a CVDisplayLink or a Win32 message loop) and forward your toolkit input as CaliperInputEvent values.
  5. caliper_core_shutdown tears everything down in the reverse order of create and clears the one-core-per-process lock.
CaliperCoreDesc desc = { .struct_size = sizeof desc };
desc.renderer = CALIPER_RENDERER_DEFAULT;      /* Metal on Apple, Vulkan on Windows */
CaliperCore* core = caliper_core_create(&desc);

CaliperCanvasDesc canvas = { .struct_size = sizeof canvas };
canvas.mode = CALIPER_CANVAS_WINDOW;           /* native_view is an NSView* / HWND */
canvas.width = w; canvas.height = h; canvas.content_scale = scale;
caliper_core_attach_canvas(core, native_view, &canvas);

caliper_core_load_applet(core, "dev.caliper.embed-scope");

/* ... from YOUR event loop, once per frame: */
caliper_core_frame(core);
/* ... on each input, translated to a toolkit-neutral event: */
caliper_core_event(core, &event);

caliper_core_shutdown(core);

embed.h Functions

The lifecycle, applet control and readback calls:

Call Signature Description
caliper_core_create CaliperCore* (const CaliperCoreDesc* desc) Create the core, which holds the ImGui context, the renderer, the service registry and the loader. Return NULL and log the reason for a second live core, a renderer that this system does not support or CALIPER_RENDERER=gl. The renderer starts at caliper_core_attach_canvas.
caliper_core_shutdown void (CaliperCore* core) Tear down the core in the reverse order of creation: unload the applet, join the jobs, close the stores and drop the renderer and the ImGui context. Safe on NULL. The call also ends the one-core-per-process limit, and the CaliperCore* is dead afterward.
caliper_core_attach_canvas int (CaliperCore* core, void* native_view, const CaliperCanvasDesc* desc) Attach the one canvas of the core. native_view is an NSView* or an HWND for CALIPER_CANVAS_WINDOW, and NULL for CALIPER_CANVAS_OFFSCREEN. Return 1 on success, or 0 when the core refuses because the renderer could not start, a canvas is attached already or the size is invalid. A refusal leaves the core usable and sets the last error. When the renderer could not start, the last error is "attach_canvas: the Metal renderer could not start (), and there is no fallback renderer until the WebGPU fallback through Dawn lands", with Vulkan on Windows.
caliper_core_frame void (CaliperCore* core) Run exactly one frame: clear the canvas, draw the loaded applet under the crash guard, then composite and present or store the result. The call never polls, sleeps or waits for vsync. Without an attached canvas it does nothing except set the last error.
caliper_core_event void (CaliperCore* core, const CaliperInputEvent* event) Feed one input event into the core. The call does nothing before a canvas exists.
caliper_core_load_applet int (CaliperCore* core, const char* manifest_id) Load and launch the applet whose manifest id is manifest_id, for example dev.example.my-applet. Return 1 on success, or 0 when the id is unknown or the launch is refused or fails, with the last error set. Attach a canvas first, because the first frame of an applet touches the ImGui backend of the renderer. The core tears down a loaded applet first, so reloading the same id restarts the applet with no carried state, and a failed launch leaves no applet loaded. An unknown id is the one exception: the call refuses it at once and leaves a running applet alone.
caliper_core_unload_applet void (CaliperCore* core) Tear down the loaded applet by joining its jobs and then dropping the instance. The call does nothing when no applet is loaded. Call it between frames.
caliper_core_read_pixels int (CaliperCore* core, void* buf, int stride) Copy the last composited frame to buf as tightly packed RGBA8 with stride bytes per row, where stride is at least the width times 4. Return 1 on success, or 0 when the canvas is not offscreen, buf is NULL or stride is too small.
caliper_core_last_error const char* (CaliperCore* core) Return the reason for the most recent refusal, or an empty string when there is none. The string is never NULL for a live core and stays valid until the next call on that core.

The service call is in Host Service Access, the view calls are in Built-In Tensor Views and the version call is in Versions. The header caliper/live_views.h declares the typed live-view calls (caliper_core_live_*), described in Typed Live Views.

embed.h Types

CaliperCore

The opaque handle of one core. A process holds one live core at a time.

CaliperRenderer

The HostRenderer backend that the core embeds.

There is no fallback renderer. caliper_core_create refuses when CALIPER_RENDERER=gl asks for the removed OpenGL renderer, and caliper_core_attach_canvas refuses when the backend cannot start, with a last error that names the renderer and why it could not start.

Constant Value Description
CALIPER_RENDERER_DEFAULT 0 The platform backend, Metal on Apple and Vulkan on Windows.
CALIPER_RENDERER_METAL 1 The Metal backend.
CALIPER_RENDERER_VULKAN 2 The Vulkan backend.

CaliperLogFn

The diagnostics sink of a core.

The callback receives two streams, which differ by a prefix on the message. Core diagnostics such as the renderer choice, refusals and crash text arrive untagged. Applet caliper.log.v1 lines arrive tagged with [applet]. level is a CaliperLogLevel value, from 0 for debug to 3 for error. message is valid only during the call. The core calls the sink from the frame thread for its own lines and from any thread for applet lines, so a sink that touches shared UI state must marshal to its UI thread. With a NULL sink, both streams go to stderr.

typedef void (*CaliperLogFn)(void* userdata, int level, const char* message);

CaliperCrashFn

The applet-fault callback of a core.

The core fires it after it has quarantined and torn down the faulting applet, and the core keeps running. applet_id and fault are valid only during the call. With a NULL callback, the core logs the fault and swallows it.

typedef void (*CaliperCrashFn)(void* userdata, const char* applet_id, const char* fault);

CaliperCoreDesc

The settings of a core, which caliper_core_create takes.

Set struct_size to sizeof(CaliperCoreDesc) and zero every field that you do not use.

Field Type Description
struct_size size_t sizeof(CaliperCoreDesc), as the caller built it. It must be the first member.
renderer CaliperRenderer The backend to embed.
data_dir const char* The per-core app-data root, or NULL for the default of the operating system. A directory (created if missing) holds the metrics, artifacts and applet data stores of this core and the window layout in imgui.ini. With NULL, the core keeps no layout and writes nothing to the working directory. The setting lasts for the one live core and ends at shutdown.
applets_dir const char* An extra applet search folder, or NULL for the default discovery.
log_fn CaliperLogFn The diagnostics sink, or NULL for stderr.
crash_fn CaliperCrashFn The applet-fault callback, or NULL to log and swallow faults.
userdata void* The pointer that the core passes back to log_fn and crash_fn.

CaliperCanvasMode

The kind of canvas that caliper_core_attach_canvas creates.

Constant Value Description
CALIPER_CANVAS_WINDOW 0 The canvas paints into a native view. native_view is an NSView* or an HWND.
CALIPER_CANVAS_OFFSCREEN 1 The canvas has no view. The core renders to a texture, which caliper_core_read_pixels reads back.

CaliperCanvasDesc

The settings of the canvas, which caliper_core_attach_canvas takes.

Field Type Description
struct_size size_t sizeof(CaliperCanvasDesc), as the caller built it. It must be the first member.
mode CaliperCanvasMode Whether the canvas paints into a native view or renders offscreen.
width int The width of the canvas in physical pixels.
height int The height of the canvas in physical pixels.
content_scale float The display scale, where 1.0 is one pixel per point. A value of 0 or less means 1.0.

CaliperEventType

The type of an input event.

Each constant names the fields of CaliperInputEvent that the core reads for that type.

Constant Value Description
CALIPER_EVENT_MOUSE_MOVE 0 The mouse moved. The core reads x and y, in physical pixels.
CALIPER_EVENT_MOUSE_BUTTON 1 A mouse button changed. The core reads button and down.
CALIPER_EVENT_MOUSE_SCROLL 2 The mouse wheel or a trackpad scrolled. The core reads dx and dy.
CALIPER_EVENT_KEY 3 A key changed. The core reads key, which is an ImGuiKey value, and down and mods.
CALIPER_EVENT_TEXT 4 A character was typed. The core reads codepoint.
CALIPER_EVENT_RESIZE 5 The canvas changed size. The core reads width and height, in physical pixels.
CALIPER_EVENT_CONTENT_SCALE 6 The display scale changed. The core reads scale.
CALIPER_EVENT_FOCUS 7 The canvas gained or lost focus. The core reads focused, which is 0 or 1.

CaliperInputEvent

One toolkit-neutral input event.

The core reads only the fields that the comment of the CaliperEventType constant names. Leave the other fields zero.

Field Type Description
struct_size size_t sizeof(CaliperInputEvent), as the caller built it. It must be the first member.
type CaliperEventType The type of the event.
x, y float The mouse position in physical pixels.
dx, dy float The scroll delta.
button int The mouse button: 0 for left, 1 for right and 2 for middle.
down int The press state of a button or key event: 1 for down and 0 for up.
key int The key, as an ImGuiKey value.
mods int The modifier state of a key event, as a bit set of the CALIPER_MOD_* flags.
codepoint unsigned int The typed character as a UTF-32 code point.
width, height int The new size of the canvas in physical pixels.
scale float The new display scale.
focused int 1 when the canvas has focus, otherwise 0.

The modifier flags of CaliperInputEvent.mods are constants:

Name Value Description
CALIPER_MOD_CTRL 1 << 0 Bit flag in CaliperInputEvent.mods for the Control key.
CALIPER_MOD_SHIFT 1 << 1 Bit flag in CaliperInputEvent.mods for the Shift key.
CALIPER_MOD_ALT 1 << 2 Bit flag in CaliperInputEvent.mods for the Alt key.
CALIPER_MOD_SUPER 1 << 3 Bit flag in CaliperInputEvent.mods for the Super key.

Ownership

Caliper Embed owns the applet canvas end to end. The embedder supplies a native child view, and the core runs the ImGui context, HostRenderer and bridge inside it. The chrome of a host (docking, property grids, menus) wraps around those canvases and never paints applet pixels.

Concern Owner Note
Process event loop Embedder caliper_core_frame does one frame and returns, with no polling and no vsync wait
Native window / view handle Embedder NSView* / HWND passed to attach_canvas
Input events Embedder translates, core consumes Your GLFW, AppKit or wx event becomes a CaliperInputEvent. No toolkit types cross.
ImGui context (one per canvas) Caliper Embed The embedder never touches ImGui state
HostRenderer + tensor bridge Caliper Embed The zero-copy claim travels with the core
Applet loader + service registry + services Caliper Embed The same registry that applets see
libtorch (one per process) Caliper Embed The embedder must NOT link its own torch, because the core owns the device and pack policy
Crash containment Caliper Embed The core guard catches applet faults and reports them through crash_fn. The embedder stays up.

The signal handlers of the guard are installed once per process. They pass faults outside applet calls on to the handlers installed before them, so the crash reporter of an embedder still sees its own crashes (trust model).

Per-Core Settings and Limits

  • One CaliperCore per process. caliper_core_create returns NULL for a second live core, because the one-libtorch-per-process policy already binds the process. Shut the first core down first. It also returns NULL for a renderer that the platform does not build, and for CALIPER_RENDERER=gl. The renderer itself starts at caliper_core_attach_canvas.
  • One canvas per core. caliper_core_attach_canvas refuses a second canvas. It returns 0 with last_error set when the renderer could not start, and the message names the renderer and the reason. A canvas-info query and several canvases per core are not provided.
  • CaliperCoreDesc.data_dir moves the app-data folder. A non-NULL directory (created if missing) replaces the app-data folder for that core. This covers the metrics, data and artifacts stores, the applet data folders data/<id>/, and the user applets folder applets/ that the core searches, unless CALIPER_USER_APPLETS_DIR names another one. The window layout is kept at <data_dir>/imgui.ini. The override lasts for the one live core and ends at shutdown.
  • Without data_dir, CALIPER_DATA_DIR decides. With NULL the core uses the folder that CALIPER_DATA_DIR names when it is set and not empty. Otherwise it uses the folder of the operating system. The core then keeps no window layout: it reads and writes no imgui.ini, so every run starts with the default layout and nothing lands in the working directory. The process reads CALIPER_DATA_DIR once, at the first lookup.
  • Live session files follow CALIPER_DATA_DIR first. The session files under live/ (see Live Session Layout) are found in an explicit root when the caller gives one. Otherwise the core looks in CALIPER_DATA_DIR, and only then in its data_dir or the folder of the operating system.
  • CaliperCoreDesc.applets_dir is searched first. It replaces the --applets folders of the caliper executable in the search order. As with those folders, a folder with no manifest but with an applets/ subfolder that has one stands for that subfolder, so you can pass a build folder as it is.
  • Applet log lines reach log_fn. When the embedder sets log_fn, the applet caliper.log.v1 service routes there with the prefix [applet]. Core diagnostics (renderer choice, refusals, crash text) arrive untagged. With log_fn unset, both go to stderr. The core calls log_fn from the frame thread for its own lines and from any thread for applet lines. A sink that touches shared UI state must marshal to its UI thread.
  • Window mode has no automated test. Run embed_host on each platform to check a windowed canvas. The offscreen read_pixels tests check byte-exactness on both backends.
  • The Windows package build is untested. The package and its offscreen mode have not run on Windows.
  • No fallback renderer. The core embeds Metal on macOS and Vulkan on Windows. When that renderer cannot start, attach_canvas returns 0 and last_error names it and the reason, as in "attach_canvas: the Metal renderer could not start (no Metal device), and there is no fallback renderer until the WebGPU fallback through Dawn lands". The core stays usable. CALIPER_RENDERER=gl asks for the removed OpenGL renderer, and caliper_core_create returns NULL for it (Renderer Refusals).
  • METAL views do not copy tensor bytes. The cost of a view update on the METAL path does not grow with the tensor size (Device Paths).

All calls except the any-thread services below belong to one thread, the one that calls caliper_core_frame.

Versions

embed.h versions the interface in one encoding, (major << 16) | (minor << 8) | patch, which CALIPER_EMBED_MAKE_VERSION builds:

Name Value Description
CALIPER_EMBED_API_VERSION 1 The major version of this ABI, which is the major part of CALIPER_EMBED_VERSION. It bumps when the ABI grows a field. Every struct starts with struct_size, which is the compatibility gate. The core requires struct_size to be at least its own sizeof for the struct and refuses a smaller one, so a caller built against an older header is rejected and never misread. Fields are append-only and land after the old ones. A caller built against a header at least as new as the core passes the gate and finds every field the core reads. A newer caller with an older core is not supported.
CALIPER_EMBED_MAKE_VERSION(major, minor, patch) (((major) << 16) | ((minor) << 8) | (patch)) Build a version number from its parts, in the encoding (major << 16) | (minor << 8) | patch. The macro is an integer constant expression, so #if can test it.
CALIPER_EMBED_VERSION_MAJOR CALIPER_EMBED_API_VERSION The major version of this header, which equals CALIPER_EMBED_API_VERSION. It bumps when a struct grows.
CALIPER_EMBED_VERSION_MINOR 4 The minor version of this header. It counts the additive sections: v1.1 services, v1.2 tensor views, v1.3 typed live views and v1.4 the version call.
CALIPER_EMBED_VERSION_PATCH 0 The patch version of this header. It counts library fixes that change no declaration.
CALIPER_EMBED_VERSION CALIPER_EMBED_MAKE_VERSION(CALIPER_EMBED_VERSION_MAJOR, CALIPER_EMBED_VERSION_MINOR, CALIPER_EMBED_VERSION_PATCH) The version of this header, built with CALIPER_EMBED_MAKE_VERSION from the major, minor and patch parts.

The call caliper_embed_api_version returns the version of the loaded library:

Call Signature Description
caliper_embed_api_version uint32_t (void) Return the version of the library that the process loaded, in the encoding of CALIPER_EMBED_VERSION. An embedder runs on a library of the same major whose minor is at least CALIPER_EMBED_VERSION_MINOR. The call needs no core and may run on any thread.

CALIPER_EMBED_VERSION is the version of the header that an embedder compiled against. caliper_embed_api_version() returns the version of the library that the process loaded, which is the CALIPER_EMBED_VERSION of the header the library was built from. An embedder runs on a library of the same major whose minor is at least the minor of the header:

uint32_t lib = caliper_embed_api_version();
if ((lib >> 16) != CALIPER_EMBED_VERSION_MAJOR ||
    ((lib >> 8) & 0xff) < CALIPER_EMBED_VERSION_MINOR) {
    /* another major, or a library older than this header: do not embed it */
}

The macros are integer constant expressions, so #if can test them. The call needs no core and may run on any thread. CALIPER_EMBED_HAVE_VIEWS stays defined as 1 for code that tests for the views. The caliper-embed package carries the same version.

Host Service Access

Call Signature Description
caliper_core_get_service const void* (CaliperCore* core, const char* id) Return the service table that an applet receives from CaliperHost.get_service for id, such as caliper.metrics.v1 or caliper.jobs.v1, or NULL for an unknown id or a NULL core. Cast the result to the matching struct of the caliper/services headers and call its function pointers as an applet does. The table is static for the process and valid from creation until caliper_core_shutdown. The metrics, artifacts, data, jobs, device and log services may run on any thread, while the tensor bridge, geometry and UI services are frame-thread only.

caliper_core_get_service(core, id) returns the same service table that an applet receives from CaliperHost.get_service for that id. Examples are "caliper.metrics.v1", "caliper.jobs.v1", "caliper.artifacts.v1" and "caliper.data.v1". Cast the result to the matching struct from the caliper/services headers and call its function pointers as an applet would. No renderer, torch or ImGui type crosses the seam. The interchange is the C ABI, CaliperTensor and Arrow C streams. A C++ host can use the caliper.hpp sugar. The call returns NULL for an unknown id or a NULL core. The pointer is a process-static table, valid from create until shutdown.

The header states a thread rule for each service:

Service Thread rule
caliper.metrics.v1 Any thread. The store holds one DuckDB connection under one mutex, so reads from a host thread serialize with applet writes.
caliper.artifacts.v1 Any thread, under the same one-connection model. path_of returns a thread-local buffer, valid until the next artifacts call on that thread.
caliper.data.v1 Any thread, under one mutex. last_error() is thread-local, so each thread sees its own last failure.
caliper.jobs.v1 Any thread, by design: submit, cancel, is_running and progress work over the process job system.
caliper.device.v1 Any thread. It reads a record negotiated at startup that never changes.
caliper.log.v1 Any thread. It is reentrant and routes to log_fn when one is installed.
caliper.tensor_bridge.v1, v1_1, v1_2 Frame thread only. They upload to the GPU.
caliper.ui.v1 Frame thread only. It wraps the ImGui and ImPlot contexts, which a host has no use for.

A host pushes parameters, and an applet worker produces device tensors, because there is one torch per process and it is never the host torch. The host-side use of the bridge is CPU-staged uploads on the frame thread.

Built-In Tensor Views

The view section of caliper/embed.h lets a host hand the core a CaliperTensor and have the core draw it. The core makes a texture through the process tensor bridge and adds an ImGui window titled with the view name. It composites the window in caliper_core_frame after the draw of the loaded applet. Views work with no applet loaded and alongside one. No ImGui, renderer or texture type crosses the seam, because the caller only names views and passes tensors. The caliper.show call of the Python entry point uses this surface.

The section is additive: CALIPER_EMBED_API_VERSION stays 1 and no existing struct changed. CALIPER_EMBED_HAVE_VIEWS is defined as 1, so a host can test for views at compile time.

Call Signature Description
caliper_core_view_tensor int (CaliperCore* core, const CaliperViewDesc* desc) Create the view named desc->name, or update it when it exists. Return 1 on success, or 0 with the last error set. A failed first show leaves no view, and a failed update keeps the previous pixels of the view. A different vmin, vmax or colormap on an existing f32 view maps the new tensor into the same texture, while a different shape or dtype recreates the texture.
caliper_core_view_remove int (CaliperCore* core, const char* name) Remove the view named name and release its texture and import. Return 1 if the view existed and was removed, otherwise 0.
caliper_core_view_count int (CaliperCore* core) Return the number of views.
caliper_core_view_info int (CaliperCore* core, const char* name, CaliperViewInfo* out) Fill out with the measured state of the view named name. Return 1 on success, otherwise 0.
caliper_core_view_readback int (CaliperCore* core, const char* name, void* buf, size_t buf_bytes) Copy the texture of the view named name, not the canvas, to buf as tightly packed RGBA8 of width*height*4 bytes, for tests and measurement. buf_bytes is the size of buf. Return 1 on success, otherwise 0.
caliper_core_colormap_lut int (int32_t colormap, uint32_t out256[256]) Copy the built-in 256-entry RGBA8 table of colormap to out256, as a CPU reference for tests. Each entry packs r | g<<8 | b<<16 | a<<24. Return 1 on success, otherwise 0. The call needs no core and may run on any thread.

CaliperViewDesc

One tensor view to create or update, which caliper_core_view_tensor takes.

The core accepts two layouts and refuses any other with a reason in the last error. A 2-D f32 tensor of shape (H,W) is colormapped over [vmin, vmax]. A 3-D u8 tensor of shape (H,W,4) is RGBA and shows as is. The tensor must be row-major contiguous, with strides in elements and each dimension in 1 to 16384, on device CPU or METAL.

For a CPU tensor, the core reads the bytes at data + byte_offset and copies them before the call returns. For a METAL tensor, data is an in-process id<MTLBuffer> and the renderer reads it in place without a copy. The call fails when the device path refuses, and the core never downloads a METAL tensor to the host. The GPU reads the buffer after the call returns unless CALIPER_VIEW_FLAG_WAIT_GPU is set, so the producer must have finished writing before the call.

Field Type Description
struct_size size_t sizeof(CaliperViewDesc), as the caller built it.
name const char* The id and window title of the view. The same name updates the existing view in place.
tensor const CaliperTensor* The tensor to draw, either 2-D f32 (H,W) or 3-D u8 (H,W,4), on device CPU or METAL.
byte_offset uint64_t For METAL only, the byte offset into the MTLBuffer of tensor->data, as in DLPack. It must be a multiple of 4.
colormap int32_t The CaliperColormap for a 2-D f32 tensor (0 to 15, starting with 0 viridis, 1 magma, 2 rdbu).
vmin, vmax float The mapping range of a 2-D f32 tensor. Both ends must be finite.
flags uint32_t A bit set of the CALIPER_VIEW_FLAG_* flags.
Name Value Description
CALIPER_EMBED_HAVE_VIEWS 1 Defined as 1 when the header declares the view calls, so that a host can test for them.
CALIPER_VIEW_FLAG_RAW 1 << 0 Bit flag to draw the texture 1:1 at the canvas origin with no window chrome, for tests.
CALIPER_VIEW_FLAG_WAIT_GPU 1 << 1 Bit flag to block until the device update completes, which makes the handoff safe and adds a measured cost.

Windowed views are drawn in creation order and tiled left to right. The views of a live session take the cells of a grid instead (see What you see). A small tensor is magnified by a whole-number factor and sampled nearest, so cells stay cells. With CALIPER_VIEWS_DEBUG=1, or views_debug set on the core of a host, each window carries an info line (WxH dtype device path updates=N last=ms). CALIPER_VIEW_FLAG_RAW draws the texture 1:1 at canvas (0,0) with no window chrome. The byte-exact read_pixels tests compare this surface.

Accepted Layouts

Tensor Drawn as Rule
2-D f32 (H,W) Colormapped heatmap colormap 0 viridis, 1 magma, 2 rdbu, over [vmin, vmax] (both must be finite). idx = clamp((v-vmin)/(vmax-vmin),0,1)*255+0.5. NaN maps to index 0.
3-D u8 (H,W,4) RGBA image, as is C must be 4. RGB and gray are refused.

Both layouts must be row-major contiguous (strides in elements), with each dimension in 1..16384, on device CPU or METAL. The core refuses anything else with a view_tensor('<name>'): ... reason in caliper_core_last_error. The Python layer converts other dtypes and shapes into one of these two layouts on the own device of the tensor before the call. For an MPS tensor this is a GPU copy, never a host copy.

Device Paths

  • CPU. A CPU-staged upload of the bytes at data + byte_offset (path cpu-staged). The core copies the bytes before the call returns, so the caller may free or rewrite them at once.
  • METAL. Zero-copy. tensor->data is an in-process id<MTLBuffer> (DLPack kDLMetal data, the buffer object pointer of the storage). desc->byte_offset is the DLPack byte_offset, a multiple of 4. The view imports the buffer with a strong retain through tensor_bridge.v1_2 import_allocation. It caches the import per view and imports again when the buffer pointer changes. The renderer reads the buffer in place at byte_offset on the GPU. It uses the colormap compute kernel for f32 (path compute-imported) and a blit for u8 (blit-imported), and sets info.imported = 1.

If the device path refuses, the call fails. A refusal happens when the active renderer is not Metal, the buffer lives on another GPU, the buffer is shorter than byte_offset + extent, or the renderer cannot import. The core never quietly downloads a METAL tensor to the host. A refusal is an error, not a slower success.

tensor->stream is passed through. A non-NULL MTLCommandQueue* orders the GPU read after the committed work of that queue (bridge v1_1). NULL is the normal case for a caller that made sure the producer finished first.

Sync and Memory Stability

Without CALIPER_VIEW_FLAG_WAIT_GPU, the GPU reads [byte_offset, byte_offset + extent) of the buffer after the call returns. The contract follows from that:

  • Before the call, the producer must have finished writing those bytes. Device-side ordering through tensor->stream covers only producer work committed before the call. The Python caliper.show call uses torch.mps.synchronize(). The live-streaming layer applies a snapshot only after a polled torch.mps.Event reports it complete.
  • Without WAIT_GPU, do not rewrite the bytes until the next update of the same view or the next caliper_core_frame. A rewrite in that window, such as an in-place opt.step(), gives a torn or stale frame, never a crash. The import retains the MTLBuffer, and the command buffer retains every resource it references until it retires.
  • With WAIT_GPU, the call blocks until the read of the renderer completes. On return the caller may rewrite or free the buffer at once. The Metal renderer waits on the last device-update command buffer, and info.last_update_ms includes the wait.

The texture is the own copy of the pixels in the view, and the core reads the source buffer only during the update. A view keeps its last MTLBuffer retained (the import) until the next update from a different buffer or until removal.

Mapping Changes and View Info

A different vmin, vmax or colormap on an existing f32 view re-pins the mapping of the bridge entry. The core then maps the new tensor into the same texture, and creates does not change. A different shape or dtype recreates the texture (creates += 1). The core builds the new texture before it releases the old one, so a failed recreate leaves the old view intact.

The measured state of one view, which caliper_core_view_info fills.

Field Type Description
struct_size size_t sizeof(CaliperViewInfo), as the caller built it.
path const char* The renderer path of the last update: compute-imported, blit-imported, compute, blit or cpu-staged. It stays valid until the next core call.
width, height int32_t The size of the texture in texels.
device int32_t The CaliperDeviceKind of the last tensor.
updates uint64_t The number of successful updates.
last_update_ms double The CPU wall time of the last caliper_core_view_tensor call in milliseconds, including the GPU wait when CALIPER_VIEW_FLAG_WAIT_GPU was set.
imported int32_t 1 when the last update read an imported MTLBuffer in place, which is the zero-copy case, otherwise 0.
creates uint64_t The number of texture creations: 1 after the first show and 1 more for each shape or dtype change. A mapping change does not count.

Threading

Every view function except caliper_core_colormap_lut is frame-thread only. Call it from the thread that calls caliper_core_frame(), between frames, as with caliper.tensor_bridge.*. Views need an attached canvas, because the device of the renderer exists only after attach_canvas. A view_tensor call before attach is a refusal. caliper_core_shutdown destroys the views, and releases textures and imports, before it tears down the renderer.

Typed Live Views

The header caliper/live_views.h builds on this section. caliper_core_live_apply takes a CaliperLiveSnapshot of one of five kinds (heatmap, image, points, series, histogram) and keeps a typed view of that name. A sixth kind, scene (6), belongs to the wire protocol 3.2 draft and is not applied as a snapshot: caliper_core_live_apply refuses it. A stream attached with caliper_core_live_attach_url opens and feeds a scene view itself, which caliper_core_live_view_info (path copied-from-host) and caliper_core_live_view_readback then answer for. Heatmap and image live views are drawn through the tensor view of the same name, so caliper_core_view_info, _readback, _count and _remove keep working for them. The header documents the payload contract for each kind in CaliperLiveSnapshot, the claim rule that caliper_core_live_view_read_done reports for each kind, and the pause flag of each core. The header caliper/live.h is the shared-memory session protocol, with the client and viewer C API that feed it from another process. Both work on macOS with Metal only. The design is in Live streaming.

All typed live-view calls run on the frame thread, between frames and after attach_canvas. caliper_core_shutdown destroys the views.

Call Signature Description
caliper_core_live_apply int (CaliperCore* core, const CaliperLiveSnapshot* snap) Create the typed view named snap->name, or update it when it exists. Return 1 on success, or 0 with the last error set. The producer applies a snapshot only after the GPU work that wrote it completed, and never rewrites a slot that the core may still read. An apply with the same name and another kind rebuilds the view and restarts its counters, and a failed rebuild keeps the old view. A switch between heatmap and image stays in place. A points, series or histogram apply refuses a name that a plain tensor view owns.
caliper_core_live_view_remove int (CaliperCore* core, const char* name) Remove the typed view named name. Return 1 if the view existed and was removed, otherwise 0.
caliper_core_live_view_count int (CaliperCore* core) Return the number of typed views.
caliper_core_live_view_info int (CaliperCore* core, const char* name, CaliperLiveViewInfo* out) Fill out with the measured state of the view named name. Return 1 on success, otherwise 0.
caliper_core_live_view_read_done int (CaliperCore* core, const char* name) Probe without blocking whether a transport may rewrite the slots of the view named name. Return 1 when it may, and never wait. The rule depends on the kind. For a heatmap or image view, the result is 1 once the device update of every apply so far has completed, so the last payload is free too. For a points view, the current payload stays claimed while it is current, because every redraw reads it. The result is then 1 once the last frame that drew every superseded payload has retired, which is also the case right after the first apply. A transport keeps the current slot and frees the previous ones when the result is 1. A series or histogram view copies at apply and claims nothing, and an unknown view reports 1.
caliper_core_live_view_readback int (CaliperCore* core, const char* name, void* buf, size_t buf_bytes) Copy the texture of a texture-backed view (heatmap, image or points) named name to buf as tightly packed RGBA8 of width*height*4 bytes. buf_bytes is the size of buf. Return 1 on success, otherwise 0.
caliper_core_live_view_values int (CaliperCore* core, const char* name, float* out, size_t cap, size_t* count) Copy the values that a series or histogram view currently holds into out, oldest first for a series and as bin counts for a histogram. The call copies at most cap values and sets *count to the number available, so out may be NULL with cap 0 to count. Return 1 on success, and 0 for other kinds.
caliper_core_live_set_paused void (CaliperCore* core, int paused) Freeze or resume the display of every typed view of this core. One flag serves the whole core. While it is set, each apply still runs every gate and then the core accepts and drops the snapshot, which adds to dropped. A first apply while paused creates an empty view. Claims keep progressing, so training is never slowed. Each typed window shows a Pause and Resume button for this flag.
caliper_core_live_paused int (CaliperCore* core) Return 1 when the display is paused, otherwise 0.

CaliperLiveSnapshot

One snapshot of a typed live view, which caliper_core_live_apply takes.

The kind selects the payload, and the values of CaliperLiveKind are shared with caliper/live.h. A HEATMAP payload is data of shape (H,W) in f32, colormapped over [vmin, vmax]. The AUTO flags take the ends from stats[0] and stats[1], which hold the minimum and maximum of the producer. A non-finite automatic range keeps the last finite one, and a flat range widens by 0.5 on each side. The core draws a heatmap through the tensor view of the same name, so caliper_core_view_info, caliper_core_view_readback, caliper_core_view_count and caliper_core_view_remove keep working for it. Its renderer path is compute-imported for a METAL payload and cpu-staged for a CPU payload.

An IMAGE payload is data of shape (H,W,4) in u8 RGBA, drawn like the image view of embed.h with the path blit-imported. A POINTS payload is data of shape (N,3) in f32 positions. A 2-D caller pads z with 0 and sets points_dims to 2. The optional aux of shape (N,) in f32 carries one value per point and lives on the same device as data. With label_count above 0, aux holds categorical labels from 0 to label_count - 1, drawn with a fixed palette of 16 colors where label L takes color L mod 16. This is exact for integer labels up to 255, and larger labels clamp to 255. With label_count 0, aux is colormapped over [vmin, vmax]. Without aux, the points have one flat color. stats[2..7] may carry the bounding box (xmin, xmax, ymin, ymax, zmin, zmax) for the automatic fit when stats_count is at least 8. Without it, the fit scans the CPU-visible payload.

For a METAL points payload, the GPU redraws the view straight from the payload buffer, which is zero-copy with the path points-imported. It redraws whenever the payload, the camera or the window size changes, so the current payload stays claimed while it is current. A CPU payload is staged into a buffer that the view owns at apply, with the path points-cpu-staged, and the caller may free it on return. Points views need the Metal renderer.

A SERIES payload is data of shape (M,) in f32, a ring of capacity M. The values with index i from total - count up to but excluding total live at index i mod M, where count = min(total, M) and total is series_total. The viewer copies the window that it draws. A value that the producer overwrites while the viewer copies the oldest sample is a one-sample glitch at the old end, by design, because the processes share no lock. A HISTOGRAM payload is data of shape (B,) in f32 bin counts over [stats[0], stats[1]]. Without finite stats, the bins are numbered from 0. The core copies the payload at apply, so it is reclaimable at once.

The device of data is CPU or METAL. A METAL payload is an in-process id<MTLBuffer> that the core reads at data_offset, which is the DLPack byte offset plus the slot offset. A CPU payload is the bytes at data->data + data_offset. Every payload that a producer hands over is shared-storage memory that the CPU can read too. The view layer reads series and histogram values and hover values from that CPU side. It refuses a METAL payload whose contents the CPU cannot see, such as a private torch buffer, for series and histogram views. For a heatmap, such a payload still draws but loses its hover values. A heatmap hover reads the slot after its claim ended, so it may show a value of a newer snapshot of the same view. This is a display aid only. The core copies a CPU payload at apply for hover, because the caller may free its bytes on return. An f32 payload of any kind and every METAL payload need a data_offset that is a multiple of 4.

Field Type Description
struct_size size_t sizeof(CaliperLiveSnapshot), as the caller built it.
name const char* The id of the view. The same name updates the existing view in place.
kind int32_t The CaliperLiveKind of the payload.
data const CaliperTensor* The payload tensor. Its shape and type depend on the kind.
data_offset uint64_t The byte offset into data->data.
aux const CaliperTensor* For POINTS only, a tensor of shape (N,) in f32 with one value or label per point, or NULL.
aux_offset uint64_t For POINTS only, the byte offset into aux->data.
stats const float* CPU-readable producer statistics, valid for the call, or NULL.
stats_count int32_t The number of floats in stats.
colormap int32_t The CaliperColormap of a heatmap or of a points view with continuous values.
vmin, vmax float The fixed ends of the mapping range. The AUTO flags override them.
flags uint32_t A bit set of the CALIPER_LIVE_APPLY_* flags.
series_total uint64_t For SERIES only, the number of values appended so far.
points_dims int32_t For POINTS only, 2 for a view with pan and zoom or 3 for an orbit camera.
label_count int32_t For POINTS only, the number of categorical classes in aux, or 0 for continuous values.
seq uint64_t The publish counter of the producer for this view.
stamp_ns uint64_t The time of the snapshot in the clock of the viewer, which is CLOCK_UPTIME_RAW on Apple. A producer on the same machine stamps with that clock, and a network source maps the stamps of the producer into it. The value 0 means unknown.
step int64_t The step stamp of the snapshot, valid only with CALIPER_LIVE_APPLY_HAS_STEP in flags. caliper_core_live_view_info reports it as step.

CaliperLiveViewInfo

The measured state of one typed live view, which caliper_core_live_view_info fills.

Field Type Description
struct_size size_t sizeof(CaliperLiveViewInfo), as the caller built it.
kind int32_t The CaliperLiveKind of the view.
path const char* The renderer path of the last apply. A heatmap or image view reports the path of the tensor view, a points view reports points-imported or points-cpu-staged, and a series or histogram view reports cpu-read. The string stays valid until the next core call.
width, height int32_t The texture size of a texture-backed kind, or 0 for the others. For a points view it is the render target, which is 0 until the first frame draws it.
updates uint64_t The number of successful applies, not counting dropped ones.
creates uint64_t The number of texture creations. For a heatmap or image view it counts the texture creations of the tensor view, which a shape or dtype change causes. For a points view it counts the render target creations, at the first frame and at each window resize. For a series or histogram view it is 1.
dropped uint64_t The number of applies that the core ignored while paused.
seq uint64_t The seq of the last applied snapshot.
stamp_ns uint64_t The stamp_ns of the last applied snapshot.
last_apply_ms double The CPU wall time of the last apply in milliseconds.
latency_ms double The apply time minus stamp_ns for the last apply in milliseconds, or 0 when the stamp is unknown.
imported int32_t 1 when the GPU reads the last payload MTLBuffer in place, as for a METAL heatmap, image or points view, or 0 for a CPU copy such as a series or histogram.
read_done int32_t 1 when the GPU read of the previously applied payload has retired, otherwise 0.
count int64_t For SERIES, the values held. For HISTOGRAM, the bins. For POINTS, N. Otherwise 0.
step int64_t The step stamp of the last applied snapshot, or INT64_MIN when it had none.
Name Value Description
CALIPER_EMBED_HAVE_LIVE_VIEWS 1 Defined as 1 when the header declares the typed live view calls, so that a host can test for them.
CALIPER_LIVE_APPLY_RAW 1u << 0 Bit flag for heatmap and image views to draw the texture 1:1 at the canvas origin with no window chrome, for tests.
CALIPER_LIVE_APPLY_AUTO_VMIN 1u << 1 Bit flag to take vmin from stats[0].
CALIPER_LIVE_APPLY_AUTO_VMAX 1u << 2 Bit flag to take vmax from stats[1].
CALIPER_LIVE_APPLY_WAIT_GPU 1u << 3 Bit flag to block until the GPU read completed, for tests only.
CALIPER_LIVE_APPLY_STAMP_RELATIVE 1u << 4 Bit flag that marks stamp_ns as mapped from the clock of the producer, as for a network source. The latency is then the delay above the fastest recent message and excludes a constant transit time, and the view labels it "rel lat".
CALIPER_LIVE_APPLY_HAS_STEP 1u << 5 Bit flag that marks step of the snapshot as valid. Without it the snapshot has no step.

Live Session Attachment

An embed host attaches to the live session of a training script with the C calls of caliper/live.h. The Caliper app uses the same calls for "Attach to process", and caliper-viewer uses them too. The app owns its window and renderer, so it attaches through a hosted core that borrows them, and its session list follows the same rules as the viewer's list.

Listing sessions works from any thread. The caliper_core_live_* calls need an embed core with an attached canvas, and they run on its frame thread:

#include <caliper/live.h>

/* List sessions (any thread). struct_size must be set on every entry. */
CaliperLiveSessionInfo s[16];
for (int i = 0; i < 16; ++i) s[i].struct_size = sizeof s[i];
int n = caliper_live_list_sessions(s, 16);      /* newest first; -1 + caliper_live_last_error() */

/* Attach: by token, by pid, by a stream link, or show the built-in session list. */
caliper_core_live_attach(core, s[0].session);
caliper_core_live_attach_pid(core, pid, NULL);  /* NULL = the default data root */
caliper_core_live_attach_url(core, "ws://127.0.0.1:8765/v3/stream?token=...");
caliper_core_live_picker(core, 1, NULL);        /* list with Attach buttons; Detach returns to it */

/* Every frame, before caliper_core_frame. */
caliper_core_live_poll(core);                   /* claim newest snapshots, write the heartbeat */
caliper_core_frame(core);

caliper_core_live_detach(core);                 /* release claims, clear the heartbeat */

A host whose window can be hidden must keep its frame timer running. macOS slows the frames of a hidden window, and a slow viewer writes its heartbeat late. A stale heartbeat stops the script's snapshots while the user is still attached. For this reason, caliper-viewer holds an NSProcessInfo activity with NSActivityUserInitiatedAllowingIdleSystemSleep | NSActivityLatencyCritical, and the Caliper app holds the same activity while a session is attached.

Live Session Calls

The listing calls work from any thread. The viewer calls run on the frame thread of a core with an attached canvas.

Call Signature Description
caliper_live_data_root const char* (void) Return the default data root, which is $CALIPER_DATA_DIR, else caliper::app_data_dir() with the data_dir override of an embed core. Sessions live in <root>/live. The string is thread-local and valid until the next call on this thread.
caliper_live_list_sessions int (CaliperLiveSessionInfo* out, int cap) List the live sessions under <data_root>/live in the default root, newest first. The call reclaims stale files, which are files of a dead or reused process id. It unlinks their shared memory names and removes the file, and it does not list them. Thus a trainer that a signal killed leaks nothing past the next listing. The call fills min(n, cap) entries and returns the number n of sessions, or -1 with a reason in caliper_live_last_error. The argument out may be NULL when cap is 0. Any thread may call it.
caliper_live_list_sessions_in int (const char* data_root, CaliperLiveSessionInfo* out, int cap) List the live sessions as caliper_live_list_sessions does, under <data_root>/live, with NULL for the default root.
Call Signature Description
caliper_core_live_attach int (CaliperCore* core, const char* session) Attach to the session with the token session. The call accepts a session that is still starting, when the control segment is absent or not yet initialized and a session file names the token, or when magic is 0. It returns 1, and the poll keeps trying with status.pending set to 1. It refuses an unknown token, a protocol mismatch and a session that another live viewer holds, because a session has one viewer. Return 1 on success and 0 on refusal.
caliper_core_live_attach_pid int (CaliperCore* core, int32_t pid, const char* data_root) Attach to the session of the process pid, found by its session file under data_root, with NULL for the default root. Added in protocol v2.
caliper_core_live_attach_url int (CaliperCore* core, const char* url) Attach to a wire protocol v3 stream on this machine. The stream comes from a producer, which is caliper.serve(), or from a hub, which is caliper serve. The url is the stream link ws://127.0.0.1:<port>/v3/stream?token=<token> or the page link http://127.0.0.1:<port>/?token=<token>, and localhost works for 127.0.0.1. An optional session=<id> parameter names the session of a hub. The call waits up to 2 seconds for the server. It returns 0 with a reason in the last error in four cases. The link is not a loopback stream link, nothing listens, the server refuses with HTTP 403 for the token, the Host header or the Origin header, or the server breaks the protocol. It returns 1 once attached, or while the server holds no session yet, with status.pending set to 1. The call subscribes every view of the session with its default data view. The session of the status is the session id and never the token. The field client_alive becomes 0 when the connection or the session ends, and the views keep their last pixels. The stream reconnects after a drop. The views, the claims, the status, the detach call and the caliper_core_live_view_* probes behave as for an attach to shared memory. The protocol is in caliper/live_net.h.
caliper_core_live_detach void (CaliperCore* core) Detach from the session, drop the live views, release the claims and clear the heartbeat, and thus caliper_live_client_attached turns false at once. Training is not affected.
caliper_core_live_poll int (CaliperCore* core) Map and unmap the segments when the table changes, apply the newest completed snapshot of every view and write the heartbeat. Return the number of views updated by this call, or -1 when the core is not attached, picker mode included. A Detach that the user clicked in the status window happens in this call, and then it returns -1.
caliper_core_live_picker int (CaliperCore* core, int enable, const char* data_root) Enable or disable the session picker, which is the landing of "Attach to process". While it is enabled and the core is not attached, the poll refreshes the session list of data_root, with NULL for the default root, once a second, and the frame draws it with an Attach button for each session. Detach in the status window returns to the picker. Return 1 on success. Added in protocol v2.
caliper_core_live_status int (CaliperCore* core, CaliperLiveStatus* out, int reset_window) Fill out with the status of the session and return 1. A reset_window other than 0 starts a new latency and fps window after the call fills out.
caliper_core_live_view_status int (CaliperCore* core, int index, CaliperLiveViewStatus* out) Fill out with the status of the live view at index and return 1, or return 0 when there is no such view.
caliper_core_live_window_latencies size_t (CaliperCore* core, uint64_t* t_ns, double* lat_ms, size_t cap) Copy the raw samples of the current latency window, so call it before a reset. Each sample is a pair of the viewer CLOCK_UPTIME_RAW time in nanoseconds when the update was encoded and the step-to-screen latency in milliseconds. Copy up to cap pairs and return the number copied. Either array may be NULL to count only.

The embedding library also exports the client and segment calls that a producer uses.

Call Signature Description
caliper_live_last_error const char* (void) Return the reason for the most recent refusal on this thread, as a string that is valid until the next live call on this thread.
caliper_live_now_ns uint64_t (void) Return the CLOCK_UPTIME_RAW time in nanoseconds.
caliper_live_client_open CaliperLiveClient* (const CaliperLiveClientDesc* desc) Create the session, with the control segment first and then, unless CALIPER_LIVE_CLIENT_NO_SESSION_FILE is set, the session file. Return the client, or NULL with a reason in caliper_live_last_error. Call the client functions from one thread at a time per client.
caliper_live_client_session const char* (const CaliperLiveClient* c) Return the session token of the client.
caliper_live_client_session_file const char* (const CaliperLiveClient* c) Return the path of the session file, or an empty string when the client has none. Added in protocol v2.
caliper_live_client_attached int (const CaliperLiveClient* c) Return 1 while a viewer heartbeat is younger than CALIPER_LIVE_ATTACH_WINDOW_NS, and 0 otherwise or for NULL. The call is one atomic load and one clock read, and any thread may call it. The Python show() takes no snapshot while it returns 0, and thus an unwatched session costs almost nothing. Added in protocol v2.
caliper_live_client_viewer int (const CaliperLiveClient* c, int32_t* viewer_pid, uint64_t* age_ns) Return 1 and store the viewer process id in viewer_pid, with 0 for none, and the time since its last poll in age_ns, with UINT64_MAX for none.
caliper_live_client_add_view CaliperLiveSegment* (CaliperLiveClient* c, const CaliperLiveViewDesc* desc) Create a view and its segment, and rewrite the session file. The client keeps one reference to the segment. The returned pointer is borrowed, so retain it to keep it beyond caliper_live_client_remove_view or caliper_live_client_close.
caliper_live_client_remove_view int (CaliperLiveClient* c, CaliperLiveSegment* s) Drop the view from the table and unlink its shared memory name. The mapping lives on while references remain, for example the DLPack capsules that retain the segment.
caliper_live_client_close void (CaliperLiveClient* c) Mark the session closed, unlink every name, remove the session file and drop the references of the client. The call never waits for a viewer and is safe on NULL. The mappings live on while references remain.
caliper_live_segment_retain void (CaliperLiveSegment* s) Add one reference to the segment.
caliper_live_segment_release void (CaliperLiveSegment* s) Drop one reference to the segment. The last reference unmaps it.
caliper_live_segment_info int (CaliperLiveSegment* s, CaliperLiveSegmentInfo* out) Fill out with the layout and the live counters of the segment. Return 1 on success.
caliper_live_segment_acquire int (CaliperLiveSegment* s, int* busy) Choose a slot to write, for tests and C producers. The Python ring chooses its own slot. A free slot is not published_slot, not a viewer claim and not a slot of this client that still holds an unpublished snapshot. Return the slot index. Return -1 with *busy set to 1 when every candidate is in flight, and then the caller drops this snapshot, which counts in dropped_client. Return -1 with *busy set to 0 when the segment was removed. A series always gets slot 0.
caliper_live_segment_publish int (CaliperLiveSegment* s, int slot, const CaliperLivePublish* meta) Publish an acquired slot with the metadata meta. The GPU writes to the slot must be complete. Return 1 on success.
caliper_live_segment_publish_slot int (CaliperLiveSegment* s, int slot, const CaliperLivePublish* meta) Publish a slot that the caller chose itself, by the rule of the Python ring that the slot is not published_slot, not a claim and not pending. The other rules are those of caliper_live_segment_publish. Added in protocol v2.
caliper_live_segment_claims int (CaliperLiveSegment* s, uint32_t* reading, uint32_t* prev) Return 1 and store the two claims of the viewer in reading and prev, each CALIPER_LIVE_SLOT_NONE when free. The loads use seq_cst order. Added in protocol v2.
caliper_live_segment_count_drop void (CaliperLiveSegment* s) Count one snapshot that the caller dropped because no slot was free. Added in protocol v2.
caliper_live_segment_abandon void (CaliperLiveSegment* s, int slot) Give back an acquired slot without a publish.

Live Session Types

CaliperLiveClientDesc

The description of a client, which caliper_live_client_open takes.

Field Type Description
struct_size size_t sizeof(CaliperLiveClientDesc).
session const char* The session token, 1 to 20 characters of A-Z, a-z, 0-9, ., _ and -. With NULL, the client uses clp-<pid>-<6 hex>.
mtl_device void* The id<MTLDevice> for the segment buffers, which is the device of the producer, for example the device of a torch buffer. With NULL, the client uses MTLCreateSystemDefaultDevice().
script const char* The name of the script that viewers show. With NULL, the client uses the process name. Added in protocol v2.
data_dir const char* The root folder of the session file. With NULL, the client uses the default data root, as caliper_live_data_root returns it. Added in protocol v2.
flags uint32_t A combination of the CALIPER_LIVE_CLIENT_* flags. Added in protocol v2.

CaliperLiveViewDesc

The description of a view, which caliper_live_client_add_view takes.

The kinds have these payloads. A heatmap is (H,W) of float, an image is (H,W,4) of uint8, points are (N,3) of float with an optional aux array of N values, a series is (M,) of float in 1 slot, and a histogram is (B,) of float.

Field Type Description
struct_size size_t sizeof(CaliperLiveViewDesc).
name const char* The name of the view, 1 to 63 bytes. It is unique in the session.
kind uint32_t The kind of the view, a CaliperLiveKind value.
dtype int32_t The CaliperDType of the payload. It must match the kind.
ndim int32_t The number of dimensions of the payload.
shape int64_t[4] The extent of each dimension of the payload.
slots uint32_t The number of slots. With 0, the view uses the number of its kind, which is 3, or 1 for a series. Added in protocol v2.
aux_count int64_t For points, the number N of aux values that every slot gets as an (N,) array of float. Added in protocol v2.

CaliperLiveSegmentInfo

The live description of a view segment, which caliper_live_segment_info fills.

Field Type Description
struct_size size_t sizeof(CaliperLiveSegmentInfo).
mtl_buffer void* The id<MTLBuffer> over the whole mapping. The segment owns it, and it is NULL on a machine without a device.
host_ptr void* The CPU address of the mapping.
segment_bytes uint64_t The length in bytes of the whole mapping.
payload_bytes uint64_t The size in bytes of the payload of one snapshot.
stats_bytes uint64_t The size in bytes of the stats region of one slot.
slot_offset uint64_t[CALIPER_LIVE_SLOTS] The byte offset of the payload of each slot.
stats_offset uint64_t[CALIPER_LIVE_SLOTS] The byte offset of the stats region of each slot.
slot_count uint32_t The number of slots.
table_index int32_t The row of the view in the control table, or -1 after the client removed the view.
segment_name const char* The shared memory name of the segment. It is valid while the segment lives.
seq uint64_t The seq of the shared header, which counts the publishes.
published_slot uint32_t The published_slot of the shared header.
viewer_reading_slot uint32_t The viewer_reading_slot of the shared header.
dropped_client uint64_t The dropped_client counter of the shared header.
viewer_seq uint64_t The viewer_seq of the shared header.
skipped_viewer uint64_t The skipped_viewer counter of the shared header.
kind uint32_t The kind of the view, a CaliperLiveKind value. Added in protocol v2.
viewer_prev_slot uint32_t The viewer_prev_slot of the shared header. Added in protocol v2.
aux_bytes uint64_t The size in bytes of the aux region of one slot, or 0 for none. Added in protocol v2.
aux_offset uint64_t[CALIPER_LIVE_SLOTS] The byte offset of the aux region of each slot. Added in protocol v2.

CaliperLivePublish

The metadata of one published snapshot, which the publish calls copy into the slot metadata.

Field Type Description
struct_size size_t sizeof(CaliperLivePublish).
stamp_ns uint64_t The CLOCK_UPTIME_RAW time of the show() call, in nanoseconds. It is the same clock as the Python time.monotonic_ns.
colormap int32_t The CaliperColormap of a heatmap or of continuous points.
flags uint32_t A combination of the CALIPER_LIVE_SNAP_* bits.
vmin, vmax float The fixed range, vmin for the lower end and vmax for the upper end, for the ends that are not automatic.
series_total uint64_t For a series, the number of values appended so far. Added in protocol v2.
points_dims int32_t For points, the number of dimensions of a point, 2 or 3. Added in protocol v2.
label_count int32_t For points, the number of categorical classes in the aux region, or 0 when the aux region holds values. Added in protocol v2.
stats_count int32_t The number of meaningful float values in the stats region. With 0, the call uses 2. Added in protocol v2.

CaliperLiveSessionInfo

One live session that the listing found.

Field Type Description
struct_size size_t sizeof(CaliperLiveSessionInfo).
pid int32_t The process id of the client.
alive int32_t 1 when the client runs and its session is open.
view_count int32_t The number of views in the control table now.
protocol int32_t The protocol version of the session file.
start_unix_ms uint64_t The wall clock time of the opening of the session, in milliseconds since the Unix epoch.
viewer_pid int32_t The process id of a viewer with a fresh heartbeat, or 0.
compatible int32_t 1 when protocol equals CALIPER_LIVE_PROTOCOL_VERSION.
session char[CALIPER_LIVE_SESSION_MAX+4] The session token, NUL-terminated.
script char[CALIPER_LIVE_SCRIPT_MAX] The name of the script, NUL-terminated.
path char[1024] The path of the session file, NUL-terminated.

CaliperLiveStatus

The counters and latency of the attached session, which caliper_core_live_status fills.

Field Type Description
struct_size size_t sizeof(CaliperLiveStatus).
attached int32_t 1 when the core is attached to a session.
client_pid int32_t The process id of the client.
client_alive int32_t 0 once the client exited or closed the session.
views int32_t The number of live views.
frames uint64_t The number of frames drawn since the attach.
polls uint64_t The number of polls since the attach.
updates uint64_t The number of view updates applied since the attach.
skipped uint64_t The number of publishes that the viewer never drew because a newer one arrived first.
client_dropped uint64_t The sum of the snapshots that the client dropped because no slot was free.
errors uint64_t The number of updates that the viewer refused.
latency_samples uint64_t The number of latency samples in the current window, which starts at the last reset.
latency_ms_median, latency_ms_p95, latency_ms_max double The median, the 95th percentile and the largest step-to-screen latency in milliseconds over the current window. The latency is the viewer CLOCK_UPTIME_RAW time when the update is encoded minus the show() stamp of the client. The frame that draws the update is committed in the same tick.
fps double The frames per second over the current window.
window_frames uint64_t The number of frames in the current window.
window_updates uint64_t The number of view updates in the current window.
session const char* The session token, or an empty string when the core is not attached. The string is valid until the next live call. Added in protocol v2.
script const char* The name of the script of the session. The string is valid until the next live call. Added in protocol v2.
start_unix_ms uint64_t The wall clock time of the opening of the session, in milliseconds since the Unix epoch. Added in protocol v2.
pending int32_t 1 when the core is attached and waits for a session that is still starting. Added in protocol v2.
picker int32_t 1 when the session picker is enabled. Added in protocol v2.
sessions_listed int32_t The number of sessions in the last listing of the picker. Added in protocol v2.
reserved0 int32_t Reserved.

CaliperLiveViewStatus

The state of one live view, which caliper_core_live_view_status fills.

Field Type Description
struct_size size_t sizeof(CaliperLiveViewStatus).
name const char* The name of the view. The string is valid until the next live call.
kind uint32_t The kind of the view, a CaliperLiveKind value.
seq uint64_t The seq of the last publish that the viewer drew.
updates uint64_t The number of updates applied since the attach.
window_updates uint64_t The number of updates in the current window.
skipped uint64_t The number of publishes that the viewer never drew.
client_dropped uint64_t The number of snapshots that the client dropped for this view.
latency_ms_last double The step-to-screen latency of the last update, in milliseconds.
error const char* The reason for the failure of the last update, or an empty string when it succeeded.
series_total uint64_t For a series, the number of values appended so far in the last applied snapshot. Added in protocol v2.
points_dims int32_t For points, the number of dimensions of a point in the last applied snapshot. Added in protocol v2.
label_count int32_t For points, the number of categorical classes in the last applied snapshot. Added in protocol v2.
stats_count int32_t The number of meaningful stats values in the last applied snapshot. Added in protocol v2.
slot int32_t The slot that the last applied snapshot came from. Added in protocol v2.
apply const char* The path that applied the last snapshot, live_views or v1.2 for the heatmap and image path. Added in protocol v2.

The header defines these feature macros and client flags:

Name Value Description
CALIPER_LIVE_CLIENT_NO_SESSION_FILE 1u << 0 Bit flag to use shared memory only and write no session file. Added in protocol v2.
CALIPER_EMBED_HAVE_LIVE 1 Defined as 1 when the header declares the live viewer calls.
CALIPER_EMBED_HAVE_LIVE_SESSIONS 1 Defined as 1 when the header declares the session list, the attach by process id and the picker. Added in protocol v2.
CALIPER_EMBED_HAVE_LIVE_NET 1 Defined as 1 when the header declares caliper_core_live_attach_url.

caliper-embed Package

cmake --install <build> --prefix <prefix> --component embed installs the caliper-embed CMake package on macOS and Windows. It is separate from the SDK (--component sdk) and goes into the prefix of the SDK or a prefix of its own.

Installed path Contents
lib/libcaliper_embed.dylib (macOS), bin/caliper_embed.dll and lib/caliper_embed.lib (Windows) The embedding library.
include/caliper-embed/caliper/ embed.h, live.h and live_views.h, with copies of the SDK C headers they include and of the service tables that caliper_core_get_service returns: tensor.h, arrow_c.h and services/.
lib/cmake/caliper-embed/ caliper-embed-config.cmake, its version file and the exported target.
share/caliper-embed/ LICENSE and NOTICE.

find_package(caliper-embed CONFIG) gives one imported target, caliper::embed, which carries the library and the include root include/caliper-embed. On macOS the library needs macOS 14 (Sonoma) or later. The package sets CALIPER_MACOS_MIN to its minimum, 14.0 by default. It makes that value CMAKE_OSX_DEPLOYMENT_TARGET unless the project, -DCMAKE_OSX_DEPLOYMENT_TARGET or MACOSX_DEPLOYMENT_TARGET chose one. The package version is the interface version (Versions), 1.4.0, with the CMake SameMajorVersion rule: a request for 1.2 accepts 1.4, and a request for 2 refuses it. In the core build, caliper::embed is an alias of the caliper_embed target, so one target_link_libraries line works in the tree and outside it.

Shared Library

libcaliper is a static library over a dozen more, among them the Metal or Vulkan backend, DuckDB, ImGui, ImPlot and GLFW. If the package shipped those archives, every embedder would link all of them, and their symbols would sit beside the embedder copies of the same libraries. The package ships one shared library instead, caliper_embed, built from libcaliper and everything behind it. It exports only the C functions that embed.h, live.h and live_views.h declare. An embedder keeps its own ImGui, GLFW or DuckDB apart from the core copies. The frameworks that the core needs (Metal, QuartzCore, Cocoa, IOKit, CoreVideo) are load commands of the library, not link items of the embedder.

On Windows the export list leaves out the caliper_live_* client and listing calls, which exist on macOS only. The caliper executable, the test binaries and the Python extension still link the static libcaliper.

On macOS the install name is @rpath/libcaliper_embed.dylib. A program built in its own build folder finds the library through the build rpath that CMake adds. An installed program needs an rpath to <prefix>/lib. On Windows the program needs caliper_embed.dll beside it or on PATH, and embed_host copies the DLL beside itself after each build.

Package Linking

cmake --install cmake-build-release --prefix <prefix> --component embed
cp -R examples/embed_host <work>/embed_host
cmake -S <work>/embed_host -B <work>/embed_host-build -DCMAKE_PREFIX_PATH=<prefix>
cmake --build <work>/embed_host-build

The CMakeLists.txt of examples/embed_host calls cmake_minimum_required, project and find_package(caliper-embed 1.4 CONFIG REQUIRED) only when it is the top-level project, as examples/hello does with the SDK. It links the same target in both builds. The frameworks serve the window code of the host:

target_link_libraries(embed_host PRIVATE
    caliper::embed
    "-framework Cocoa" "-framework QuartzCore" "-framework Metal")

embed_host Offscreen Mode

With CALIPER_EMBED_OFFSCREEN=1, embed_host runs without a window. main() takes this path before it creates an NSApplication, a window class or a window, so nothing appears on screen. It creates the core and attaches a CALIPER_CANVAS_OFFSCREEN canvas of 1280x800. It loads the applet named on the command line and pumps frames for CALIPER_EMBED_EXIT_AFTER seconds (1 by default). Then it reads the last frame back with caliper_core_read_pixels, prints what it did, and exits 0 when the applet drew, otherwise 1. Both modes check the version of the library first and read the applets folder from CALIPER_EMBED_APPLETS.

CALIPER_EMBED_OFFSCREEN=1 CALIPER_EMBED_APPLETS=<applets> \
    <work>/embed_host-build/embed_host dev.caliper.hello

The test caliper_embed_install (label embed) runs this whole path in a work folder, with HOME and the user applets folder inside it. When the canvas cannot attach, as on a machine without a GPU, the test reports Skipped, and CALIPER_REQUIRE_GPU=1 makes that a failure. CALIPER_EMBED_PROBE_DIR sets the work folder.

Torch-Free Build

libcaliper (core, Metal renderer, embed C ABI) includes no torch header. The renderers read CaliperTensor.data as a raw id<MTLBuffer> (Metal) or a CUDA device pointer (Vulkan). The options below make that boundary buildable, so one process can host Caliper Embed next to a different torch, such as the torch that a Python script imported beside the Python extension.

In a torch-free build the core carries no libtorch at all. The libtorch row of the ownership table thus describes torch builds only, and the embedding process is free to load its own torch.

Options

Option Default Effect
CALIPER_WITH_TORCH ON OFF skips the PyTorch dependency block (no download, no find_package(Torch)) and every target that links torch: the applets/* tree (forces CALIPER_BUILD_APPLETS OFF), examples/sine_scope, caliper_torch_tests, the applet learning-core tests and the MSVC torch-DLL copy. caliper_embed_tests then compiles with CALIPER_TESTS_NO_TORCH_APPLETS=1, so its sine-scope swap cases compile out, and no binary carries a libtorch rpath.
CALIPER_BUILD_APPLETS OFF Also builds the applets/* folders inside the core build. Each also builds on its own against the installed SDK. Forced OFF when torch is OFF, because most applets link libtorch.
CALIPER_BUILD_PYTHON OFF Adds the nanobind extensions caliper._native and caliper._live. The wheel build sets it ON.
CALIPER_WITH_SLANG OFF Configure the vendored slang (SystemVerilog) library.
CALIPER_BUILD_VIEWER ON Builds caliper_viewer, the live-viewer process (Apple only). The wheel ships it as caliper/bin/caliper-viewer.
CALIPER_WITH_BUILDER ON, but OFF on Windows Builds the builder, which libcaliper does not link and no package installs. It also links the DuckDB json extension into the host DuckDB, so libcaliper, the embedding library and the caliper exe carry that extension. The wheel sets it OFF.

slang is configured EXCLUDE_FROM_ALL, and nothing that libcaliper, the caliper exe or the tests need links it. At configure time slang clones boost_regex and mimalloc over the network, which a pip build should not do. CALIPER_WITH_SLANG thus defaults to OFF, and the configure presets and the Python build keep it OFF, so a fresh configure clones neither. Two FetchContent clones remain: tomlplusplus (caliper_host_lib) and doctest (tests only). With CALIPER_WITH_BUILDER on, the configure also downloads the nlohmann/json archive.

The wheel build sets CALIPER_BUILD_PYTHON ON. It sets CALIPER_WITH_TORCH, CALIPER_BUILD_APPLETS, CALIPER_BUILD_EXAMPLES, BUILD_TESTS, USE_CUDA, CALIPER_WITH_SLANG and CALIPER_WITH_BUILDER OFF. It builds only the _native, _live, _netio and caliper_viewer targets.

The caliper exe links CALIPER_DEPENDENCY_LIBS, which holds the UI chrome widgets, DuckDB and the rest, but never libtorch. Applets and torch tests link "${TORCH_LIBRARIES}" themselves. libcaliper links only CALIPER_CORE_LIBS as PRIVATE: glfw, imgui_backends, which holds the GLFW backend of ImGui, and the Apple frameworks Cocoa, IOKit and CoreVideo.

The split matters because libcaliper is a static library, and its private dependencies still propagate to every embedder as link-only items. DuckDB reaches an embedder through caliper_host_lib, and imgui, implot, implot3d and ImGuiFileDialog reach it through caliper::ui_stack. Inside the core build, an embedder can link libcaliper caliper::sdk and nothing of the exe list, plus whatever its own window code needs. examples/embed_host links caliper::embed instead, the shared library of the package, which carries all of that inside it. The Python extensions link libcaliper and caliper::sdk plus the Apple frameworks, and glfw for the window of caliper._native.

release-notorch Preset

CMakePresets.json has configure, build and test presets named release-notorch: binary dir cmake-build-notorch, CMAKE_BUILD_TYPE=Release, BUILD_TESTS=ON, CALIPER_WITH_TORCH=OFF, CALIPER_WITH_SLANG=OFF, CALIPER_WGSL_FROM_SOURCE=ON and USE_CUDA=OFF. The Python extension builds against this configuration.

cmake --preset release-notorch
cmake --build --preset release-notorch
ctest --preset release-notorch
./cmake-build-notorch/tests/caliper_embed_tests

The default cmake --preset release configures with torch ON, using the vendored libtorch 2.5.1. libcaliper still builds with zero torch symbols there.

Verification

Run these checks in the torch-free tree cmake-build-notorch. Each count must be 0:

$ nm -gU cmake-build-notorch/libcaliper.a | grep -ci "torch\|c10::\|_ZN2at"
$ nm -u  cmake-build-notorch/libcaliper.a | grep -ci "torch\|c10\|_ZN2at"
$ otool -L <bin> | grep -ciE 'libtorch|libc10|libomp'
$ nm <bin> | c++filt | grep -cE '[ (<,](at|c10|torch)::|_ZN3c10|_ZN2at|_ZN5torch'
$ grep -rnE '#\s*include\s*[<"](torch|ATen|c10)' src include

A case-insensitive torch grep over the binaries gives false positives from DuckDB symbol names (OperatorChildren, VectorChildIndex), hence the namespace-anchored patterns. The otool -L output lists only system frameworks, libc++ and libobjc. In the torch build, otool -L on libcaliper_embed.dylib lists the same libraries.

Header Listing

The tables on this page list every declaration of caliper/embed.h and caliper/live_views.h with the doc comment of each. The caliper-embed package installs both headers, with live.h, under include/caliper-embed/caliper/ (package contents).