Skip to content

Adapters

The adapter headers are applet-side helpers. They are header-only, and the host never includes them. They cover the torch adapter, the allocation registry, the exportable pool, the OBJ loader and the orbit camera.

torch.hpp

caliper/adapters/torch.hpp is a header-only bridge from a torch::Tensor to the frozen CaliperTensor. It compiles against the libtorch of the applet, so torch stays out of the ABI. The host links no torch. It hands the CaliperTensor to caliper.tensor_bridge.v1.

The adapter has three entry points:

Entry point Sync behavior Use when
to_tensor(t) none CPU tensors, or you own the ordering yourself
synced_to_tensor(t) full device drain before handoff device tensors on a v1 host (always correct, costs a barrier)
stream_to_tensor(t, caps) drain or stream-ordered handoff, negotiated device tensors. Pass bridge.caps() and get the best rung the host honors

Copy Rejection

The adapter never silently copies. Each entry point returns std::optional<CaliperTensor>. On success, the value aliases the memory of the tensor with zero copies. When the tensor cannot be a v1 CaliperTensor, the entry point returns std::nullopt and copies nothing. The adapter rejects a tensor for these reasons:

  • An unsupported dtype. Only f32, f16, bf16, i64, i32 and u8 map. It rejects f64, bool, complex, quantized and fp8.
  • ndim > 8, because the frozen shape and strides arrays hold 8 entries.
  • A non-contiguous layout, because the bridge assumes row-major order with no gaps.
  • An MPS view with a nonzero storage offset (see below).
  • A device other than CPU, MPS or CUDA.

The caller repairs the tensor in applet code, for example with an explicit .contiguous() before the next call. Thus the cost of a copy is visible where the applet pays it.

MPS Offset and Contiguity

An MPS tensor must also have storage_offset() == 0. The frozen CaliperTensor has no storage-offset channel, and the bridge casts storage().mutable_data() straight to an id<MTLBuffer>. A view with a nonzero offset would start the buffer at the wrong address and silently address the wrong texels. The adapter rejects such a view. The caller then clones it with .clone(), or with .contiguous() of a materialized tensor, so the buffer starts at offset 0.

A per-kernel select() slice of an (8,1,3,3) weight has this problem. The worker takes an owned clone of each (3,3) filter, which also decouples the snapshot from the live weight.

Windows CUDA Tensors

A CUDA tensor maps to CALIPER_DEV_CUDA, with data set to the device pointer. The Vulkan backend imports it through external-memory interop (see Zero-copy). The adapter compiles the CUDA branch under this guard:

#if !defined(__APPLE__) && __has_include(<c10/cuda/CUDAStream.h>) && \
    __has_include(<cuda_runtime_api.h>)

The check of the c10 header alone is not enough, because the mac libtorch and the Windows CPU libtorch ship the c10/cuda headers without the CUDA toolkit headers.

synced_to_tensor Cost

synced_to_tensor is to_tensor preceded by a device drain. Thus the texture that the host uploads this frame reflects every kernel that the applet has enqueued.

torch::mps::synchronize() and torch::cuda::synchronize() are full device barriers. They block the calling CPU thread until the device drains. Pay this cost once at the handoff and not at each frame. CPU tensors need no sync, so the adapter skips the drain for them.

stream_to_tensor Handoff

const uint32_t caps = bridge.caps();          // tensor_bridge.v1_1, additive
auto ct = caliper::adapters::stream_to_tensor(t, caps);

When the host grants CALIPER_BRIDGE_CAP_STREAM_ORDERED (caps bit 0), the adapter skips the drain. It publishes the queue of the producer in CaliperTensor.stream instead. This value is an MTLCommandQueue* on MPS and a cudaStream_t on CUDA. The renderer orders its copy on the GPU after the queued work of the producer, so no CPU thread waits. Without the caps bit, stream_to_tensor(t, 0) is the same as synced_to_tensor, with byte-identical v1 behavior.

On CUDA, a NULL stream can be an honored handoff. The default stream of torch has the handle nullptr (the legacy default stream), and the NULL rung of the renderer uses that same stream. Only a producer on a non-default stream carries a non-NULL handle. Do not write assertions that assume otherwise.

MPS Serialization

The public MPS stream calls of torch are not internally serialized. Command buffers corrupt when the frame thread drains while the training thread encodes. Thus the adapter runs the whole MPS portion of both rungs, the v1 drain and the stream handoff, as one block on the own stream dispatch queue of torch. This has two results for applet authors:

  1. Any thread can call the adapter safely. But any raw MPS or Metal call that you add must also use that dispatch queue.
  2. CUDA has no such rule, because driver calls are thread-safe by contract.

alloc_registry.hpp

AllocRegistry maps a raw device pointer back to the exportable allocation that contains it, so an adapter can hand the bridge an (alloc, offset) pair instead of a bare pointer. It is plain C++ with no CUDA dependency and works on every platform.

  • add(base, size, os_handle) records an allocation by its base address, and remove(base) forgets it.
  • find(p, extent_bytes) returns a Hit with the operating-system handle, the allocation size, the byte offset of p inside it and the base. It returns nothing when p lies outside every recorded allocation or when fewer than extent_bytes remain after p.

Every call takes one mutex, so any thread may use a registry. ExportablePool owns one.

exportable_pool.hpp

ExportablePool gives an applet tensors that the bridge can import, so a texture updates with zero copies of the data. It is applet-side only, because the host links no ML framework. Every failure degrades to "not pool-backed", and the caller falls back to the stream_to_tensor and update_texture path.

The class has the same public surface on every platform, and three implementations behind it:

  • CUDA (not macOS, with the c10 and CUDA runtime headers present). The pool is a CUDAPluggableAllocator in a c10::cuda::MemPool. It creates each block with a shareable handle type and registers the block in the AllocRegistry. It needs no CUDA toolkit link, and torch owns the CUDA context.
  • MPS (macOS). Unified memory means that the storage of every MPS tensor already is an id<MTLBuffer>, so use() does nothing and to_bridge imports the storage buffer of the tensor. A tensor passed to to_bridge must stay alive until the pool is destroyed or the import is released. Otherwise the MPS caching allocator could hand the same buffer to an unrelated tensor while the host still renders from it. The storage_offset of a tensor travels in the returned offset.
  • Neither. Applet code still compiles, but ok() is false, use() does nothing and to_bridge declines.

The members an applet uses:

Member Meaning
ExportablePool(device_index) Create the pool. ok() reports whether it is backed.
use() Returns a Scope. Tensors allocated while the Scope is alive land in the pool. The Scope cannot be copied or moved, so the begin and end calls balance exactly once.
to_bridge(bridge, tensor) Find the tensor's block, import it into the bridge once (cached by base address, and a refused import is cached too), and return a BridgeRef of {alloc, offset}. Returns nothing when the tensor is not in the pool or the host declined.
registry() The pool's AllocRegistry.

The returned BridgeRef goes to the *_from_alloc calls of caliper.tensor_bridge.v1_2. Release and import calls belong to the frame thread, and the destructor of the pool releases the imports it made. Torch may free a block from any thread. Thus the pool queues the release of the import of that block and drains the queue on the frame thread, in to_bridge and in the destructor.

GPTScope allocates its drawn attention heatmap buffer this way (see Applets). The platform differences are in Torch on each platform.

obj.hpp

caliper::obj is a small Wavefront OBJ loader, with no dependency beyond the standard library.

  • load(std::istream&, Mesh&, std::string* error) and load_file(path, Mesh&, std::string* error) return true on success. On failure they return false, leave the output empty and write a message of the form OBJ line N: reason. They reject malformed positions, texture coordinates, normals and face indices, out-of-range or relative indices, faces with fewer than three vertices and a file with no faces.
  • Mesh holds positions (vertex count by 3), normals (by 3), uvs (by 2) and triangulated indices, plus has_normals and has_uvs. The loader deduplicates vertices on their position, texture and normal index triple, so a mesh with hard edges or seams has more vertices than the file has positions. A missing normal or UV reads as zero, and the flags say whether the whole mesh had them. The loader fan-triangulates polygons.

The loader does only OBJ. glTF and other asset formats are not supported.

orbit_camera.hpp

Header-only orbit-camera math in caliper::adapters, so that drawing and picking use one eye computation and a pick ray lands where the draw put the pixel.

  • V3 with +, -, scalar *, dot, cross and normalized. A zero-length vector normalizes to world up, so no call produces NaN.
  • look_at(eye, at, up, m) writes a right-handed, column-major view matrix.
  • perspective(fovy, aspect, near, far, m) writes a Vulkan-style projection with depth in [0, 1]. It does not flip Y, because the negative-viewport convention of the backend supplies the up direction.
  • orbit_eye(azimuth, elevation, distance, target) returns the eye position. The azimuth sweeps the horizontal ring, the elevation lifts toward world up and the distance is the radius.
  • cursor_ray(eye, target, fov_deg, aspect, ndc_x, ndc_y) returns the normalized world-space ray through a point in normalized device coordinates, with +y up.
  • kOrbitPi is the constant the camera code uses.

torch.hpp Source

#pragma once
/* caliper/adapters/torch.hpp — header-only bridge from a torch::Tensor to the
 * frozen CaliperTensor (docs/applets/tensor-and-arrow-headers.md#tensor-header). It compiles against the APPLET's
 * libtorch and is NEVER included by the host: torch stays out of the ABI.
 * The host links no torch; it consumes only the CaliperTensor this produces.
 *
 * Exemplar teaching points baked into the contract:
 *   - The adapter NEVER silently copies. A non-contiguous tensor is REJECTED
 *     (std::nullopt); the caller makes the copy visible in applet code with an
 *     explicit `.contiguous()` before calling again — the cost is in the applet,
 *     not hidden in the bridge.
 *   - MPS tensors additionally REQUIRE storage_offset() == 0. The frozen
 *     CaliperTensor has no storage-offset channel, and the bridge casts
 *     storage().mutable_data() straight to an id<MTLBuffer>; a view with a
 *     nonzero offset would silently address the wrong texels. Reject it — the
 *     caller clones the view (`.clone()` / `.contiguous()` of a materialized
 *     tensor) so the buffer starts at offset 0.
 *   - v1 device story: `stream == NULL`. Correctness on device textures comes
 *     from torch::mps::synchronize() (see synced_to_tensor), i.e. sync-then-
 *     update. That sync is a FULL device barrier — it blocks the calling CPU
 *     thread until every MPS stream drains — so pay it once at the handoff, not
 *     needlessly per frame. stream_to_tensor (M2) supersedes this when the
 *     host's bridge-v1.1 caps() grants stream-ordered handoff.
 */
#include <optional>

#include <caliper/tensor.h>
#include <caliper/services/tensor_bridge_v1_1.h>
#include <torch/torch.h>
#if defined(__APPLE__)
#include <dispatch/dispatch.h>  // dispatch_sync_f: serialize on torch's MPS stream queue
#include <objc/message.h>       // producer-queue lookup without an ObjC++ TU
#endif
// The c10/cuda headers ship in every libtorch (mac, and the Windows CPU zip)
// but include the CUDA toolkit's own headers, so presence-of-header alone is
// not usability: cuda_runtime_api.h must be there too. Apple torch builds
// never have CUDA anyway.
#if !defined(__APPLE__) && __has_include(<c10/cuda/CUDAStream.h>) && \
    __has_include(<cuda_runtime_api.h>)
#include <c10/cuda/CUDAStream.h>
#endif

namespace caliper::adapters {

namespace detail {

// v1 dtype map. Anything not named here (f64, bool, complex, quantized, fp8…)
// is rejected — the bridge only understands these six.
inline std::optional<CaliperDType> map_dtype(at::ScalarType st) {
    switch (st) {
        case at::kFloat:    return CALIPER_DT_F32;
        case at::kHalf:     return CALIPER_DT_F16;
        case at::kBFloat16: return CALIPER_DT_BF16;
        case at::kLong:     return CALIPER_DT_I64;
        case at::kInt:      return CALIPER_DT_I32;
        case at::kByte:     return CALIPER_DT_U8;
        default:            return std::nullopt;
    }
}

#if defined(__APPLE__)
// [cb commandQueue] via the C ObjC runtime, so this header stays compilable
// as plain C++ (applet TUs are .cpp, not .mm). The queue is torch's global
// MPS command queue — process-lifetime, safe to hand across the ABI.
inline void* mtl_command_queue_of(void* command_buffer) {
    using Send = void* (*)(void*, SEL);
    return command_buffer
        ? ((Send)objc_msgSend)(command_buffer, sel_registerName("commandQueue"))
        : nullptr;
}

// The whole MPS handoff — command-buffer peek AND commit — as ONE block on
// torch's MPS stream dispatch queue. NONE of the torch::mps stream calls are
// internally serialized (verified by disassembly of this libtorch:
// commitStream/deviceSynchronize tail-call MPSStream::synchronize, which is
// straight-line objc_msgSends — no dispatch_sync anywhere), while every
// torch-internal kernel encode runs as a block on get_dispatch_queue() (its
// documented purpose is exactly this synchronization). Touching the stream
// from a frame thread while a training thread encodes therefore corrupts the
// MPSCommandBuffer/encoder state — MPS aborts with 'command buffer already
// committed' / AGX encoder-coalescing crashes (the EmbedScope SIGABRT). The
// same disassembly is what makes nesting commit() inside our block safe: it
// cannot deadlock, because it never dispatches. Plain C dispatch API — no
// ObjC blocks — keeps the header .cpp-compilable.
inline void mps_handoff_probe(void* ctx) {
    void** queue = static_cast<void**>(ctx);
    *queue = mtl_command_queue_of(torch::mps::get_command_buffer());
    if (*queue != nullptr)
        torch::mps::commit();   // enqueue-not-drain, atomic with the peek
}
inline void* mps_commit_and_get_queue() {
    void* queue = nullptr;
    if (void* dq = torch::mps::get_dispatch_queue())
        dispatch_sync_f(static_cast<dispatch_queue_t>(dq), &queue,
                        &mps_handoff_probe);
    return queue;
}

// The drain-path twin of the above, for synced_to_tensor and the null-queue
// fallback: torch::mps::synchronize() is just as unserialized as commit()
// (same disassembly), so a frame-thread drain races worker encodes the same
// way — the third face of that race is an AGX encoder-coalescing SIGSEGV.
// Same recipe: run the drain as ONE block on torch's stream dispatch queue,
// atomic with worker encodes; nesting synchronize() inside is deadlock-free
// because it never dispatches.
inline void mps_sync_block(void*) { torch::mps::synchronize(); }
inline void mps_synchronize_serialized() {
    if (void* dq = torch::mps::get_dispatch_queue())
        dispatch_sync_f(static_cast<dispatch_queue_t>(dq), nullptr,
                        &mps_sync_block);
    else
        torch::mps::synchronize();
}
#endif

}  // namespace detail

// Build a CaliperTensor that aliases `t`'s memory (zero-copy). Returns nullopt
// — and copies nothing — when `t` cannot be represented as a v1 CaliperTensor.
// Rejection reasons: unsupported dtype, ndim > 8, non-contiguous, an MPS view
// with a nonzero storage offset, or a device other than CPU/MPS. The caller
// logs / repairs (e.g. `t.contiguous()`); the adapter never hides a copy.
inline std::optional<CaliperTensor> to_tensor(const at::Tensor& t) {
    const auto dt = detail::map_dtype(t.scalar_type());
    if (!dt) return std::nullopt;

    const int64_t nd = t.dim();
    if (nd < 0 || nd > 8) return std::nullopt;   // frozen shape/strides are [8]

    // Contiguity is mandatory on every device: the bridge assumes row-major with
    // no gaps. Reject rather than copy so the cost is visible in applet code.
    if (!t.is_contiguous()) return std::nullopt;

    CaliperTensor out{};
    out.struct_size = sizeof(CaliperTensor);
    out.dtype = *dt;
    out.ndim = static_cast<int32_t>(nd);
    for (int64_t i = 0; i < nd; ++i) {
        out.shape[i]   = t.size(i);      // elements
        out.strides[i] = t.stride(i);    // elements
    }
    out.stream = nullptr;                // v1: no stream channel (sync explicitly)

    if (t.is_cpu()) {
        out.data = t.data_ptr();
        out.device = CALIPER_DEV_CPU;
        out.device_index = 0;
        return out;
    }
    if (t.is_mps()) {
        // No offset channel in CaliperTensor and the bridge casts this pointer
        // straight to id<MTLBuffer>; a nonzero offset would mis-address texels.
        if (t.storage_offset() != 0) return std::nullopt;
        out.data = t.storage().mutable_data();   // the MTLBuffer bridge pointer
        out.device = CALIPER_DEV_METAL;
        out.device_index = static_cast<int32_t>(t.device().index());
        return out;
    }
    if (t.is_cuda()) {
        // Unlike MPS there is no buffer-object cast: data_ptr() IS the device
        // address (storage offset already applied), and the Vulkan backend
        // copies from it in-VRAM (docs/python/zero-copy-tensors.md). Contiguity was enforced above;
        // views with a nonzero storage offset are therefore fine here.
        out.data = t.data_ptr();
        out.device = CALIPER_DEV_CUDA;
        out.device_index = static_cast<int32_t>(t.device().index());
        return out;
    }
    // Any other device is not a v1 target for this adapter.
    return std::nullopt;
}

// Same as to_tensor, but first drains the MPS device so the texture the host
// uploads THIS frame reflects every kernel the applet has enqueued. This is the
// v1 correctness story for device textures (sync-then-update). Cost, honestly:
// torch::mps::synchronize() is a full device barrier that blocks the CPU until
// all MPS streams complete — the price of a stream-free v1 ABI. CPU tensors
// need no sync, so the call is skipped for them.
inline std::optional<CaliperTensor> synced_to_tensor(const at::Tensor& t) {
#if defined(__APPLE__)
    // Serialized on torch's MPS stream dispatch queue — a bare synchronize()
    // races concurrent training-thread encodes (see the detail helper).
    if (t.is_mps()) detail::mps_synchronize_serialized();
#else
    if (t.is_mps()) torch::mps::synchronize();
#endif
    if (t.is_cuda()) torch::cuda::synchronize();   // same contract, CUDA form
    return to_tensor(t);
}

// M2: hand over ORDER instead of a drained
// device. When the host's bridge-v1.1 caps carry
// CALIPER_BRIDGE_CAP_STREAM_ORDERED, populate t.stream with the producer's
// stream/queue and SKIP the full-device drain; the renderer GPU-orders its
// update after the producer's already-enqueued work. Without the bit (v1
// host, GL fallback, headless) this is exactly synced_to_tensor — the adapter
// never skips a drain the host didn't promise to replace. Thread-safety story
// unchanged from v1: the caller still hands over a tensor it owns at a
// quiescent point in its own logic (spec §4, last paragraph).
//
// FRAME-THREAD WARNING: without CALIPER_BRIDGE_CAP_STREAM_ORDERED this degrades
// to synced_to_tensor (a full device barrier). Gate on the cap before calling
// from draw_ui.
inline std::optional<CaliperTensor> stream_to_tensor(const at::Tensor& t,
                                                     uint32_t bridge_caps) {
    if (!(bridge_caps & CALIPER_BRIDGE_CAP_STREAM_ORDERED))
        return synced_to_tensor(t);
#if defined(__APPLE__)
    if (t.is_mps()) {
        auto out = to_tensor(t);
        if (!out) return out;
        // One dispatch-serialized block does the queue peek AND the commit —
        // atomic against concurrent training-thread encodes (see the detail
        // helper's comment for why nothing here may touch the stream outside
        // that block). Enqueue, not drain: pending torch kernels become
        // committed GPU work the renderer's producer-queue signal is ordered
        // after (M2b). The queue outlives the handoff (process-lifetime).
        void* queue = detail::mps_commit_and_get_queue();
        if (queue == nullptr) { detail::mps_synchronize_serialized(); return out; }
        out->stream = queue;
        return out;
    }
#endif
#if !defined(__APPLE__) && __has_include(<c10/cuda/CUDAStream.h>) && \
    __has_include(<cuda_runtime_api.h>)
    if (t.is_cuda()) {
        auto out = to_tensor(t);
        if (!out) return out;
        // Stream order puts the renderer's DtoD copy after the producer's
        // kernels — torch::cuda::synchronize() elided entirely (M2a).
        out->stream = (void*)at::cuda::getCurrentCUDAStream(
                          t.device().index()).stream();
        return out;
    }
#endif
    return synced_to_tensor(t);   // CPU: no sync needed; unknown devices drain
}

}  // namespace caliper::adapters