Run Control Calls¶
The run control calls let viewers pause a training loop, change its parameters, run its actions and link selections across views.
Controls¶
Controls let viewers reach back into the running script. They pause, resume and single-step its training loop, change the parameters it registered and run the actions it registered. Linked selection makes a selection in one view highlight the same items in the other views.
Both travel on the stream as messages of wire protocol 3.1 (Controls and Linked selection). Thus they work while a notebook cell runs, when the kernel cannot read widget messages. The viewers of caliper.serve() may control unless it started with control=False. The viewers of a hub that connect() streams to may control only when the hub started with --allow-control. Both senders carry them.
Script Control uses them in a training loop. Every call also works without a server. Parameters keep their values, step() returns at once, and Python code can call an action.
step¶
step(step=None) -> None
Mark the checkpoint of the training loop, where the controls change the script.
Call it once per step, on the training thread, between two steps. It is the only place where the controls change the script. There it sets the parameter values that viewers changed, runs the actions they asked for in the order they asked, and waits while a viewer has paused the run.
A waiting step() returns in these cases:
- A viewer resumes the run or asks for a number of single steps.
- The server closes.
- No connection that may control has been open for 10 seconds. A page reload stays well within this time.
While it waits, it still sets values and runs actions as they arrive. Ctrl-C, or the
interrupt of a notebook, ends the wait with KeyboardInterrupt, and the run is no longer
paused afterward. Right before it waits, it sends the snapshots and series values of the step
where it paused. The run state goes to each viewer after them, so a view that reads paused
already shows that step (What a viewer may rely
on).
With nothing waiting, a call only counts the step and reads one flag. While the run runs and a server is open, the first call after each second also sends the step number to the viewers.
Before the first step() of the script, viewers can change parameters, which then take
effect at once. They cannot pause the run, and actions wait for the first checkpoint.
Arguments
| Name | Type | Description | Default |
|---|---|---|---|
step
|
int | None
|
The number of the step, which viewers show where the run paused.
|
None
|
pause¶
pause() -> bool
Pause the run at the next step, as the Pause button of a viewer does.
Use it for example when the loss stops being finite. A viewer resumes the run. When no stream
server runs, no viewer could resume it. The call then does nothing and warns with a
RuntimeWarning. When a server runs but no connection may control it, the call warns that the
run resumes after 10 seconds.
Returns
| Type | Description |
|---|---|
bool
|
|
param¶
param(
name: str, value, *, min=None, max=None, log=False, choices=None, help=None
) -> Param
Register a parameter that viewers can change while the script runs.
lr = caliper.param("lr", 1e-3, min=1e-5, max=1e-1, log=True, help="learning rate")
for batch in loader:
caliper.step()
for group in opt.param_groups:
group["lr"] = lr.value
The type of the value sets the type of the parameter:
value |
Type | A viewer shows |
|---|---|---|
bool |
boolean |
A toggle |
int |
integer |
A slider or a field |
float |
number |
A slider or a field |
str, with choices |
choice |
A menu |
A value from a viewer is checked and clamped. A number or an integer is clamped to min and
max, an integer must be a whole number, and a choice must be one of choices. The value
reaches Param.value at the next step, or at once before the first step()
of the script. When a viewer sends several values before a step(), the last one wins.
Registering a name again replaces the parameter. A script has at most 64 parameters.
Arguments
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
1 to 63 bytes. Registering a name again replaces the parameter. |
required |
value
|
bool | int | float | str
|
The first value. Its type sets the type of the parameter. |
required |
min
|
int | float | None
|
The lower end of the range of a number or an integer. A value from a viewer is clamped to it. |
None
|
max
|
int | float | None
|
The upper end of the range of a number or an integer. A value from a viewer is clamped to it. |
None
|
log
|
bool
|
Draw the slider on a log scale. Needs |
False
|
choices
|
Sequence[str] | None
|
The choices of a |
None
|
help
|
str | None
|
A tooltip, at most 1,024 bytes. |
None
|
Returns
| Type | Description |
|---|---|
Param
|
The registered parameter. Read its |
Raises
| Type | Description |
|---|---|
ValueError
|
When an argument is out of range, for example |
TypeError
|
When |
Param ¶
A parameter that viewers can change while the script runs, made by param.
The script reads value in its loop. A viewer changes it through the stream.
Attributes
| Name | Type | Description |
|---|---|---|
name |
str
|
The name of the parameter. |
type |
str
|
|
min |
int | float | None
|
The lower end of the range, or |
max |
int | float | None
|
The upper end of the range, or |
log |
bool
|
Whether a viewer draws the slider on a log scale. |
choices |
tuple[str, ...] | None
|
The choices of a |
help |
str | None
|
The tooltip, or |
value ¶
value
The current value, to read in the loop, from any thread.
It changes only in step, or at once before the first step() of the
script.
set ¶
set(value)
Set the value from the script, at once and for every viewer.
The value is checked and clamped like a value from a viewer.
Arguments
| Name | Type | Description | Default |
|---|---|---|---|
value
|
bool | int | float | str
|
The new value, of the type of the parameter. |
required |
Returns
| Type | Description |
|---|---|
bool | int | float | str
|
The value set. |
Raises
| Type | Description |
|---|---|
ValueError
|
When the value has another type or is not one of the choices. |
remove ¶
remove() -> bool
Take the parameter away from the viewers.
value keeps its last value.
Returns
| Type | Description |
|---|---|
bool
|
|
action¶
action(name: str, fn=None, *, help=None)
Register a function that viewers can run, as an action.
@caliper.action("save checkpoint", help="saves the model's weights")
def save_checkpoint():
torch.save(model.state_dict(), "checkpoint.pt")
return "saved checkpoint.pt"
caliper.action(name, fn) registers fn, a function without arguments. caliper.action(name)
does the same as a decorator. A request of a viewer runs the function at the next
step, on the training thread, after the parameter values are set. Requests
run one at a time in the order they arrived. A request for an action that already waits joins
that run.
The text that fn returns goes back to the viewer that asked, cut to 1,024 bytes. An
exception goes back to that viewer with its message and appears in the script as a
RuntimeWarning. It does not stop the loop. A request that no step() has run within 10
minutes fails with a time-out. A script has at most 64 actions, and registering a name again
replaces the action.
Arguments
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the action, 1 to 63 bytes. |
required |
fn
|
Callable[[], object] | None
|
The function to run. |
None
|
help
|
str | None
|
A tooltip, at most 1,024 bytes. |
None
|
Returns
| Type | Description |
|---|---|
Action
|
The registered action, or a decorator that returns it when |
Raises
| Type | Description |
|---|---|
ValueError
|
When |
TypeError
|
When |
Action ¶
A function that viewers can run, made by action.
A request of a viewer runs fn() at the next caliper.step(), on the thread that calls it.
Attributes
| Name | Type | Description |
|---|---|---|
name |
str
|
The name of the action. |
fn |
Callable[[], object]
|
The registered function. |
help |
str | None
|
The tooltip, or |
items¶
items(space: str, details=None) -> ItemSpace
Register the item space space for linked selection, with optional details.
caliper.items("eval", details={"class": eval_labels})
caliper.points(z, eval_labels, "embedding", classes=10, items="eval")
caliper.show(probabilities, "predictions", items="eval")
An item space is a set of items numbered from 0 that several views index, such as the samples
of an evaluation set. A view names the item space of its item axis with items=, a keyword of
show, points, series and offer:
| Call | items="eval" names the space of |
|---|---|
show |
Its rows: the first dimension, or the first of dims |
points |
Its points: the point dimension |
series |
Its index, the number of values appended before each value |
offer |
The first dimension of each source, or the point dimension of points |
items={"sample": "eval"} names the dimensions of dims instead. A histogram has no item
axis. A selection made on an axis with an item space highlights the same items in every view
of the session that names the space: the points, the rows of a heatmap and markers on a
series. A call without items= has no extra cost.
details gives a viewer a few fields of the selected items, shown in a small table under the
view where the selection was made. It is one of two forms:
- A mapping
{field: sequence}indexed by item id, copied to the host once, at the call. - A function
fn(ids)that returns{field: values}in the order ofids, or one dict per item.
The function runs on the thread caliper.details, never on the training thread, and has 2
seconds. It must read only data that the loop does not change in place, such as labels or
arrays that the script computed before. Details cover the first 32 selected items and at most
16 fields. Each value is a number, a string of at most 256 bytes, a boolean or None.
A session has at most 16 item spaces. Python code also receives each select event through
server.on_event, server.events(), widget.selection and on_select. Its detail has
space and items too.
Arguments
| Name | Type | Description | Default |
|---|---|---|---|
space
|
str
|
The name of the item space, 1 to 63 bytes. |
required |
details
|
dict | Callable[[Sequence[int]], object] | None
|
The details of the selected items, in one of the two forms above. |
None
|
Returns
| Type | Description |
|---|---|
ItemSpace
|
The item space, with the current selection and the calls to change it. |
Raises
| Type | Description |
|---|---|
ValueError
|
When a name is invalid, a details column has too many fields, or the session would have more than 16 item spaces. |
TypeError
|
When |
ItemSpace ¶
A set of items numbered from 0 that several views index, made by items.
An example is the samples of an evaluation set. A selection in one view highlights the same items in every view that names the space.
Attributes
| Name | Type | Description |
|---|---|---|
name |
str
|
The name of the item space. |
selection ¶
selection: list
The list of selected item ids, ascending.
A viewer or select set it. It is current even while a notebook cell runs.
select ¶
select(items) -> list
Set the selection from the script, for every viewer.
An empty sequence clears it.
Arguments
| Name | Type | Description | Default |
|---|---|---|---|
items
|
Iterable[int]
|
The item ids to select. |
required |
Returns
| Type | Description |
|---|---|
list[int]
|
The item ids as viewers get them: ascending, without repeats, at most 32,768. |
Raises
| Type | Description |
|---|---|
ValueError
|
When an id is negative. |
controls¶
controls(*, height: int = 160)
Show the run controls, parameters and actions of the script in a notebook widget.
The widget is like widget. It shows the run state, the Pause, Resume and
Step buttons, every parameter and every action of the script, and the result of the last
action it ran. It reads the stream directly, so it works while a cell runs, and it starts
serve when no server runs. Its traits are src and height. The header of
every view widget also shows the run state and the Pause, Resume and Step buttons.
A build whose browser assets lack the module of the panel, caliper-controls-widget.js,
warns and shows a note in its place. The call needs the notebook extra caliper[notebook].
Arguments
| Name | Type | Description | Default |
|---|---|---|---|
height
|
int
|
Height of the whole panel in CSS pixels. |
160
|
Returns
| Type | Description |
|---|---|
AnyWidget
|
The controls panel. |
Watch With an Optimizer¶
caliper.watch(model, optimizer) is the one line that puts a training script under run control. Its signature is caliper.watch(model, optimizer=None, *, activations=True, gradients=False, every=1, include=None, rate=None, groups=True, scene=True), and every argument after optimizer is a keyword. Without an optimizer, the call behaves as before. With one, it starts caliper.serve() when no server runs, and it keeps the shared memory session closed. Thus a view does not appear twice in an app that attaches with --url.
The call makes optimizer.step() the checkpoint of the run with a step pre-hook. At each checkpoint the hook publishes the loss, calls caliper.step() and writes the parameter lr into the parameter groups. Pending parameters apply, queued actions run and a pause waits there, before the weights change. A script that passes an optimizer must not also call caliper.step().
The call registers the parameter lr on a log scale, from the start rate divided by 1,000 to the start rate multiplied by 10. It registers no parameter when parameter group 0 has no positive rate, and it warns instead. A new value of lr is the rate of group 0 and moves every other group by the same factor. It applies to the same optimizer step.
The call also publishes these names:
| Name | Kind | Content |
|---|---|---|
loss |
Series | The last 0-d tensor that backward() ran on before the step, also for a closure that optimizer.step(closure) runs |
lr |
Series | The learning rate of group 0 that each step used |
model |
Scene | One entity, modules, with one box for each watched module along +y |
The size of a box shows the parameter count of its module, and its color shows the mean absolute value of the last output of the module. The label is the module name. The row id of a box is the index of its module in WatchHandle.modules, thus a pick on a box names the module. The scene is computed only while a viewer watches it. The argument scene=False leaves it out.
Without a scheduler, the new rates stay in optimizer.param_groups. Under a torch learning rate scheduler, a new lr scales the schedule from the step where it applies. The hook multiplies the scheduled rates by a factor before each step and takes it off after the step. The scheduler thus neither undoes the change nor compounds it. param_groups and get_last_lr() show the scheduled rates, and the series lr shows the rate that the step used. WatchHandle.remove() also removes lr and the loss tap, and it leaves the series and the scene.
Programs in the Script¶
Under caliper.watch(model, optimizer), the script announces the capabilities programs and interventions to a viewer. The app then sends the GPU programs of its open spec as PROGRAM messages (GPU Programs). The script needs no other line. A script that does not call caliper.watch(model, optimizer) announces neither capability.
The module caliper._producer loads when the first program arrives, thus a script that only streams tensors loads nothing new. It compiles the program through the sandbox, imports each input tensor on the GPU in place and read-only, and never copies a training tensor. caliper.step() runs the programs that are due after the work of the step is done. A program runs every N steps, as the cadence of the program rules, and its GPU time has a limit. A program that is refused or stopped is an error of its panel and never raises in the script.
An input is live:<name>. The name is a parameter name of the watched model, a parameter name with .grad added for its gradient, or a module name with .act added for the last output of the module. The script gives a geometry output to the publish path of caliper.scene, as a batch of the target entity. It gives a pixels output to caliper.show, as the live view program.<id>. A pick, a selection and a recording then work on the output as on any other. The script answers each PROGRAM with a PROGRAM_STATE, and it sends the status of each program again after a change and at most twice a second while programs run.
The script also lists each module of the model as an intervention point by its dotted name, and each head of an attention module that has a head count and an output projection as <module>#<h>. A CONTROL with the op intervene sets or clears an ablate of a point, and the script applies it at the next step with a forward hook. The wire messages are in the wire protocol reference.
Watch in a Managed Run¶
The app's model runner starts a script as a managed run and sets CALIPER_RUN_DIR, with the other variables of Managed Runs. When that variable is set, caliper.watch(model, optimizer) and caliper.watch(model) also do the following, and the script needs no other line.
- It starts the server when none runs.
- It loads the checkpoint that
CALIPER_RUN_RESUMEnames into the model and the optimizer, and the step count continues from the step of the checkpoint. A run that resumes redoes that step with its own parameter values. - It applies the parameter values of the checkpoint, and then those of
CALIPER_RUN_PARAMS, when each parameter is registered. A value of the wrong type causes a warning, and a number out of range is clamped. - It registers the actions
caliper.checkpointandcaliper.stop. - It writes the link file that
CALIPER_RUN_LINK_FILEnames, with the stream link and no newline. The file comes last, thus the app that attaches finds the parameters and the actions.
The action caliper.checkpoint writes checkpoint-<step>.pt in the run folder at the next checkpoint and returns its path. The file holds the model state, the optimizer state, the step and the parameter values. The action caliper.stop makes the script end with SystemExit(0) at its next checkpoint, after it sends what is pending and before the weights change. It also ends a pause.
Without an optimizer, each forward pass of the model is the checkpoint, thus an inference loop with caliper.watch(model) takes the actions too. Such a script must not also call caliper.step(). Outside a managed run, caliper.watch does none of this.