---
# System prepended metadata

title: 'Proposal: Add print_value() builtin to gtscript'
tags: [gtscript]

---

# Proposal: Add print_value() builtin to gtscript

###### tags: `gtscript`

Author: Johann Dahm <johann.dahm@gmail.com>

## Motivation

When writing large stencils, it's difficult to debug state changes, so
it would be helpful to be able to add `print()` statements inside stencils.

## Feature

```python
@gtscript.stencil(backend="numpy")
def stencil():
    with computation(PARALLEL), interval(...):
        tmp = infield[1, 0, 0]
        print_value(2 * tmp[0, 0, 0], msg="DEBUG", i=0, j=5)
        outfield = tmp[0, 1, 0]
```

## Syntax

```python
def print_value(expr, *, msg: str, **kwargs):
    ...
```

`msg` is an argument that is printed before the expr, and `**kwargs` are the constraints.

The user can specify any set of constraints, e.g. setting only `i=...` would print for all `j` and `k` with that `i` value, etc.

## Output

The output for unconstrained axes is not guaranteed to be ordered in a deterministic way, but it must follow the GridTools parallel model. For example the print above takes place in a `PARALLEL` loop so it might print in the following way:

```
DEBUG(i=0, j=5, k=0) = 1.2678564
DEBUG(i=0, j=5, k=1) = 6241.5
DEBUG(i=0, j=5, k=3) = 1.4
DEBUG(i=0, j=5, k=2) = 1.2678564
...
```

## Supported backends

This could be implemented by all backends.

## Questions/Comments

- HV: What is the expected behavior if the printed variable gets optimized away. Should the print disappear or should it limit optimizations?
    - JD: Currently there is no method of optimizing away the prints.
- HV: For the GridTools backends, the index is not available by default, we need to inject the `positional` which alters the generated code.
    - JD: Good point. We already do this for the horizontal regions, but it'll take a bit of code to implement for this path as well.
- HV: Since this is a pure debug thing, let's put that in the name.
    - JD: I had `debug_print` but some people thought `print_value` is better. What about `debug_print_value`? Or, `PRINT_VALUE` to make it stand out.
- HV: I would be interested in a more detailed motiviation for which kind of debug situation this is useful. That might answer my other questions above. Will it primarily used in the numpy backend or in the optimized backends? Because my answer to the current motivation would not be a print statement but debugger support.
    - JD: The particular case is tracking down where a value changes at a particular index. In general yes, users want debugging support, and that is already possible in vscode inside the numpy backend, since users can set breakpoints.
    - HV: So you want it for the optimized backends?
    - JD: There's no reason not to implement for the optimized backends. It could help users track down issues in the parallel model if any exist.