Debug with a coding agent¶
A coding agent can pause training, inspect layers, and trace numerical problems for you with nansense-cli, a command-line client that ships with NaNsense.
The agent and browser share one session, so you can follow its work in the UI.
Connect¶
Start your run as usual:
uv run --group cpu examples/standard/main.py --nansense-port 6464
The startup banner prints the command an agent starts from:
┌──────────────────────────────────────────────────────────────────────┐
│ NaNsense UI is running at: │
│ http://127.0.0.1:6464 │
│ │
│ Debug this run from a coding agent: │
│ /home/you/project/.venv/bin/python -m nansense_cli --port 6464 tools │
└──────────────────────────────────────────────────────────────────────┘
The banner uses the run's own Python when nansense-cli is not on PATH or is found only inside the run's virtual environment (as under uv run). That command works without activating the environment in the agent's shell. When nansense-cli is found on PATH outside that environment, the banner prints just nansense-cli. The examples below use the short name.
The banner appears once the endpoint accepts connections. An agent that launched the run in the background can wait for the banner, or pass --wait 60 to its first command to wait up to 60 seconds for the server to accept connections.
If the agent started the run itself, it reads this line from the output. Otherwise, tell it which port to use: "Debug my training run with nansense-cli --port 6464." Nothing needs to be registered, so several agents can each debug their own run on its own port at the same time.
tools prints a short guide and one line per tool. The agent then calls a tool by name, with its arguments as flags:
nansense-cli --port 6464 tools # the guide and the tool list
nansense-cli --port 6464 get_layer_stats --help # one tool's description and flags
nansense-cli --port 6464 get_layer_stats --layers conv1 fc
nansense-cli --port 6464 configure_debug_checks --interval_batches 1
nansense-cli --port 6464 render_layer --layers conv1 --out shots
Most tools print JSON results. The render_* tools print a descriptive note and any additional JSON details; the CLI saves their pictures as PNG files under --out (default .nansense-cli/) and prints the paths, so the agent opens only the ones it needs. A tool error goes to stderr with a non-zero exit code. That includes a refusal, such as stepping a run that has finished; the message says why.
To turn agent access off, pass mcp=False to serve.
It listens on localhost
The endpoint is bound wherever you bound the UI, and it can control your training run. On the default loopback bind it also rejects requests carrying a foreign Host header, so a web page you visit cannot reach it. Don't expose the port to an untrusted network.
What the agent can do¶
Ask in plain language — "why has my loss stopped falling?" — and the agent works through the tools below.
| Tool | What it does |
|---|---|
get_status |
Where the run sits: paused or running, position, watched layers, any numerical warning |
get_architecture |
Layer names, hyperparameters and the compute graph |
get_layer_stats |
Activation and gradient statistics for the last captured batch, for any layer |
rank_layers |
Top layers from the last captured batch, ranked by activation or gradient std, abs max, NaN/Inf share, or dead-channel share |
get_stats_history |
One layer's statistics per epoch — the trend across the run |
get_debug_report |
Which layers produced NaN/Inf or collapsing gradients, with per-layer percentages |
step, run, run_until, pause |
The top bar's run controls — including detach, as run --detach, and step --count N for N batches (counts above 1 require a known phase length and must stay within that phase) |
refresh |
Publish a fresh snapshot from a free-running session without pausing it |
watch_layers, unwatch_layers, set_stats_scope |
Choose which layers collect running statistics |
configure_debug_checks, silence_debug_check |
Tune the numerical-error checks |
get_weight_stats |
A layer's parameters, their gradients, and the optimizer state moving them |
get_metrics |
Custom scalar metrics registered with watch_metric |
get_settings, set_update_frequency, set_watch_performance |
The settings dialog |
Run controls return a short status; get_status has the full view. Filter custom metrics with --metrics, --phase and --layers; --last N keeps each series' newest N points.
Statistics come from two places, and the distinction matters when you read the agent's reasoning. get_layer_stats reads the last captured batch and covers any layer. get_stats_history reads the running accumulators, which only cover watched layers and only while collection is on (it is off by default) — so the agent watches a layer, turns collection on with set_stats_scope, lets a few epochs run, and then asks for the trend. Ask too early and the tool names which of the three is missing rather than returning an empty series.
What the agent can see¶
The render_* tools return the views as pictures — the same ones the browser draws, rendered server-side and saved as PNG files the agent looks at directly.
| Tool | The view |
|---|---|
render_layer |
Per-channel activation and gradient strips: red positive, blue negative, NaN/Inf as transparent holes. average collapses each strip to one mean tile, values="abs"/"square" shows magnitude, background draws the input behind spatial tiles and size sets the tile size, matching the page's render options. first_channel/channel_count select a window of channel tiles while keeping the full strip's colour scale; single-tile strips stay whole. Captured custom tensors from watch_layer_tensor are drawn as extra rows, except in probe views |
render_input |
One sample of the model's input, denormalized |
render_weights |
A layer's kernels, gradients, optimizer state and custom tensors from watch_weight_tensor, plus the live learning rate |
render_histogram |
Value distributions of watched layers, over the signed-log bins. bands marks the dtype's subnormal/near-overflow edges where visible, and current_batch draws the last captured batch for any layer with captured data, matching the stats page's options (phase is ignored) |
render_extreme_patches |
The inputs that most (and least) excite each channel |
render_bin_samples |
The inputs behind one histogram bar — which samples landed in it |
This is worth its tokens when the numbers say that something is wrong but not where. A layer's mean and standard deviation look healthy while one channel of sixty-four is dead; the strip shows that at a glance. A conv filter that has collapsed to noise, an activation saturating along one edge of the image, a gradient histogram with a spike in the overflow bin — all are shapes, not scalars.
Pictures are capped at 1568 pixels on the longest side and downscaled past it, with a note saying so, since a wide layer would otherwise arrive as an unreadably large image.
Raw tensors¶
When neither statistics nor pictures answer the question, export_tensors --layers conv1 fc returns the latest captured batch's tensors as one .pt file: each layer's activation and parameters, with available gradients, optimizer state, numeric optimizer hyperparameters and custom tensors. The CLI saves it under --out and prints the path alongside a JSON manifest of shapes, dtypes and batch position. --no-weights exports only activations, their gradients and custom layer tensors; --no-activations exports only parameters and their associated data.
The agent loads the file with torch.load(path, weights_only=True) and analyses it with its own scripts. Tensors include the full batch and every channel, on CPU, with each tensor's captured dtype preserved. Missing entries are omitted; optimizer state and hyperparameters require an optimizer passed to start. The server writes no file. Each export is capped at 256 MiB of tensor data, excluding file overhead; select fewer layers or disable activations or weights for a smaller export.
What the agent can try¶
Reading a paused run is one thing; the rest of the UI is about interrogating it.
| Tool | What it does |
|---|---|
time_travel, get_time_travel_status |
Restart at an earlier epoch, with the model, optimizer and scheduler restored |
get_hyperparameters, set_hyperparameters |
Read the optimizer's numeric settings; change them while paused, for one parameter group or all groups |
pin_batch, unpin_batch, set_probe_mode, get_probe_status |
Re-run the model on one fixed input at every capture |
add_perturbation, clear_perturbations |
Edit that input and see which layers move |
list_experiments, run_experiment, get_experiment_result, render_experiment, cancel_experiment |
Deep dream, Captum attributions and the training script's custom experiments — run_experiment --video records deep dream or streamed custom results to MP4 |
set_auto_run_experiments |
Stop open experiment pages re-running on the thread you need |
Custom tools, get_tool_result |
Call functions registered with session.tool, listed by tools; poll queued or running calls with get_tool_result --seq N |
start_recording, stop_recording, discard_recording, list_recordings |
Record a view to MP4, one frame per visualization update — view is a typed per-view specification |
save_snapshot |
Save one still of a view as a PNG file to hand a human, from the same typed view |
Time travel is the one that changes how debugging goes. An agent that has run past a divergence normally has to restart the script. Instead it can jump back to the epoch before it, this time with configure_debug_checks --interval_batches 1 and the suspect layers watched — so the second pass sees what the first one missed. It needs the training loop driven by session.epochs() with session.restore_point(); get_time_travel_status says whether yours is.
Combine time travel with a hyperparameter change to test a fix. Call time_travel --epoch 3, then set_hyperparameters --values '{"lr": 0.0001}' to set every parameter group's learning rate to 0.0001 before resuming epoch 3. Travel first: the jump restores the checkpoint's hyperparameters and active learning-rate multipliers. get_hyperparameters identifies an attached scheduler and explains how it may change or replace the edited learning rate at later scheduler steps.
Add --rescale_schedule to scale future learning rates while keeping the schedule's shape. This requires a scheduler passed to start and an lr value. For each targeted group, the multiplier is new lr ÷ the schedule's current, unscaled lr, applied after every later scheduler step. get_hyperparameters reports active multipliers as lr_multiplier alongside the unscaled scheduled_lr. Set lr to that group's scheduled_lr with the same flag to end its multiplier. Only lr is rescaled; schedulers still control any momentum or betas they cycle.
Pin inputs for fair comparisons. Normally, both the weights and batch change as you step. Pinning a batch keeps the input fixed, so differences come from the model. Use set_probe_mode --mode eval to check evaluation behavior, including BatchNorm's running statistics.
Experiments run on the paused training thread, so pause first, or the request queues until the next pause. There is a wall-clock ceiling on each run, and run_experiment returns statistics while render_experiment draws the result. A result you poll before it exists is not simply missing: get_experiment_result reports the request's stage — running, queued (with queued_ahead), or absent — so waiting longer and re-requesting are told apart.
Experiment parameters are validated before queuing or replacing a recording’s auto-run. Invalid types and non-finite numbers return an error without changing the existing request. Unknown parameter keys are reported as ignored.
Record deep dream as a video. render_experiment returns the final image. Use run_experiment ... --video when the path it took matters. By default, the video keeps about 20 evenly spaced frames; pass --params '{"all_steps": true}' to keep every step.
Recordings capture change over time. One frame per visualization update — so set_update_frequency is the frame rate, and a run that stays paused records nothing. Start one, let training run, then stop it for the file path to show a human — or discard it, if the take went wrong, so no half-finished file is left looking like a result. save_snapshot is the same thing at length one: a single PNG of a view as it stands, written immediately, with nothing to start or stop. Use it for the file you want a human to open — the render_* tools return the picture to you.
Both take one view argument: an object whose own view field names the page — layers, weights, histograms, patches or experiment — alongside only the arguments that page takes, so {"view": {"view": "layers", "layers": ["conv1"], "average": true}} records the main view while {"view": {"view": "weights", "layer": "conv1"}} records one layer's kernels. The tool schema carries a variant per view with its fields and defaults, so there is nothing to guess. The experiment variant differs between the two: a recording registers a re-running request (layer, kind, params) so each frame is fresh, while a snapshot draws a result already published (seq, default the newest).
A worked example¶
A typical exchange, once the run is paused:
You: Training loss goes to NaN around epoch 3. Find out where it starts.
The agent calls get_status to see the run is paused at epoch 0, then configure_debug_checks --interval_batches 1 so the checks run on every batch instead of every hundredth, then run and polls until the debugger trips. get_debug_report names the layer and the fraction of its gradient that went non-finite, and get_layer_stats on that layer and the one feeding it shows which of the two was already unhealthy a batch earlier.
Because the agent is driving the same session, you can open the UI at any point and see exactly the batch it stopped on.
Things worth knowing¶
Two positions. live_position is where training is now; snapshot_position is the batch the statistics describe. They're identical while paused and diverge once the run advances freely — the tools report both so the agent doesn't read stale numbers as current.
Non-finite values are explicit. Since JSON has no NaN literal, tools return "nan", "inf", and "-inf" as strings. Statistics describe finite values; non_finite_count reports the rest.
Long steps don't hang. A step over a slow epoch returns after a timeout with a note that the run is still going; the command stays in effect and the agent polls get_status.
A finished run keeps serving. After training ends, the page stays up for post-mortem browsing, keeping the process alive. Press Ctrl-C or call shutdown from the agent to stop the server. shutdown allows the process to exit once the training script has ended; it is refused while training is still live or the session is locked.
Locked sessions refuse. On a locked demo session the control tools return an explicit refusal rather than silently doing nothing, so an agent can't loop forever stepping a run that never moves. Inspection keeps working.