diff --git a/CLAUDE.md b/CLAUDE.md index b4df98d3..7a2144c4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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. diff --git a/changelog.d/compile-log.md b/changelog.d/compile-log.md new file mode 100644 index 00000000..ea110967 --- /dev/null +++ b/changelog.d/compile-log.md @@ -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). diff --git a/docs/contracts/runtime-api.md b/docs/contracts/runtime-api.md index d91b8fc5..68f38829 100644 --- a/docs/contracts/runtime-api.md +++ b/docs/contracts/runtime-api.md @@ -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`) | diff --git a/docs/core/kernel-cache.md b/docs/core/kernel-cache.md index 9a5e5571..370f2264 100644 --- a/docs/core/kernel-cache.md +++ b/docs/core/kernel-cache.md @@ -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 diff --git a/docs/design/specialization-and-caching.md b/docs/design/specialization-and-caching.md index e7f0021b..269ad40d 100644 --- a/docs/design/specialization-and-caching.md +++ b/docs/design/specialization-and-caching.md @@ -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. diff --git a/packages/tack-core/src/tack/lang/kernel.py b/packages/tack-core/src/tack/lang/kernel.py index c5b469d8..9c9fefb4 100644 --- a/packages/tack-core/src/tack/lang/kernel.py +++ b/packages/tack-core/src/tack/lang/kernel.py @@ -4,6 +4,7 @@ """Tack kernel decorator — captures Python functions for compilation.""" import ast +import itertools import struct import textwrap import threading @@ -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) diff --git a/packages/tack-core/src/tack/runtime/compile_log.py b/packages/tack-core/src/tack/runtime/compile_log.py new file mode 100644 index 00000000..7a65e90a --- /dev/null +++ b/packages/tack-core/src/tack/runtime/compile_log.py @@ -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 diff --git a/packages/tack-core/src/tack/runtime/kernel_utils.py b/packages/tack-core/src/tack/runtime/kernel_utils.py index fe7395a0..8c8ad723 100644 --- a/packages/tack-core/src/tack/runtime/kernel_utils.py +++ b/packages/tack-core/src/tack/runtime/kernel_utils.py @@ -26,6 +26,7 @@ import struct import threading +import time import weakref import numpy as np @@ -42,7 +43,7 @@ check_workgroup_participation, ) from tack.lang.workgroup_support import check_workgroup_support -from tack.runtime import debug_bounds, dispatch +from tack.runtime import compile_log, debug_bounds, dispatch def as_address(ptr) -> int | None: @@ -160,6 +161,58 @@ def kernel_variant_key(ir_func, kernel, vector_arrays, template_args, return (param_sig, vec_sig, tmpl_key, shape_sig, disjoint) +def variant_key_parts(key, probe, template, template_args) -> dict: + """``kernel_variant_key``'s ``key`` as named parts, ``{name: value}``, each value + a short string: what a compile log compares between two variants of a kernel. + + It reads the key's own positions, never the arguments again, so it cannot say + something the key does not: the parameters' types and kinds (``probe``'s + parameters, in the key's order), the vector widths, the template part (each + template's class, class constants, arrays' types and ranks, runtime scalars, + function-valued attributes and nested classes), the dimensions the code bakes + in (``ir_shape_deps(template)``, in ``shape_sig``'s order) and the disjoint + flag. Kept beside ``kernel_variant_key``, which it must follow: a part it does + not know is named by its position, not guessed at.""" + param_sig, vec_sig, tmpl_key, shape_sig, disjoint = key + parts = {} + for p, (annotation, is_array, is_texture, texture_shape) in zip(probe.params, param_sig): + kind = ("texture" if is_texture else "array" if is_array + else "scalar" if is_array is not None else "untyped") + name = getattr(annotation, "name", None) or str(annotation) + parts[p.name] = f"{name} {kind}" + (f" {texture_shape}" if texture_shape else "") + for name, width in vec_sig: + parts[f"{name} components"] = str(width) + names = {idx: name for idx, (name, _) in (template_args or {}).items()} + for part in tmpl_key: + label = part[0] + if label == "vec": + continue # vec_sig named them + if label.startswith("tmpl_") and len(part) == 7: + arg = names.get(int(label[5:]), label) + token, constants, arrays, runtime, funcs, nested = part[1:] + parts[f"{arg} class"] = repr(token) + for k, kind, value in constants: + parts[f"{arg}.{k} (class constant)"] = repr(value if kind is not float + else struct.unpack("!d", value)[0]) + for k, dtype, rank, width, matrix, layout in arrays: + parts[f"{arg}.{k} (array)"] = (f"{getattr(dtype, 'name', dtype)} rank {rank}" + + (f" width {width}" if width else "") + + (f" matrix {matrix}" if matrix else "") + + (f" {layout}" if layout != "aos" else "")) + parts[f"{arg} runtime scalars"] = ", ".join(runtime) + for k, func in funcs: + parts[f"{arg}.{k} (function)"] = getattr(func, "__qualname__", repr(func)) + for path, token in nested: + parts[f"{arg}.{'.'.join(path) if isinstance(path, tuple) else path} class"] = \ + repr(token) + else: + parts[f"template part {label}"] = repr(part[1:]) + for (name, dim), size in zip(ir_shape_deps(template), shape_sig): + parts[f"{name}.shape[{dim}] (baked)"] = str(size) + parts["arrays disjoint"] = str(bool(disjoint)) + return parts + + def _static_array_aliases(ir_func) -> dict: """Map each alias name to the array name it ultimately refers to. @@ -620,6 +673,9 @@ def _resolve_variant(backend, kernel, args, kwargs, build, store_texture_shapes, debug = dispatch._debug if debug: debug_bounds.check() # a launch that came without a check + # TACK_LOG_COMPILES: the stages' times, taken only while it is on. + log = compile_log.enabled + started = time.perf_counter() if log else 0.0 # The fast path (`_fast_resolve`) ran before this, outside the template # scope; this is the slow path, which records what it resolves for it. @@ -646,6 +702,7 @@ def _resolve_variant(backend, kernel, args, kwargs, build, store_texture_shapes, ).functions[0] if debug: effective_args = debug_bounds.hidden_args(backend, template, effective_args) + times = {"frontend": time.perf_counter() - started} if log else None check_workgroup_support( template, supports_workgroups=backend.supports_workgroups, @@ -673,48 +730,35 @@ def _resolve_variant(backend, kernel, args, kwargs, build, store_texture_shapes, from tack.runtime import disk_cache disk_key = disk_cache.variant_key(backend, template, probe, vector_arrays, shape_sig, disjoint) + loading = time.perf_counter() if log else 0.0 variant = _stored_variant(backend, disk_key, template, effective_args) if variant is not None: slot[key] = variant + if log: + times.update(passes=0.0, backend=time.perf_counter() - loading, disk=0.0) + compile_log.logged(kernel, backend, + variant_key_parts(key, probe, template, template_args), + "loaded", len(slot), times, debug) if variant is None: - from tack.lang.ir_optimize import optimize_ir - from tack.lang.ir_resolve import resolve_ir - from tack.lang.ir_verify import verify_stage - - ir_func = clone_ir(template) - resolve_ir(ir_func, name_to_array) - verify_stage(ir_func, 'resolved') - infer_param_types(ir_func, effective_args) - store_texture_shapes(ir_func, effective_args) - verify_stage(ir_func, 'inferred') - check_dispatch_types(ir_func, effective_args, - supported_dtypes=backend.supported_dtypes, - backend_name=backend.label) - _localize_outer_scalars(ir_func) - verify_stage(ir_func, 'localized') - atomic_targets = check_atomic_support( - ir_func, backend_name=backend.name, - supported_dtypes=backend.supported_atomic_dtypes, - ) - check_atomic_alignment(ir_func.name, atomic_targets, effective_args) - full_groups = (backend.supports_workgroups and - check_workgroup_participation(ir_func)) - if full_groups: - check_workgroup_launch(ir_func.name, _get_loop_range(ir_func, effective_args), - backend_label=backend.label) - optimize_ir(ir_func) - verify_stage(ir_func, 'optimized') - ir_func.disjoint_arrays = disjoint - variant = KernelVariant(ir_func, build(ir_func, effective_args), - requires_full_workgroups=full_groups, - atomic_targets=atomic_targets, - written_arrays=_written_array_args( - template, effective_args), - has_textures=any(isinstance(a, Texture3D) - for a in effective_args)) + try: + variant = _built_variant(template, name_to_array, effective_args, + store_texture_shapes, backend, disjoint, build, times) + except BaseException: + if log: + compile_log.logged(kernel, backend, + variant_key_parts(key, probe, template, template_args), + f"failed-in-{'backend' if 'passes' in times else 'passes'}", + len(slot), times, debug) + raise slot[key] = variant + mark = time.perf_counter() if log else 0.0 _store_variant(backend, disk_key, variant) - variant.ir = _launch_skeleton(ir_func) + variant.ir = _launch_skeleton(variant.ir) + if log: + times["disk"] = time.perf_counter() - mark + compile_log.logged(kernel, backend, + variant_key_parts(key, probe, template, template_args), + "built", len(slot), times, debug) elif variant.requires_full_workgroups: check_workgroup_launch(variant.ir.name, _get_loop_range(variant.ir, effective_args), backend_label=backend.label) @@ -735,6 +779,53 @@ def _resolve_variant(backend, kernel, args, kwargs, build, store_texture_shapes, return variant, effective_args +def _built_variant(template, name_to_array, effective_args, store_texture_shapes, backend, + disjoint, build, times): + """A new variant: the IR passes on a copy of ``template``, then the backend's + ``build`` (code generation and compilation). ``times``, where a compile log + is on, gets the two stages' durations.""" + from tack.lang.ir_optimize import optimize_ir + from tack.lang.ir_resolve import resolve_ir + from tack.lang.ir_verify import verify_stage + + started = time.perf_counter() if times is not None else 0.0 + ir_func = clone_ir(template) + resolve_ir(ir_func, name_to_array) + verify_stage(ir_func, 'resolved') + infer_param_types(ir_func, effective_args) + store_texture_shapes(ir_func, effective_args) + verify_stage(ir_func, 'inferred') + check_dispatch_types(ir_func, effective_args, + supported_dtypes=backend.supported_dtypes, + backend_name=backend.label) + _localize_outer_scalars(ir_func) + verify_stage(ir_func, 'localized') + atomic_targets = check_atomic_support( + ir_func, backend_name=backend.name, + supported_dtypes=backend.supported_atomic_dtypes, + ) + check_atomic_alignment(ir_func.name, atomic_targets, effective_args) + full_groups = (backend.supports_workgroups and + check_workgroup_participation(ir_func)) + if full_groups: + check_workgroup_launch(ir_func.name, _get_loop_range(ir_func, effective_args), + backend_label=backend.label) + optimize_ir(ir_func) + verify_stage(ir_func, 'optimized') + ir_func.disjoint_arrays = disjoint + if times is not None: + built = time.perf_counter() + times["passes"] = built - started + payload = build(ir_func, effective_args) + if times is not None: + times["backend"] = time.perf_counter() - built + return KernelVariant(ir_func, payload, + requires_full_workgroups=full_groups, + atomic_targets=atomic_targets, + written_arrays=_written_array_args(template, effective_args), + has_textures=any(isinstance(a, Texture3D) for a in effective_args)) + + def _stored_variant(backend, disk_key, template, effective_args): """The variant a previous process compiled for this call, or None. diff --git a/packages/tack-core/tests/test_compile_log.py b/packages/tack-core/tests/test_compile_log.py new file mode 100644 index 00000000..ea65f7fe --- /dev/null +++ b/packages/tack-core/tests/test_compile_log.py @@ -0,0 +1,260 @@ +# SPDX-FileCopyrightText: Copyright (c) Kitware Inc. +# SPDX-License-Identifier: BSD-3-Clause + +"""``TACK_LOG_COMPILES``: one stderr line per new variant, naming what changed in its +key since the last one logged (`kernel_utils.variant_key_parts`), its outcome and +its stages' times. Calls that find their variant log nothing, the warm fast path +never reaches the log, and the log keeps nothing alive.""" + +import gc +import os +import subprocess +import sys +import textwrap +import weakref + +import numpy as np +import pytest + +import tack +from tack.runtime import compile_log, dispatch +from tack.runtime import kernel_utils as ku + +pytestmark = pytest.mark.quick + + +@pytest.fixture +def log(monkeypatch, capsys, no_debug): + """The log on, and a function giving the lines written since the last call.""" + monkeypatch.setattr(compile_log, "enabled", True) + + def lines(): + return [line for line in capsys.readouterr().err.splitlines() + if line.startswith("tack: compiled")] + return lines + + +def _changed(line): + return line.split('changed="', 1)[1].rstrip('"') + + +def _field(line, name): + return next(part.split("=", 1)[1] for part in line.split() if part.startswith(name + "=")) + + +def test_a_baked_stride_is_named_and_a_launch_length_or_scalar_is_not(log): + @tack.kernel + def scale(a, out, s): + for i in range(a.shape[0]): + for j in range(a.shape[1]): + out[i, j] = a[i, j] * s + + def call(shape, s, dtype=np.float32): + a = tack.array(np.ones(shape, dtype)) + scale(a, tack.empty(shape, a.dtype), s) + + call((4, 32), 2.0) + first = log() + assert len(first) == 1 and "first variant" in _changed(first[0]) + assert _field(first[0], "outcome") == "built" and _field(first[0], "variants") == "1" + assert _field(first[0], "device") == "cpu" + call((8, 32), 3.0) # the launch length and a scalar: no variant + assert log() == [] + call((4, 64), 2.0) + line, = log() + assert _changed(line) == "a.shape[1] (baked): 32 -> 64; out.shape[1] (baked): 32 -> 64" + assert _field(line, "variants") == "2" + for stage in ("frontend_ms", "passes_ms", "backend_ms", "disk_ms"): + assert float(_field(line, stage)) >= 0.0 + call((4, 64), 2.0, np.float64) + line, = log() + assert "a: f32 array -> f64 array" in _changed(line) + assert "s: f32 scalar -> f64 scalar" in _changed(line) + + +def _model(gain): + @tack.device_class + class Model: + K = gain + + def __init__(self, x): + self.x = x + + @tack.func + def get(self, i): + return self.x[i] * self.K + return Model + + +@tack.kernel +def _apply(m, out): + for i in range(out.shape[0]): + out[i] = m.get(i) + + +def test_a_class_constant_and_a_class_defined_afresh_are_named(log): + x = tack.array(np.ones(8, np.float32)) + out = tack.empty((8,), tack.f32) + model = _model(2.0) + _apply(model(x), out) + log() + model.K = 3.0 + _apply(model(x), out) + line, = log() + assert _changed(line) == "m.K (class constant): 2.0 -> 3.0" + again = _model(3.0) # the same name, another class + _apply(again(x), out) + line, = log() + before, after = _changed(line).split(": ", 1)[1].split(" -> ") + assert before.startswith("_model..Model#") and after.startswith("_model..Model#") + assert before != after + + +def test_a_variant_found_on_the_slow_path_logs_nothing(log): + """Debug mode resolves every call on the slow path; the variant it finds there + the second time is not new, and logs no line.""" + @tack.kernel + def double(a): + for i in range(a.shape[0]): + a[i] = a[i] * 2.0 + + a = tack.array(np.ones(4, np.float32)) + tack.set_debug(True) + try: + double(a) + first = log() + double(a) + assert log() == [] + finally: + tack.set_debug(False) + assert len(first) == 1 and _field(first[0], "debug") == "1" + + +def test_the_warm_fast_path_never_reaches_the_log(log, monkeypatch): + @tack.kernel + def add(a, b): + for i in range(a.shape[0]): + a[i] = a[i] + b[i] + + a = tack.array(np.ones(4, np.float32)) + b = tack.array(np.ones(4, np.float32)) + add(a, b) + add(a, b) # the fast path records it + + def refuse(*args, **kwargs): + raise AssertionError("a warm call reached the compile log") + + for on in (True, False): + monkeypatch.setattr(compile_log, "enabled", on) + monkeypatch.setattr(compile_log, "logged", refuse) + monkeypatch.setattr(ku, "variant_key_parts", refuse) + for _ in range(3): + add(a, b) + np.testing.assert_array_equal(a.numpy(), np.full(4, 9.0)) # 1 + 8 additions + + +def test_off_it_writes_nothing(monkeypatch, capsys): + monkeypatch.setattr(compile_log, "enabled", False) + + @tack.kernel + def fill(a): + for i in range(a.shape[0]): + a[i] = 1.0 + + fill(tack.empty((4,), tack.f32)) + assert "tack: compiled" not in capsys.readouterr().err + + +def test_a_failed_build_is_logged_and_its_error_kept(log, monkeypatch): + backend = dispatch.get_backend() + + def broken(ir_func, effective_args): + raise RuntimeError("the backend refused") + + monkeypatch.setattr(backend, "_build_variant", broken) + + @tack.kernel + def fill(a): + for i in range(a.shape[0]): + a[i] = 1.0 + + with pytest.raises(Exception, match="the backend refused"): + fill(tack.empty((4,), tack.f32)) + line, = log() + assert _field(line, "outcome") == "failed-in-backend" + + +def test_the_parts_name_every_position_of_the_key(log): + """Every parameter, vector width, template part and baked dimension of the real + key has a name, and no part is guessed: the names follow the key's positions.""" + captured = {} + real = ku.variant_key_parts + + def keep(key, probe, template, template_args): + parts = real(key, probe, template, template_args) + captured.update(key=key, probe=probe, template=template, parts=parts) + return parts + + ku_parts = pytest.MonkeyPatch() + ku_parts.setattr(ku, "variant_key_parts", keep) + try: + x = tack.array(np.ones((8, 3), np.float32)) + v = tack.empty((8,), tack.vec3()) + out = tack.empty((8,), tack.f32) + + @tack.kernel + def mixed(m, v, out): + for i in range(out.shape[0]): + out[i] = m.get(i) + v[i][0] + + mixed(_model(2.0)(x), v, out) + finally: + ku_parts.undo() + key, probe, parts = captured["key"], captured["probe"], captured["parts"] + param_sig, vec_sig, tmpl_key, shape_sig, _ = key + assert len(param_sig) == len(probe.params) + assert all(p.name in parts for p in probe.params) + assert all(f"{name} components" in parts for name, _ in vec_sig) + assert len(shape_sig) == len(ku.ir_shape_deps(captured["template"])) + assert "m class" in parts and "m.K (class constant)" in parts + assert not any(name.startswith("template part") for name in parts) + assert parts["arrays disjoint"] in ("True", "False") + + +def test_the_log_keeps_no_class_alive(log): + x = tack.array(np.ones(8, np.float32)) + out = tack.empty((8,), tack.f32) + model = _model(5.0) + _apply(model(x), out) + assert log() + gone = weakref.ref(model) + del model + gc.collect() + assert gone() is None + + +def test_the_environment_switches_it_on_and_a_stored_variant_is_loaded(tmp_path): + """``TACK_LOG_COMPILES=1`` before Tack is imported; a second process finds the + variant on disk and says it loaded it.""" + script = tmp_path / "run.py" + script.write_text(textwrap.dedent(""" + import numpy as np + import tack + + @tack.kernel + def twice(a): + for i in range(a.shape[0]): + a[i] = a[i] * 2.0 + + twice(tack.array(np.ones(4, np.float32))) + """)) + env = dict(os.environ, TACK_LOG_COMPILES="1", TACK_CACHE="write", + TACK_CACHE_DIR=str(tmp_path / "cache")) + env.pop("TACK_DEBUG", None) + outcomes = [] + for _ in range(2): + done = subprocess.run([sys.executable, str(script)], env=env, capture_output=True, + text=True, timeout=300, check=True) + lines = [line for line in done.stderr.splitlines() if line.startswith("tack: compiled")] + outcomes.append([_field(line, "outcome") for line in lines]) + assert outcomes == [["built"], ["loaded"]]