Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,8 @@ argument type signature + array/scalar/texture categories + vector widths + text

That last one matters for correctness, not speed. `ir_resolve` substitutes dimension sizes as literals — `a[i, j]` linearizes to `i * dim1 + j` with `dim1` baked in — so the row stride is part of the compiled code's identity. `shape_signature()` reports exactly the dimensions a kernel bakes in (memoized per IR; empty for 1-D kernels, so varying a flat length does **not** re-specialize).

`variant_key_parts` beside `kernel_variant_key` names each position of the key for `TACK_LOG_COMPILES` (`runtime/compile_log.py`: one stderr line per new variant, built or loaded, with the parts changed since the kernel's last logged variant and the stages' times, slow path only; class tokens carry a name and serial for it): a new key part needs a name there (`test_compile_log.py`).

Because the passes mutate IR in place, the template from `get_ir()` must be treated as immutable — a pass that consumed its `IRDimSize` nodes would leave nothing for a later shape to resolve.

Arrays may share storage, including distinct views and imported pointers. Preserve program order within each race-free iteration; array parameters must not carry unconditional `noalias`/`restrict` promises.
Expand Down
9 changes: 9 additions & 0 deletions changelog.d/compile-log.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
### Added

- `TACK_LOG_COMPILES=1`: every call that makes a new kernel variant writes one
line to stderr naming what about the call made it new (an argument's type,
a dimension the code bakes in such as a row stride, a device class's
constant, or a class defined afresh), whether it was built or loaded from
the disk cache, how many variants the kernel holds, and the host time of
each stage. Calls that find their variant write nothing, and the warm
dispatch path is unchanged (#325).
1 change: 1 addition & 0 deletions docs/contracts/runtime-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -753,6 +753,7 @@ it is queued (see [Host operations](#host-operations)).
| `TACK_DEBUG` | `import tack` (`runtime/dispatch.py`) | A boolean flag read like `TACK_NO_REINIT`: turns on debug mode's bounds checks. `tack.set_debug` overrides it (above) |
| `TACK_FILL_NEW` | `import tack` (`lang/array.py`) | A byte, `0xFF` or `255` (Python's integer spelling), `off`, or unset or empty. Every new array (`tack.empty` and every constructor over it) is filled with that byte on every backend, so code that reads an array before writing it reads with `0xFF` NaN floats, -1 signed integers and an unsigned type's largest value (255 for `u8`). Unset, debug mode fills with 0xFF; `off` fills nothing, debug mode included, which keeps its bounds checks. Anything else raises `ValueError` at import. No backend clears a new array otherwise (#386) |
| `TACK_NO_REINIT` | `tack.set_default_device` | A boolean flag (`dispatch.env_flag`): when on, `set_default_device` leaves an existing default alone. `0`, `false`, `no`, `off` and empty mean off. See above |
| `TACK_LOG_COMPILES` | `import tack` (`runtime/compile_log.py`) | A boolean flag read like `TACK_NO_REINIT`: each new variant (built, or loaded from the disk cache) writes one line to stderr naming what changed in its key since the kernel's last logged variant, its outcome and its stages' times. Calls that find their variant write nothing. See [The Kernel Cache](../core/kernel-cache.md) |
| `TACK_CACHE` | The disk cache, at the first kernel compiled | `write` (default), `read`, `bundle` (default under MPI) or `off`; also `0`, `false`, `no`, `none` for off. Any other value raises `ValueError`. See [The Kernel Cache](../core/kernel-cache.md) |
| `TACK_CACHE_SIZE` | The disk cache, at the first kernel compiled | The most the entries of every Tack version may take: bytes, a size such as `500M` or `2G` (binary units), or `unlimited`; default `1G`. Past it, a process that stores entries deletes the least recently used, at most once an hour. Any other value raises `ValueError` |
| `TACK_CACHE_DIR` | The disk cache, at the first kernel compiled | The cache directory. Default: the platform's per-user cache directory. It must belong to the user and be writable by nobody else, or it is not used (with a `RuntimeWarning`) |
Expand Down
40 changes: 40 additions & 0 deletions docs/core/kernel-cache.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,46 @@ compiles.
Debug mode is part of the key. A kernel compiled with bounds checks is a
different kernel, so switching modes never mixes the two.

## See why a call compiled

Set `TACK_LOG_COMPILES=1` before Tack is imported, and every call that makes
a new variant writes one line to stderr, saying what about the call made it
new:

```bash
TACK_LOG_COMPILES=1 python my_pipeline.py
```

```text
tack: compiled kernel=scale (pipeline.py:7) device=cpu outcome=built variants=2 frontend_ms=0.0 passes_ms=0.3 backend_ms=12.2 disk_ms=0.9 changed="a.shape[1] (baked): 32 -> 64; out.shape[1] (baked): 32 -> 64"
```

- `changed` compares the new variant with the last one logged for that
kernel on that device, part by part: an argument's type (`a: f32 array ->
f64 array`), a dimension the code bakes in (`a.shape[1] (baked)`, a row
stride), a device class's constant (`m.K (class constant): 2.0 -> 3.0`), or
the class itself (`m class: Model#1 -> Model#2`, a class defined afresh,
even under the same name). The first variant of a kernel has nothing to
compare with, and says so.
- `outcome` is `built`, or `loaded` from this cache. A loaded variant skips
Tack's passes and code generation, but Metal still compiles the stored MSL
and CUDA loads its PTX through the driver.
- `variants` is how many variants the kernel holds on the device now.
- The times are the host's: the kernel's translation (or the cache's copy of
it), Tack's passes, the backend's code generation and compilation, and
storing the entry.

A call that finds its variant writes nothing, so a quiet log means nothing is
recompiling. Run a filter twice on grids of two sizes, and only the kernels
that bake a size in show up the second time:

```text
tack: compiled kernel=_points (_flying_edges.py:415) device=cpu outcome=built variants=2 ... changed="windows.shape[0] (baked): 1024 -> 2304"
```

Changing a length that only bounds the parallel loop, or a scalar argument's
value, never makes a variant, so it never shows up.

## Keep it to a size

The entries of every Tack version share one limit, `TACK_CACHE_SIZE`. Each
Expand Down
12 changes: 10 additions & 2 deletions docs/design/specialization-and-caching.md
Original file line number Diff line number Diff line change
Expand Up @@ -579,8 +579,16 @@ To keep the number of variants down:
- **Define `@tack.device_class` classes once, at module level.** A class
defined per call is a new identity each time. Its variants are released
when it is collected, but each call still pays a cold compile.
- **Expect re-specialization when a template's array changes shape.** Its
full shape is part of the template key.
- **Expect re-specialization when a template's array changes rank or
type.** Its rank, element type and layout are in the template key; its
sizes count only where the code bakes them in, as a plain array's do.

`TACK_LOG_COMPILES=1` shows which of these is happening: one line per new
variant, naming the key parts that changed since the kernel's last logged
variant (`variant_key_parts`, below `kernel_variant_key` in
`runtime/kernel_utils.py`, which reads the real key's positions; the log is
`runtime/compile_log.py`). It runs on the slow path only. A new part of the
key needs a name there, or it is shown by its position.

Specializing on baked-in dimensions is usually worth it: a known row
stride lets LLVM and the vendor compilers fold and vectorize around it.
Expand Down
16 changes: 13 additions & 3 deletions packages/tack-core/src/tack/lang/kernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"""Tack kernel decorator — captures Python functions for compilation."""

import ast
import itertools
import struct
import textwrap
import threading
Expand Down Expand Up @@ -42,19 +43,28 @@ class _ClassToken:
collected, every specialization built for it is dropped.
"""

__slots__ = ('__weakref__', 'kernels')
__slots__ = ('__weakref__', 'kernels', 'name', 'serial')

def __init__(self):
def __init__(self, name="", serial=0):
self.kernels = weakref.WeakSet() # kernels specialized on this class
# For diagnostics only (TACK_LOG_COMPILES): the class's name and a number
# no other class of this process gets, so two classes of one name -- one
# defined per call -- are told apart. Equality stays identity.
self.name = name
self.serial = serial

def __repr__(self):
return f"{self.name}#{self.serial}"


_class_tokens = weakref.WeakKeyDictionary() # class → _ClassToken
_token_serials = itertools.count(1)


def _class_token(cls) -> _ClassToken:
token = _class_tokens.get(cls)
if token is None:
fresh = _ClassToken()
fresh = _ClassToken(cls.__qualname__, next(_token_serials))
token = _class_tokens.setdefault(cls, fresh)
if token is fresh:
weakref.finalize(cls, _retire_class, token)
Expand Down
78 changes: 78 additions & 0 deletions packages/tack-core/src/tack/runtime/compile_log.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# SPDX-FileCopyrightText: Copyright (c) Kitware Inc.
# SPDX-License-Identifier: BSD-3-Clause

"""Why a kernel call compiled: one line per new variant on stderr (``TACK_LOG_COMPILES``).

With ``TACK_LOG_COMPILES=1`` set before Tack is imported, every variant a call
builds or loads from the disk cache logs a line::

tack: compiled kernel=scale (pipeline.py:12) device=cpu outcome=built variants=2 \\
frontend_ms=0.1 passes_ms=0.4 backend_ms=6.9 disk_ms=0.0 \\
changed="a.shape[1] (baked): 32 -> 64"

- ``outcome`` is ``built`` (passes, code generation, compilation) or ``loaded``
(from the disk cache: no passes, though a backend may still compile what was
stored -- Metal its MSL, CUDA its PTX).
- ``variants`` is how many variants this kernel holds on this device now: a
class collected, or a cache dropped, makes it fewer.
- The times are the host's, flat: ``frontend_ms`` the IR (lowered, or read from
the IR caches), ``passes_ms`` the IR passes, ``backend_ms`` code generation and
compilation (or, loaded, reading and loading the stored entry, ``disk_ms`` then
0), ``disk_ms`` storing the new entry.
- ``changed`` compares the variant's key, part by named part
(`kernel_utils.variant_key_parts`), with the last variant this log saw for the
kernel on the device: not the last call, since calls that find their variant
log nothing. The first has nothing to compare with, and says so.

A call that finds its variant in memory logs nothing, nor does the warm fast path
(`kernel_utils._fast_resolve`), which this module never touches. A line that
cannot be written is dropped: the log never changes what a call does.
"""

import sys
import weakref

from tack.runtime.dispatch import as_device, env_flag

#: Whether new variants are logged: ``TACK_LOG_COMPILES``, read when Tack is
#: imported. Tests set it directly.
enabled = env_flag("TACK_LOG_COMPILES")

#: Per kernel, weakly, the last logged variant's parts on each device (by name):
#: strings only, so the log keeps no argument, class, function or IR alive.
_last = weakref.WeakKeyDictionary()


def _where(kernel) -> str:
code = getattr(getattr(kernel, "func", None), "__code__", None)
if code is None:
return ""
return f" ({code.co_filename.rsplit('/', 1)[-1]}:{code.co_firstlineno})"


def _changes(before, after) -> str:
if before is None:
return "first variant logged for this kernel on this device"
changed = [f"{name}: {before[name]} -> {after[name]}"
for name in after if name in before and before[name] != after[name]]
changed += [f"{name}: (none) -> {after[name]}" for name in after if name not in before]
changed += [f"{name}: {before[name]} -> (none)" for name in before if name not in after]
return "; ".join(changed) or "no part of the key (a variant dropped and made again)"


def logged(kernel, backend, parts, outcome, variants, times, debug=False):
"""Write the line for a new variant of ``kernel`` on ``backend``: ``parts`` its
key's named parts, ``outcome`` ``built`` or ``loaded``, ``variants`` the
kernel's count on the device, ``times`` ``{stage: seconds}``."""
try:
device = str(as_device(backend)) # "cpu", "cuda:0": tack.device's spelling
per_device = _last.setdefault(kernel, {})
before = per_device.get(device)
per_device[device] = parts
stages = " ".join(f"{stage}_ms={seconds * 1e3:.1f}" for stage, seconds in times.items())
line = (f"tack: compiled kernel={kernel.name}{_where(kernel)} device={device} "
f"outcome={outcome}{' debug=1' if debug else ''} variants={variants} "
f"{stages} changed=\"{_changes(before, parts)}\"\n")
sys.stderr.write(line)
except Exception: # never let the log break a call
pass
Loading
Loading