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'
|
vmin
|
float | None
|
Fixed lower end of the colormap range. |
None
|
vmax
|
float | None
|
Fixed upper end of the colormap range, as for |
None
|
rate
|
float | None
|
Snapshots per second for this view (Rate Limit). |
None
|
dims
|
Sequence[str] | None
|
One name for each dimension of |
None
|
data_view
|
dict | None
|
The default data view of the view, in the form of
|
None
|
items
|
str | dict | None
|
The item space of the rows, as a name or as |
None
|
Returns
| Type | Description |
|---|---|
bool | ShowStats
|
|
Raises
| Type | Description |
|---|---|
ValueError
|
When |
DataViewError
|
When |
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, |
required |
labels
|
Tensor | None
|
Per-point labels or values, shape |
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 |
None
|
cmap
|
str | int
|
Without |
'viridis'
|
vmin
|
float | None
|
Lower end of the label range. Without |
None
|
vmax
|
float | None
|
Upper end of the label range, as for |
None
|
rate
|
float | None
|
Snapshots per second for this view (Rate Limit). |
None
|
dims
|
Sequence[str] | None
|
One name for each dimension of |
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 |
None
|
Returns
| Type | Description |
|---|---|
bool | ShowStats
|
As for |
Raises
| Type | Description |
|---|---|
ValueError
|
When |
DataViewError
|
When |
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 |
None
|
Returns
| Type | Description |
|---|---|
bool | ShowStats
|
Raises
| Type | Description |
|---|---|
ValueError
|
When |
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 |
None
|
data_view
|
dict | None
|
The default data view of the view. |
None
|
Returns
| Type | Description |
|---|---|
bool | ShowStats
|
As for |
Raises
| Type | Description |
|---|---|
ValueError
|
When |
DataViewError
|
When |
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:
- It starts the stream server with
servewhen 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. - It makes each
optimizer.step()the checkpoint of the run, through a step pre-hook that callsstep. 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 callcaliper.step(). - It registers the parameter
lrand publishes the serieslossandlrand the scenemodel.
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
|
activations
|
bool
|
A forward hook per selected module shows its output as |
True
|
gradients
|
bool
|
Each selected module shows the gradient of its own parameters that have 2
or more dims and |
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
|
rate
|
float | None
|
Passed to |
None
|
groups
|
bool | str
|
Also offer the grouped views above. A string prefixes their names with
|
True
|
scene
|
bool
|
With an optimizer, also publish the scene |
True
|
Returns
| Type | Description |
|---|---|
WatchHandle
|
The handle of the hooks. Its |
Raises
| Type | Description |
|---|---|
TypeError
|
When |
ValueError
|
When |
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)
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.