Skip to content

View Calls

The view calls of the caliper package turn tensors into live views that every open route receives.

Call Cost

With nothing attached, a view call is one atomic load and a clock read. It takes no snapshot and no slot, and it does no GPU work. A scene call also runs its argument checks, which read host metadata only. With no viewer of the scene attached, scene.mesh, scene.lines and scene.points cost a few microseconds (Python Calls).

Rate Limit

Each view has a rate limit for each route. The rate argument of the call sets it.

rate Meaning
None (default) The default of the route: 60 snapshots per second (DEFAULT_RATE_HZ) for the session and the window, and every call for offscreen(). window(rate=...) changes the window default
> 0 At most that many snapshots per second for this view
0 A snapshot on every call, when a slot is free

The interval starts at the last snapshot of the view. A call inside the interval returns False. A view other than a series has 3 slots. A slot is busy when the GPU has not finished an earlier snapshot or the viewer still reads it. If all slots are busy, the call takes no snapshot, returns False and does not restart the interval. A negative or NaN rate raises ValueError.

A series is the exception. Every call appends its values on every attached route, and the view is republished at most rate times per second, with one pending snapshot at a time. watch(every=N) drops N-1 of N hook calls before the rate limit applies.

show

show(
    t,
    name: str = "tensor",
    cmap="viridis",
    vmin=None,
    vmax=None,
    rate=None,
    *,
    dims=None,
    data_view=None,
    items=None,
)

Show or update view name with tensor t as a heatmap or an RGBA image.

The call returns at once. With dims or data_view, the view shows a data view of t instead of the layouts below (Data Views).

Input Shown as
0-D or 1-D A 1xN heatmap strip
2-D (H, W) Heatmap (cast to float32 in the copy kernel)
(H, W, 3) or (H, W, 4) RGBA image
(1, H, W) Heatmap
(3, H, W) or (4, H, W) RGBA image
(C, H, W), any other C Channel mosaic heatmap: ceil(sqrt(C)) columns, empty cells NaN, range over all channels
(N, C, H, W) Item 0, then as above
More than 4 dims Leading dims stacked as channels, (-1, H, W)

A 3-D tensor whose last dimension is 3 or 4 is read as (H, W, C) if it is uint8 or its first dimension is not 1, 3 or 4. Otherwise it is read as (C, H, W).

Image values follow these rules: uint8 stays as it is, floating point is clamped to [0, 1] and scaled to 255, and other integers are clamped to 0..255. A missing alpha channel is 255. Booleans become float32 (uint8 for an image), and complex tensors become their magnitude. With autoscale, a non-finite range keeps the last finite one, and a flat range widens by +-0.5. NaN values draw as colormap index 0.

Arguments

Name Type Description Default
t Tensor

The tensor, in one of the layouts above.

required
name str

View id. The same name updates the view in place. Non-empty, with no ##.

'tensor'
cmap str | int

"viridis", "magma" or "rdbu" (case-insensitive), or 0, 1 or 2.

'viridis'
vmin float | None

Fixed lower end of the colormap range. None takes that end from a GPU aminmax of the snapshot. Each end is independent, and both must be finite.

None
vmax float | None

Fixed upper end of the colormap range, as for vmin.

None
rate float | None

Snapshots per second for this view (Rate Limit).

None
dims Sequence[str] | None

One name for each dimension of t, or for an image all but the color one (Data Views).

None
data_view dict | None

The default data view of the view, in the form of set_data_view.

None
items str | dict | None

The item space of the rows, as a name or as {dim: space}, for linked selection. See items.

None

Returns

Type Description
bool | ShowStats

True if a route took a snapshot. False when the call was rate limited, all slots were busy or nothing is attached. A ShowStats in the synchronous offscreen mode.

Raises

Type Description
ValueError

When name is empty or holds ##, when cmap is unknown, when vmin or vmax is not finite, or when rate is negative or NaN.

DataViewError

When data_view does not fit t.

points

points(
    z,
    labels=None,
    name: str = "points",
    classes=None,
    cmap="viridis",
    vmin=None,
    vmax=None,
    rate=None,
    *,
    dims=None,
    data_view=None,
    items=None,
)

Show or update view name as a scatter of the points z.

z is (N, 2) (pan and zoom) or (N, 3) (orbit). Any dtype is cast to float32 on its device, and N must be at least 1. The bounding box for auto-fit is computed on the device. With dims or data_view, z is a source of data views and labels follows its kept dimension. Above the point budget, points and labels are sampled with a stride. See Data Views.

Arguments

Name Type Description Default
z Tensor

The points, (N, 2) or (N, 3). With dims, one more leading dimension per name.

required
labels Tensor | None

Per-point labels or values, shape (N,), on the device of z or on the CPU. CPU labels for MPS points are copied to the device without waiting for its queue, from a private copy. The caller may reuse its tensor at once. Nothing is copied the other way. None draws one flat color.

None
name str

View id. The same name updates the view in place.

'points'
classes int | None

K categorical labels 0..K-1, drawn with a fixed 16-color palette (label L gets color L mod 16). Needs labels.

None
cmap str | int

Without classes, labels are colormapped as for show.

'viridis'
vmin float | None

Lower end of the label range. Without classes, None autoscales as for show.

None
vmax float | None

Upper end of the label range, as for vmin.

None
rate float | None

Snapshots per second for this view (Rate Limit).

None
dims Sequence[str] | None

One name for each dimension of z but the last, ending with the point dimension.

None
data_view dict | None

The default data view of the view.

None
items str | dict | None

The item space of the points, as a name or as {dim: space}, for linked selection. See items.

None

Returns

Type Description
bool | ShowStats

As for show.

Raises

Type Description
ValueError

When z has a wrong shape, when the label count is not N, when labels is on a device other than the device of z or the CPU, when classes is below 1, or when classes is given without labels.

DataViewError

When data_view does not fit z.

series

series(value, name: str = 'series', rate=None, *, items=None)

Append value to the series name.

The value is a Python int or float, a 0-d tensor, or a tensor of several values. Pass loss.detach(), not loss.item(), to avoid a GPU sync. A tensor of several values is flattened, and more than 4096 values keep the last 4096.

The series is a ring of the last SERIES_CAPACITY (4096) float32 values on the device of the value. A CPU series that later receives device values moves to the device with one host-to-device copy of its history. The x axis is the append index. Values offered while nothing is attached are not recorded. Every call appends on every attached route, and the view is republished at most rate times per second (Rate Limit).

Arguments

Name Type Description Default
value float | Tensor

The value or values to append.

required
name str

View id. The same name appends to the same series.

'series'
rate float | None

Republications per second for this view.

None
items str | None

The item space that the series index numbers, for linked selection. A series has no dims, so this is a name only. See items.

None

Returns

Type Description
bool | ShowStats

As for show. A series also returns True when a server of serve recorded the value.

Raises

Type Description
ValueError

When value is an empty tensor or name is invalid.

histogram

histogram(
    t,
    name: str = "histogram",
    bins: int = 64,
    rate=None,
    *,
    dims=None,
    data_view=None,
)

Show or update view name as the bin counts of every element of t over its [min, max].

The tensor is flattened and cast to float32, and it needs at least one element. The range comes from a GPU aminmax. Constant data uses [v - 1, v + 1] as torch.histc does, and NaN values fall into bin 0.

On MPS the binning runs on the device (index_add_) because torch.histc on MPS reads its range back to the host and drains the queue. On the CPU it is torch.histc. With dims or data_view, the histogram bins the data view of t. See Data Views.

Arguments

Name Type Description Default
t Tensor

The tensor.

required
name str

View id. The same name updates the view in place.

'histogram'
bins int

Number of bins, in 1..65536.

64
rate float | None

Snapshots per second for this view (Rate Limit).

None
dims Sequence[str] | None

One name for each dimension of t.

None
data_view dict | None

The default data view of the view.

None

Returns

Type Description
bool | ShowStats

As for show.

Raises

Type Description
ValueError

When bins is outside 1..65536 or t is empty.

DataViewError

When data_view does not fit t.

watch

watch(
    model,
    optimizer=None,
    *,
    activations: bool = True,
    gradients: bool = False,
    every: int = 1,
    include=None,
    rate=None,
    groups=True,
    scene: bool = True,
)

Hook a module so that show displays its outputs and gradients, and with an optimizer, the run.

The call returns a WatchHandle. The root module is labeled with its class name in lower case.

caliper.watch(model, optimizer)
for x, y in loader:
    loss = loss_fn(model(x), y)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

With an optimizer, watch() also does these things:

  1. It starts the stream server with serve when no server runs, so that the Caliper app can attach with control. The shared-memory session does not open, so no view appears twice in the app.
  2. It makes each optimizer.step() the checkpoint of the run, through a step pre-hook that calls step. Pending parameter values apply and queued actions run there, and a pause holds the run there, before the weights change. A script that passes an optimizer does not also call caliper.step().
  3. It registers the parameter lr and publishes the series loss and lr and the scene model.

In a managed run, which the model runner of the Caliper app starts with the environment variable CALIPER_RUN_DIR set, watch() also starts the server when it is not started. It loads the checkpoint of CALIPER_RUN_RESUME into the model and the optimizer before the first step and continues the step count. It applies the values of CALIPER_RUN_PARAMS and of the checkpoint when each parameter is registered. It registers the actions caliper.checkpoint, which saves the model, the optimizer, the step and the parameter values to <run dir>/checkpoint-<step>.pt and returns the path, and caliper.stop, which ends the script with exit code 0 at its next checkpoint, before the weights change. Last, it writes the stream link into CALIPER_RUN_LINK_FILE. Without an optimizer, each forward pass of the model is the checkpoint. See Managed Runs.

Name Kind Content
loss Series The last 0-d tensor that backward() ran on before each step, or inside the closure of optimizer.step(closure)
lr Series The learning rate that parameter group 0 used at each step
lr Parameter A number on a log scale, from the start rate of group 0 divided by 1,000 to the start rate multiplied by 10
model Scene The entity modules: one box for each module of WatchHandle.modules, along +y in that order

A new value of lr applies to the next optimizer step, and every parameter group moves by the same factor, so the ratios between the groups stay. Without a learning rate scheduler, the new rates stay in optimizer.param_groups. With a torch scheduler, the value scales the scheduler's schedule from that step on: before each step the hook multiplies the scheduled rates by the factor, and after the step it puts them back, so the scheduler neither undoes nor compounds the change. optimizer.param_groups and scheduler.get_last_lr() then show the scheduled rates, and the series lr shows the rate that each step used.

The size of a box shows the parameter count of its module, and its color the mean absolute value of the module's last output, computed at most 10 times a second and only while a viewer watches the scene. The row id of a box is the index of its module in WatchHandle.modules, so a pick on a box names the module, and each box has the module's name as its label.

The grouped views are heatmaps with data views. Their sources are the selected modules or their parameters, so one widget can switch between layers. The same hooks feed them, so watch() adds no hook for them.

View Sources Dims Default data view
weights <module>.<param>, every parameter with 2 or more dims out, in (higher-rank weights reshaped to (out, -1)) The first source, whole
activations <module>, with activations=True From the rank: batch, feature, or batch, position, feature, or batch, channel, height, width, or batch, channel, length for a 1-D convolution The first module, its leading dims at index 0
gradients <module>.<param>, with gradients=True, as the .grad views As weights The first source, whole

The weights and gradients have the same two dims, so {"source": "fc2.weight"} alone switches between them. Activations of different ranks have different dims. A request for another module must name its own index, and {} for a 2-D output.

weights takes a snapshot when its module runs forward and on update. With activations=False, it takes the snapshot after its gradient accumulates. A source does tensor work only when a route needs it. The window and the session need the source of the default data view, and a server needs the sources that its subscriptions select. The hook of any other source records the shape and returns.

A view has at most 64 sources, so a group keeps the first 64. Sources with names longer than 63 bytes are left out, each with a RuntimeWarning.

Arguments

Name Type Description Default
model Module

The module to hook.

required
optimizer Optimizer | None

The optimizer of the run. None watches the module only, as above.

None
activations bool

A forward hook per selected module shows its output as <module>.act. A tuple output gives its first tensor. Only floating-point, non-empty tensors show. (N, C, H, W) outputs show item 0 as a channel mosaic, and (N, F) outputs show a heatmap.

True
gradients bool

Each selected module shows the gradient of its own parameters that have 2 or more dims and requires_grad, as <module>.<param>.grad with colormap rdbu. Higher-rank weights are reshaped to (out, -1).

False
every int

Show 1 of every N hook calls (per hook). Must be at least 1.

1
include str | Sequence[str] | Callable[[str, Module], bool] | None

None selects leaf modules. Strings are fnmatch patterns over named_modules() names. A callable is predicate(name, module) -> bool.

None
rate float | None

Passed to show.

None
groups bool | str

Also offer the grouped views above. A string prefixes their names with <string>., and False offers none.

True
scene bool

With an optimizer, also publish the scene model. Without one, it does nothing.

True

Returns

Type Description
WatchHandle

The handle of the hooks. Its remove() takes them off, with the parameter lr.

Raises

Type Description
TypeError

When model is not a torch.nn.Module, or optimizer is not an optimizer.

ValueError

When every is below 1.

WatchHandle

The hooks of one watch call.

len(handle) is the number of hooks that are still on. A handle also works as a context manager, and leaving the block calls remove().

with caliper.watch(model) as handle:
    train(model)

active

active: bool

True while the handle holds hooks.

views

views: list[str] = []

The view names that the hooks show into.

modules

modules: list[str] = []

The names of the hooked modules.

groups

groups: list[str] = []

The names of the grouped views, with the prefix that watch was given.

remove

remove() -> None

Take every hook off and remove the grouped views, the parameter lr and the actions.

The actions are caliper.checkpoint and caliper.stop of a run that the Caliper app started.

The series and the scene stay. Without a learning rate scheduler, a learning rate that a viewer set stays in the optimizer. With one, the scheduler's own rates apply again.

With an optimizer, watch also puts the script under run control, publishes the series loss and lr and the scene model, and keeps the shared memory session closed. Watch With an Optimizer describes it.

MPS Zero-Copy

A snapshot is a few torch operations queued on the stream of the tensor. They write into a slot that the route allocated as CPU-readable shared memory and handed to torch through DLPack. The session uses a shared-memory segment, and the window uses a Caliper-made shared MTLBuffer.

The snapshot code calls no .item(), .cpu(), .numpy(), .tolist() and no synchronize(). It detects completion by polling a torch.mps.Event. synchronize() appears only in flush() and close().

A CPU tensor is copied once into the slot. Tensors on any other device (CUDA) have no zero-copy path on macOS, and one host copy moves them to the CPU first. Labels for points may move host to device, never device to host.