Skip to content

Routes and Inspection

The caliper package sends each view call to the routes that are open, and it offers calls to open and close routes and to inspect the in-process core.

Routing

A call is offered to every route that is open, in this order:

  1. The live session (attach to app). The first view call of a script opens it when no route is open yet, unless CALIPER_SESSION=0. If the build has no session transport, that first call warns once. Then calls do nothing until window() or offscreen() opens a route.
  2. The in-process core: the window of caliper.window() or the canvas of caliper.offscreen().

Each route that is attached takes its own snapshot of the call. The session is attached while the heartbeat of a viewer is younger than 1 s, and the in-process core is attached while it is open. The device-side preparation is built once and shared. With a viewer attached and a window open, both receive every snapshot. With nothing attached, the call returns False after the check.

If caliper.window() opens before the first view call, no session opens. Call caliper.session() as well to have both.

View calls return True if at least one route took a snapshot. They return False when every route skipped it (rate limit, all slots busy, nothing attached). In the synchronous offscreen mode they return a ShowStats.

Name, colormap and range arguments are checked on every call. Checks on the tensor itself (shape, label count, bins) run when a snapshot is built. Thus a bad shape raises only when something is attached.

Routes and Lifetime

session

session(
    auto_launch: bool = False,
    viewer_path: str | None = None,
    script_name: str | None = None,
)

Open the live session, or return the open one.

Attach to the session from the Caliper app (F4 Attach to process) or from caliper-viewer. The first view call of a script opens it implicitly with auto_launch=False, unless CALIPER_SESSION=0.

Arguments

Name Type Description Default
auto_launch bool

True also spawns caliper-viewer --session <token>, unless a spawned viewer is running or a viewer is attached.

False
viewer_path str | None

Overrides the viewer binary.

None
script_name str | None

The name that viewers show. None takes the basename of sys.argv[0].

None

Returns

Type Description
SessionTransport

The open session.

Raises

Type Description
RuntimeError

When the build has no session transport.

window

window(
    width: int = 1280,
    height: int = 800,
    title: str = "caliper",
    *,
    offscreen: bool = False,
    fps: float = 60.0,
    rate=None,
    activate: bool = True,
    heartbeat: bool = False,
)

Open the in-process window and route every call to it.

An open window of the same kind is returned as is, and any other canvas is replaced. Call this function on the main thread only.

The core of the window keeps its data in $CALIPER_DATA_DIR, else in a private temporary directory that closes with the window. The data are its stores, the data folders of the applets and its imgui.ini.

The window has these limits:

  • macOS delivers input only to the main thread. Input waits during long steps unless run gives the main thread to Caliper. Outside run(), a view call on the main thread pumps events at most 60 times a second.
  • A crash of the script takes the window down, and a hung window hangs the script.
  • A process has one core, so only one window or offscreen canvas exists at a time.

While open, the window holds an NSProcessInfo user-initiated, latency-critical activity. Without it, macOS App Nap throttles the process of an occluded window.

Arguments

Name Type Description Default
width int

Width of the window.

1280
height int

Height of the window.

800
title str

Title of the window.

'caliper'
offscreen bool

True drives an offscreen canvas from the same render thread (CI, render()).

False
fps float

Frame rate of the render thread.

60.0
rate float | None

Default snapshot rate of the route. None takes 60 per second.

None
activate bool

False shows the window without taking focus from the terminal.

True
heartbeat bool

True adds a view named caliper.render that scrolls one texel per rendered frame. A screenshot then shows whether the canvas repaints.

False

Returns

Type Description
Window

The window. Its run, stats, render and close members work as the functions of the same name.

Raises

Type Description
RuntimeError

When called off the main thread.

offscreen

offscreen(width: int = 256, height: int = 256)

Open the synchronous offscreen canvas for tests and notebooks.

It replaces an open window. Call this function on the main thread only.

The canvas has no render thread. Each call waits for the GPU event of its snapshot, applies it on the calling thread and renders a frame (at most 60 per second). Thus view_info, view_readback and render see the call at once. The default rate is every call. In a notebook, caliper.render() returns the composited frame as an (H, W, 4) uint8 array to display.

Arguments

Name Type Description Default
width int

Width of the canvas.

256
height int

Height of the canvas.

256

Returns

Type Description
Window

The canvas.

Raises

Type Description
RuntimeError

When called off the main thread.

Window

The Caliper canvas of this process, which a snapshot ring feeds.

window and offscreen return it. It has three forms. Window() is a window that the render thread repaints. Window(offscreen=True) is the render thread on an offscreen canvas (benchmarks, CI, render()). Window(offscreen=True, sync=True) has no render thread and is the canvas of caliper.offscreen(). Create it on the main thread.

A window also works as a context manager. Leaving the with block closes it.

with caliper.window() as w:
    w.run(train)

Arguments

Name Type Description Default
width int

Width of the canvas.

1280
height int

Height of the canvas.

800
title str

Title of the window.

'caliper'
offscreen bool

True drives an offscreen canvas.

False
sync bool

True selects the synchronous mode without a render thread. It needs offscreen=True.

False
fps float

Frame rate of the render thread.

60.0
rate float | None

Default snapshot rate. None takes 60 per second, or every call when sync is True.

None
activate bool

False shows the window without taking focus.

True
heartbeat bool

True adds the view caliper.render that scrolls one texel per rendered frame.

False
data_dir str | None

The data folder of the core. None takes $CALIPER_DATA_DIR, else a private temporary directory that closes with the window.

None
on_pending Callable | None

Called when a snapshot is pending.

None

Attributes

Name Type Description
core object

The native core of the canvas.

offscreen bool

True for an offscreen canvas.

sync bool

True for the synchronous mode.

transport WindowTransport

The route that applies snapshots to the core.

ring SnapshotRing

The snapshot ring that feeds the core.

Raises

Type Description
RuntimeError

When created off the main thread.

ValueError

When sync is True without offscreen.

closed

closed: bool

True after close(), or after the user closed the window.

run

run(fn: Callable, *args, **kwargs)

Run fn(*args, **kwargs) on a worker thread while the main thread runs the event loop.

The window stays fully interactive whatever fn does. The worker is a daemon thread named caliper.train. Ctrl-C reaches it as KeyboardInterrupt. If the user closes the window, fn keeps running and its view calls become no-ops. The window closes when fn returns.

Arguments

Name Type Description Default
fn Callable

The function to run.

required
*args object

Positional arguments of fn.

()
**kwargs object

Keyword arguments of fn.

{}

Returns

Type Description
object

The result of fn.

Raises

Type Description
RuntimeError

When called off the main thread.

Exception

Any exception of fn.

stats

stats(reset: bool = False) -> dict

Return the render stats and the ring counters of this window.

The result has the render stats and ring, as the "window" entry of stats describes them.

Arguments

Name Type Description Default
reset bool

True clears the sample lists and the ring counters after the read.

False

Returns

Type Description
dict

The render stats plus ring.

render

render()

Render a frame and return its pixels (offscreen canvases).

Returns

Type Description
ndarray

A freshly composited frame, (H, W, 4) uint8.

Raises

Type Description
RuntimeError

When the canvas is not offscreen.

close

close() -> None

Close the canvas and release its core.

A second call does nothing.

run

run(fn, *args, **kwargs)

Run fn(*args, **kwargs), on a worker thread when a window is open.

With a window open, the main thread keeps the window interactive while fn runs. Otherwise run calls fn directly.

The worker is a daemon thread named caliper.train. Ctrl-C reaches the thread as KeyboardInterrupt. If the user closes the window, fn keeps running and its view calls become no-ops. The window closes when fn returns.

Arguments

Name Type Description Default
fn Callable

The function to run.

required
*args object

Positional arguments of fn.

()
**kwargs object

Keyword arguments of fn.

{}

Returns

Type Description
object

The result of fn.

Raises

Type Description
RuntimeError

When a window is open and the call is not on the main thread.

Exception

Any exception of fn, re-raised on the calling thread.

spin

spin(seconds: float | None = None) -> None

Flush pending snapshots, then keep the view alive.

With a window, run its event loop until it closes or seconds pass. With a session, wait until the viewer exits or seconds pass. The wait ends at once when no viewer is attached and none was spawned.

Arguments

Name Type Description Default
seconds float | None

Seconds to wait at most. None waits without a limit.

None

Raises

Type Description
RuntimeError

When a window is open and the call is not on the main thread.

flush

flush(timeout: float = 5.0) -> int

Publish every pending snapshot and poll their GPU events.

The call is not for the training loop.

Arguments

Name Type Description Default
timeout float

Seconds to wait at most.

5.0

Returns

Type Description
int

How many snapshots are still pending after timeout.

close

close() -> None

Close every route: the window, the offscreen canvas and the session.

The next view call opens a new session. The call also runs at interpreter exit.

remove

remove(name: str) -> bool

Remove view name from every route.

Arguments

Name Type Description Default
name str

The view id.

required

Returns

Type Description
bool

True if the in-process core had the view.

Inspection and Test Helpers

These calls read the in-process core. They raise RuntimeError without a window() or offscreen(), except where noted. Arrays are numpy. view_info(name) also returns the copy counters copies, copy_bytes, last_copies and last_copy_bytes (Copy Counters and Frame Statistics). live_view_info(name) returns the same counters.

stats

stats() -> dict

Return the ring counters per route plus the render stats of the window.

The call works without a core. The result has one entry per route. The key "session" holds ring counters and transport (the result of SessionTransport.stats()). The key "window" holds ring plus the render stats below. Any other route has its repr as key.

The ring counters are taken, published, skipped (rate limit), ring_full, superseded (a newer snapshot completed first), appended (series values), allocs and recreated.

The window render stats are running, fps, frames, published, superseded, drawn, deferred_takes, errors, last_error, stats_unreadable, nonfinite_range, queued, max_frame_gap_ms, events_applied and heatmap_live_apply. The sample lists are latency_ms (snapshot to first frame drawn with it), tick_ms and frame_gap_ms. Window.stats(reset=True) clears them.

Returns

Type Description
dict

The stats per route.

frame

frame() -> float

Render one frame now.

For a real window, call this function on the main thread.

Returns

Type Description
float

The wall time of the frame in ms.

Raises

Type Description
RuntimeError

Without a window() or offscreen(), or for a real window off the main thread.

render

render()

Render a frame and return its pixels (offscreen canvases).

Returns

Type Description
ndarray

A freshly composited frame, (H, W, 4) uint8.

Raises

Type Description
RuntimeError

Without a window() or offscreen(), or when the canvas is not offscreen.

read_pixels

read_pixels()

Return a copy of the last composited frame (offscreen canvases).

Returns

Type Description
ndarray

The frame, (H, W, 4) uint8.

Raises

Type Description
RuntimeError

Without a window() or offscreen().

view_info

view_info(name: str) -> dict

Return the state of a heatmap or image view.

The result has path, width, height, device ("metal" or "cpu"), updates, last_update_ms, imported and creates.

Arguments

Name Type Description Default
name str

The view id.

required

Returns

Type Description
dict

The state of the view.

Raises

Type Description
RuntimeError

Without a window() or offscreen().

view_readback

view_readback(name: str)

Read back the texture of a heatmap or image view.

Arguments

Name Type Description Default
name str

The view id.

required

Returns

Type Description
ndarray

The texture, (H, W, 4) uint8.

Raises

Type Description
RuntimeError

Without a window() or offscreen().

view_remove

view_remove(name: str) -> None

Remove view name, as remove does.

Arguments

Name Type Description Default
name str

The view id.

required

view_count

view_count() -> int

Count the heatmap and image views.

Returns

Type Description
int

The number of views. 0 without a core.

live_view_info

live_view_info(name: str) -> dict

Return the state of any typed view.

The result has kind (1 heatmap, 2 image, 3 points, 4 series, 5 histogram), path, width, height, updates, creates, dropped, seq, stamp_ns, last_apply_ms, latency_ms, imported, read_done and count.

Arguments

Name Type Description Default
name str

The view id.

required

Returns

Type Description
dict

The state of the view.

Raises

Type Description
RuntimeError

Without a window() or offscreen().

live_view_values

live_view_values(name: str)

Return the series values or the histogram counts that a view holds.

Series values come oldest first.

Arguments

Name Type Description Default
name str

The view id.

required

Returns

Type Description
ndarray

A float32 array of the values or counts.

Raises

Type Description
RuntimeError

Without a window() or offscreen().

live_view_readback

live_view_readback(name: str)

Read back a heatmap, image or points view.

Arguments

Name Type Description Default
name str

The view id.

required

Returns

Type Description
ndarray

The texture, (H, W, 4) uint8.

Raises

Type Description
RuntimeError

Without a window() or offscreen().

live_pause

live_pause(paused: bool = True) -> None

Freeze the display of every typed view.

Snapshots keep flowing and are dropped.

Arguments

Name Type Description Default
paused bool

True freezes the display, False resumes it.

True

Raises

Type Description
RuntimeError

Without a window() or offscreen().

live_paused

live_paused() -> bool

Tell whether the display of the typed views is frozen.

Returns

Type Description
bool

True while paused. False without a core.

colormap_lut

colormap_lut(name='viridis')

Return a colormap as a look-up table.

The call needs no core.

Arguments

Name Type Description Default
name str | int

A colormap name (such as "viridis", "magma" or "rdbu") or index (0 to 15).

'viridis'

Returns

Type Description
ndarray

A (256,) uint32 array. Each entry is R | G<<8 | B<<16 | A<<24.

Raises

Type Description
ValueError

When name is not a known colormap.

log_lines

log_lines() -> list[str]

Return the log lines of the core.

Returns

Type Description
list[str]

The lines. [] without a core.

caliper.live

from caliper import live imports the module. import caliper does not import it.

list_sessions

list_sessions(data_root: str | None = None) -> list[dict]

List the live sessions under <data_root>/live, newest first.

Stale sessions are reclaimed, not listed. A session is stale when its process is gone. The call unlinks its shared memory and removes its file.

Arguments

Name Type Description Default
data_root str | None

The data root. None takes data_root().

None

Returns

Type Description
list[dict]

One dict per session with pid, alive, view_count, protocol, compatible, start_unix_ms, viewer_pid, session, script and path.

data_root

data_root() -> str

Return the default data root.

Returns

Type Description
str

$CALIPER_DATA_DIR, else the app-data folder of Caliper.

viewer_executable

viewer_executable(path: str | None = None) -> str

Return the path of the viewer executable.

Arguments

Name Type Description Default
path str | None

The path to use. None takes $CALIPER_VIEWER, else the viewer in the package.

None

Returns

Type Description
str

The path of the viewer.

Raises

Type Description
FileNotFoundError

When the viewer does not exist at that path.

SessionTransport

One live session of this process.

caliper.session() returns it. The session is the transport of the snapshot ring. The caller serializes the calls, because the ring runs on the training thread. Only attached() is safe from any thread. The class also works as a context manager, and leaving the with block closes the session.

Attributes

Name Type Description
attached Callable[[], bool]

Returns True while a viewer heartbeat is younger than 1 s. Safe from any thread.

script str

The script name that viewers show.

session

session: str

The token of the session, clp-<pid>-<6 hex>, which caliper-viewer --session takes.

session_file

session_file: str

The path of the session file, or "" when the session has no file or is closed.

closed

closed: bool

True after close().

viewer

viewer: Popen | None

The Popen of the spawned viewer, or None when none was spawned.

launch_viewer

launch_viewer(
    exit_after: float | None = None, args=(), log: str | None = None
) -> subprocess.Popen

Spawn caliper-viewer --session <token> in its own process session.

A Ctrl-C in the terminal of the script does not close the viewer. It attaches at once and outlives the script.

Arguments

Name Type Description Default
exit_after float | None

Seconds after which the viewer exits. None or 0 leaves it open.

None
args Sequence[str]

Extra command-line arguments for the viewer.

()
log str | None

None discards the stderr of the viewer, "-" inherits it, and a path writes it there.

None

Returns

Type Description
Popen

The process of the viewer.

Raises

Type Description
FileNotFoundError

When the viewer executable does not exist.

viewer_alive

viewer_alive() -> bool

Tell whether the viewer runs.

Returns

Type Description
bool

True if the spawned viewer runs. Without a spawned viewer, whether a viewer is attached.

wait_attached

wait_attached(timeout: float = 10.0) -> bool

Wait for a viewer heartbeat.

The wait ends early when the spawned viewer has exited.

Arguments

Name Type Description Default
timeout float

Seconds to wait at most.

10.0

Returns

Type Description
bool

True if a viewer is attached.

wait_viewer

wait_viewer(timeout: float | None = None) -> bool

Wait until the viewer is gone.

The viewer is gone when the spawned process has exited. With none spawned, it is gone when the heartbeat has stopped.

Arguments

Name Type Description Default
timeout float | None

Seconds to wait at most. None waits without a limit.

None

Returns

Type Description
bool

True if the viewer is gone.

stats

stats() -> dict

Return the state of the session.

The result has the session token, the session file, the script, whether a viewer is attached, the viewer pid and the heartbeat age. Under views, each view has its publish and claim counters.

Returns

Type Description
dict

The state of the session.

close

close() -> None

Remove the session file and unlink the shared memory.

The call never waits for the viewer. The viewer keeps what it received and shows "session ended". Tensors that the session handed out keep their pages until they are freed.