Skip to content

ordito.precompile

Ahead-of-time kernel builds: fill Warp's kernel cache with every kernel ordito launches.

Warp compiles a module of kernels the first time one of them launches, and keeps the result in its kernel cache, keyed by the module's source and options, the launch's block_dim and the GPU architecture. A process starting from an empty cache pays those builds inside its first calls, seconds to minutes in all. precompile pays them ahead of time, in parallel and without running any workload, so a container image or a CI job can ship a warm cache:

python -m ordito.precompile --arch 86,89 --cache-dir /opt/warp-cache --jobs 16

and the processes that use it run with WARP_CACHE_PATH=/opt/warp-cache.

What is built is what kernel_variants lists: every module of ordito's kernels at every launch width ordito uses, the kernels ordito creates on first use, and the Warp modules (sparse, geometry) importing ordito creates. The cache is built against the installed Warp and ordito and holds only what they would compile, so an upgrade of either needs a new build. A kernel that only a caller's input creates (a dtype conversion ordito itself never makes) still compiles on first use.

Targets:

  • arch names CUDA compute capabilities (86 for sm_86). Compiling needs no GPU, so a build machine without one can serve any architecture. A cache entry serves its exact architecture only.
  • Without arch, the build is for the GPUs of the machine it runs on, in the format Warp would load on them; with none, for the CPU alone.
  • cpu (on by default; --no-cpu turns it off) adds the CPU device, which a GPU process also loads for host-side work. Warp compiles CPU code for the instruction set of the machine it runs on and keys the cache entry by it, so the objects serve only machines of that CPU type; on another, those modules compile on first use as they would without the cache.

From the command line, python -m ordito.precompile --help lists the options; --arch takes a comma-separated list and may repeat.

Classes:

Name Description
PrecompileReport

What a precompile call built, found built and failed on.

Functions:

Name Description
precompile

Compile every kernel ordito launches into Warp's kernel cache, without running any of them.

kernel_variants

List every Warp module ordito launches, with the CUDA launch widths it is built at.

PrecompileReport dataclass

PrecompileReport(
    targets: tuple[str, ...],
    cache_dir: str,
    built: int,
    cached: int,
    failed: tuple[tuple[str, str, str], ...],
)

What a precompile call built, found built and failed on.

Attributes:

Name Type Description
targets tuple[str, ...]

The targets built for: "sm_<arch>" ("sm_<arch>.ptx" for PTX) per CUDA architecture, and "cpu".

cache_dir str

The kernel cache directory written, Warp's version included.

built int

Number of module builds this call compiled.

cached int

Number of module builds already in the cache, left as they were.

failed tuple[tuple[str, str, str], ...]

(module, target, error) for each build that raised.

Examples:

import ordito as od

report = od.precompile.precompile()
print(report.targets[-1])  # cpu
print(report.failed)  # ()

targets instance-attribute

targets: tuple[str, ...]

cache_dir instance-attribute

cache_dir: str

built instance-attribute

built: int

cached instance-attribute

cached: int

failed instance-attribute

failed: tuple[tuple[str, str, str], ...]

precompile

precompile(
    arch: int | Sequence[int] | None = None,
    *,
    cpu: bool = True,
    cache_dir: str | PathLike[str] | None = None,
    jobs: int | None = None,
) -> PrecompileReport

Compile every kernel ordito launches into Warp's kernel cache, without running any of them.

Each worker process imports ordito's kernels and compiles its share of kernel_variants for every target; a build already in the cache is left as it is, so a second call compiles nothing. Progress and the targets chosen are logged on the ordito.precompile logger at INFO.

Parameters:

Name Type Description Default
arch int | Sequence[int] | None

CUDA compute capabilities to build for (86 for sm_86); no GPU is needed. None builds for the GPUs of this machine, or for none when it has none.

None
cpu bool

Also build for the CPU device, for this machine's instruction set. A process on a GPU loads some CPU modules too, so leave it on unless no process using the cache runs on this CPU type.

True
cache_dir str | PathLike[str] | None

Kernel cache directory, the value the processes using it set as WARP_CACHE_PATH (Warp adds its version below it). None is the cache Warp uses by default.

None
jobs int | None

Number of worker processes. None is one per CPU core.

None

Returns:

Type Description
PrecompileReport

The targets, the cache directory and the number of builds compiled, found and failed.

Raises:

Type Description
ValueError

If arch is None, cpu is False and this machine has no GPU (there would be nothing to build), if an arch is below 50, or if jobs is below 1.

See Also

kernel_variants : The modules and launch widths built.

Examples:

import ordito as od

report = od.precompile.precompile()
print(report.built + report.cached > 100)  # True
Source code in ordito/precompile.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def precompile(
    arch: int | Sequence[int] | None = None,
    *,
    cpu: bool = True,
    cache_dir: str | os.PathLike[str] | None = None,
    jobs: int | None = None,
) -> PrecompileReport:
    """
    Compile every kernel ordito launches into Warp's kernel cache, without running any of them.

    Each worker process imports ordito's kernels and compiles its share of
    [`kernel_variants`][ordito.precompile.kernel_variants] for every target; a build already in
    the cache is left as it is, so a second call compiles nothing. Progress and the targets chosen
    are logged on the ``ordito.precompile`` logger at ``INFO``.

    Parameters
    ----------
    arch
        CUDA compute capabilities to build for (``86`` for ``sm_86``); no GPU is needed.
        ``None`` builds for the GPUs of this machine, or for none when it has none.
    cpu
        Also build for the CPU device, for this machine's instruction set. A process on a GPU
        loads some CPU modules too, so leave it on unless no process using the cache runs on this
        CPU type.
    cache_dir
        Kernel cache directory, the value the processes using it set as ``WARP_CACHE_PATH``
        (Warp adds its version below it). ``None`` is the cache Warp uses by default.
    jobs
        Number of worker processes. ``None`` is one per CPU core.

    Returns
    -------
    PrecompileReport
        The targets, the cache directory and the number of builds compiled, found and failed.

    Raises
    ------
    ValueError
        If ``arch`` is ``None``, ``cpu`` is ``False`` and this machine has no GPU (there would be
        nothing to build), if an ``arch`` is below ``50``, or if ``jobs`` is below ``1``.

    See Also
    --------
    kernel_variants : The modules and launch widths built.

    Examples
    --------
    ```python
    import ordito as od

    report = od.precompile.precompile()
    print(report.built + report.cached > 100)  # True
    ```
    """
    if jobs is not None and jobs < 1:
        raise ValueError(f"jobs must be at least 1, got {jobs}")
    targets = _targets(arch, cpu)
    workers = jobs if jobs is not None else os.cpu_count() or 1
    started = time.perf_counter()
    context = multiprocessing.get_context("spawn")
    root = os.fspath(cache_dir) if cache_dir is not None else None
    with concurrent.futures.ProcessPoolExecutor(
        workers, mp_context=context, initializer=_start_worker, initargs=(root,)
    ) as pool:
        resolved_cache, variants, sizes = pool.submit(_worker_variants).result()
        _LOGGER.info(
            "precompile: %d modules, %d launch widths, for %s into %s with %d workers",
            len(variants),
            sum(len(widths) for widths in variants.values()),
            ", ".join(target.label for target in targets),
            resolved_cache,
            workers,
        )
        # Largest modules first: one module is one build, and the largest takes a minute, so it
        # sets the wall time unless it starts at once.
        builds = [
            (name, target, block_dim)
            for name in sorted(variants, key=lambda name: -sizes[name])
            for target in targets
            for block_dim in (variants[name] if target.arch is not None else (1,))
        ]
        futures = {
            pool.submit(_build, name, target.arch, target.use_ptx, block_dim): (name, target)
            for name, target, block_dim in builds
        }
        built = cached = 0
        failed: list[tuple[str, str, str]] = []
        step = max(len(futures) // 10, 1)
        for done, future in enumerate(concurrent.futures.as_completed(futures), start=1):
            name, target = futures[future]
            compiled, error = future.result()
            if error is not None:
                failed.append((name, target.label, error))
                _LOGGER.warning("precompile: %s for %s failed: %s", name, target.label, error)
            elif compiled:
                built += 1
            else:
                cached += 1
            if done % step == 0 or done == len(futures):
                _LOGGER.info("precompile: %d/%d builds done", done, len(futures))
    _LOGGER.info(
        "precompile: %d built, %d already cached, %d failed in %.0f s",
        built,
        cached,
        len(failed),
        time.perf_counter() - started,
    )
    return PrecompileReport(
        targets=tuple(target.label for target in targets),
        cache_dir=resolved_cache,
        built=built,
        cached=cached,
        failed=tuple(sorted(failed)),
    )

kernel_variants

kernel_variants() -> dict[str, tuple[int, ...]]

List every Warp module ordito launches, with the CUDA launch widths it is built at.

Imports every ordito module and creates the kernels ordito otherwise makes on first use. On the CPU device Warp loads every module at width 1 whatever the launch asks, so a CPU build is one per module.

Returns:

Type Description
dict of str to tuple of int

Warp module name to the ascending block_dims a CUDA launch loads it at, its default included. The Warp modules importing ordito creates (sparse, geometry) are listed too.

See Also

precompile : Compile them.

Examples:

import ordito as od

variants = od.precompile.kernel_variants()
print(256 in variants["ordito.kernels.reduce"])  # True
Source code in ordito/precompile.py
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
def kernel_variants() -> dict[str, tuple[int, ...]]:
    """
    List every Warp module ordito launches, with the CUDA launch widths it is built at.

    Imports every ordito module and creates the kernels ordito otherwise makes on first use. On
    the CPU device Warp loads every module at width 1 whatever the launch asks, so a CPU build is
    one per module.

    Returns
    -------
    dict of str to tuple of int
        Warp module name to the ascending ``block_dim``s a CUDA launch loads it at, its default
        included. The Warp modules importing ordito creates (sparse, geometry) are listed too.

    See Also
    --------
    precompile : Compile them.

    Examples
    --------
    ```python
    import ordito as od

    variants = od.precompile.kernel_variants()
    print(256 in variants["ordito.kernels.reduce"])  # True
    ```
    """
    import ordito
    import ordito.kernels
    from ordito.kernels import array as kernel_array

    # The wrappers too: a wrapper declares the launch widths it owns.
    for info in pkgutil.walk_packages(ordito.__path__, "ordito."):
        importlib.import_module(info.name)
    for build in kernel_array.LAZY_KERNEL_BUILDS:
        build()
    variants: dict[str, tuple[int, ...]] = {}
    for name, module in _warp_modules().items():
        if name in ordito.kernels.WARP_MODULES_BEFORE_ORDITO or not _compilable(module):
            continue
        widths = {int(module.options["block_dim"])}
        widths |= kernel_array.LAUNCH_BLOCK_DIMS.get(name, set())
        variants[name] = tuple(sorted(widths))
    return variants