Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
156 commits
Select commit Hold shift + click to select a range
7039e22
Implemented Julia kernel tuning functionality
fjwillemsen Nov 26, 2025
d73379e
Implemented gathering device information from Julia
fjwillemsen Nov 26, 2025
637ce02
Improved Julia support
fjwillemsen Dec 7, 2025
54f9764
Modified the kernel launch structure for Julia kernels, added JIT war…
fjwillemsen Dec 8, 2025
28108c7
Implement pointing to kernel file for Julia
fjwillemsen Dec 8, 2025
9df9c77
Added backend test for Julia
fjwillemsen Dec 9, 2025
634b368
Small fixes
fjwillemsen Dec 9, 2025
f11fc30
Improved Julia kernel launch for general case
fjwillemsen Dec 9, 2025
9d9e428
Generalized and added ndrange passthrough
fjwillemsen Dec 9, 2025
f3c2924
Wrote tests for julia backend
fjwillemsen Dec 10, 2025
92179ba
Implemented vector add test for Julia backend
fjwillemsen Dec 10, 2025
0a32847
Automatic conversion of Julia vectors where necessary
fjwillemsen Dec 10, 2025
3e16e38
Implemented backend-agnostic initialization of Julia
fjwillemsen Dec 11, 2025
fadf672
Implemented working backend-agnostic runs for Julia
fjwillemsen Dec 12, 2025
faba09d
Implemented Metal-specific precise GPU timers
fjwillemsen Dec 12, 2025
103ec80
Completed implementation of backend-agnostic generalization
fjwillemsen Dec 12, 2025
e853125
Fixed CUDA recordings to backend agnostic
fjwillemsen Dec 12, 2025
2c2a376
Fixed timings for Metal Julia
fjwillemsen Dec 12, 2025
12868b6
Merge branch 'julia' of https://github.com/KernelTuner/kernel_tuner i…
fjwillemsen Dec 12, 2025
0b0aa32
Implemented automatic detection of device availability in Julia backe…
fjwillemsen Dec 12, 2025
6074932
Automatic conversion of restrictions from Julia vectors
fjwillemsen Dec 12, 2025
8a102e2
Handle tunable parameters from Julia while preserving their order
fjwillemsen Dec 13, 2025
3d05082
Implemented error capture and handling for Julia backend
fjwillemsen Dec 13, 2025
32de3fd
Merge remote-tracking branch 'origin/master' into julia
fjwillemsen Jan 8, 2026
23f9d2d
Merge branch 'master' into julia
fjwillemsen Jan 16, 2026
5e01a1a
Improved automatic detection of Julia backend in test
fjwillemsen Jan 20, 2026
b6d0eaf
Added Julia kernel launch error handling
fjwillemsen Jan 21, 2026
89abfa6
Fix for CUDA 13 event streams
fjwillemsen Jan 29, 2026
88cf3df
In verbose mode, Julia launch errors are output as warnings
fjwillemsen Jan 29, 2026
1cb1633
Updated Julia functions test
fjwillemsen Jan 29, 2026
791a9ef
Merge with upstream
fjwillemsen Jan 29, 2026
d9ce98c
Implemented automatic backend platform detection for Julia
fjwillemsen Jan 29, 2026
3904bb2
Simplified GPU array conversion
fjwillemsen Jan 29, 2026
af3c679
Merge with master
fjwillemsen Feb 2, 2026
7199d03
Improved automatic detection of Julia backends available
fjwillemsen Feb 2, 2026
3b7d891
Implemented Poetry and Nox installation for Julia compatabilitu
fjwillemsen Feb 2, 2026
9155447
Implemented Nox and JuliaCall compatibility for automatically install…
fjwillemsen Feb 3, 2026
003968e
Updated linting settings and applied to changed files
fjwillemsen Feb 4, 2026
6eb5397
Fixed some linting issues
fjwillemsen Feb 4, 2026
78b1720
Disabled reusing nox environments
fjwillemsen Feb 4, 2026
9dc9bc3
Improved tests, PyCUDA compatibility and updated dependencies
fjwillemsen Feb 5, 2026
bde2913
Added conversion of and interaction with Julia objects
fjwillemsen Feb 8, 2026
733ce2d
Reduced edgeitems to prevent BlockingIOError
fjwillemsen Feb 8, 2026
8a7b5bb
Implemented Julia Device to Host and Host to Device copies, improved …
fjwillemsen Feb 9, 2026
b906fa9
Quick fix for non-Julia compatibility
fjwillemsen Feb 9, 2026
6ed180f
Fixed juliapkg to automatically find julia install
fjwillemsen Feb 26, 2026
39efc21
Merge branch 'master' into julia
fjwillemsen Feb 26, 2026
e20a607
Julia backend working for Intel GPUs
fjwillemsen Mar 5, 2026
8420eca
No Julia conversion on None inputs
fjwillemsen Mar 5, 2026
a2c393f
Merge branch 'master' into julia
fjwillemsen Mar 23, 2026
ba1e4cd
Changes to improve Intel compatibility
Mar 24, 2026
b9e614f
Merge with upstream
fjwillemsen Mar 24, 2026
e5aa602
Improved device selection for Julia
fjwillemsen Mar 24, 2026
8076ee5
Improved device selection support for CUDA and Intel platforms
fjwillemsen Mar 25, 2026
ddba6a4
Improved device selection support for CUDA and Intel platforms
fjwillemsen Mar 25, 2026
0feb054
Updated device selection for AMD
fjwillemsen Mar 25, 2026
75dc870
Extended timeout to allow Garbage Collection to complete
fjwillemsen Mar 25, 2026
dcf55b9
Removed redundant device selection logic
fjwillemsen Mar 25, 2026
493c2c9
Minor improvements to tests
fjwillemsen Mar 31, 2026
129ee93
Expanded documentation for dev environment
fjwillemsen Mar 31, 2026
08767da
Improved automatic check for Intel GPUs, improved tests
fjwillemsen Mar 31, 2026
d780b9d
Refined automatic backend check test
fjwillemsen Mar 31, 2026
5dff37c
Improved automatic detection of Julia backends in Kernel Tuner and te…
fjwillemsen Mar 31, 2026
bde773a
Added block size name augmentation to run_kernel
fjwillemsen Apr 3, 2026
36ef75c
Added synchronization detection for Julia arrays, more specific repor…
fjwillemsen Apr 4, 2026
0b33f85
Linting
fjwillemsen Apr 4, 2026
8a028be
Implemented Tunable structure for answers, improved efficiency
fjwillemsen Apr 4, 2026
f349332
Implemented nested Tunable data type
fjwillemsen Apr 4, 2026
f2ac100
Added globals for temporary arrays
fjwillemsen Apr 4, 2026
31d0390
Improved timings on AMD
fjwillemsen Apr 8, 2026
a85cd96
Improved timings on AMD
fjwillemsen Apr 8, 2026
62fba7b
Improved timings on AMD
fjwillemsen Apr 8, 2026
3250aa3
Updated AMD backend name
fjwillemsen Apr 8, 2026
f0b5b56
Updated AMD backend name
fjwillemsen Apr 8, 2026
22a51f1
Updated AMD backend name
fjwillemsen Apr 8, 2026
b258bd0
Updated AMD backend name
fjwillemsen Apr 8, 2026
3db1c8f
Added module backend string specification
fjwillemsen Apr 8, 2026
aef9aec
Adjusted AMDGPU specifications retrieval
fjwillemsen Apr 8, 2026
d4824ce
Adjusted AMD timings
fjwillemsen Apr 8, 2026
6a2026a
Updated AMD event recording
fjwillemsen Apr 8, 2026
66f5c7a
Updated AMD event record
fjwillemsen Apr 8, 2026
2c79c43
HIP event creation
fjwillemsen Apr 8, 2026
e4d9e2d
Merge branch 'julia' of https://github.com/benvanwerkhoven/kernel_tun…
fjwillemsen Apr 8, 2026
dedc822
Improved event handling for AMD
fjwillemsen Apr 8, 2026
ac32109
Much improved host-side kernel timing, Metal device name retrieval
fjwillemsen Apr 9, 2026
9a1714a
Improved CUDA and AMD GPU timings
fjwillemsen Apr 9, 2026
8dfdfad
Minor improvements to AMD GPU-side timing
fjwillemsen Apr 10, 2026
73c6331
Test for AMD GPU-side timing
fjwillemsen Apr 10, 2026
7d9cb76
Test for AMD GPU-side timing
fjwillemsen Apr 10, 2026
0cfacc0
Test for AMD GPU-side timing
fjwillemsen Apr 10, 2026
d7c8848
Test for AMD GPU-side timing
fjwillemsen Apr 10, 2026
14a5d36
Improvements for AMD and Nvidia GPU-side events
fjwillemsen Apr 10, 2026
32c1ecf
Added debug tracking
fjwillemsen Apr 13, 2026
77113f5
Added synchronize after end events
fjwillemsen Apr 17, 2026
291ddbf
Added synchronize after end events
fjwillemsen Apr 17, 2026
ee855e8
Improved timing stability
fjwillemsen Apr 17, 2026
e32703d
Moved CUDA and AMD event recording closer to kernel launch (experimen…
fjwillemsen Apr 17, 2026
b537f10
Fixed an issue with GPU-side timing events
fjwillemsen Apr 20, 2026
f873c54
Fixed an issue with GPU-side timing events
fjwillemsen Apr 20, 2026
3f7621f
Fixed an issue with GPU-side timing events for Metal
fjwillemsen Apr 20, 2026
d60dcb6
Substantially more precise Metal timing
fjwillemsen Apr 20, 2026
eacdad0
Fixed an issue with GPU-side timing events for AMD
fjwillemsen Apr 20, 2026
e001e45
Resolved unintended Metal dependency in function signature
fjwillemsen Apr 20, 2026
e1289bb
Fixed an issue with GPU-side timing events for AMD
fjwillemsen Apr 21, 2026
8a502df
Fixed an issue with GPU-side timing events AMD
fjwillemsen Apr 21, 2026
5507c0c
Resolved merge with master
fjwillemsen Apr 22, 2026
96c60fd
Added option to raise errors from Julia backend
fjwillemsen Apr 24, 2026
238932d
Improved Julia compatibility and automatic handling of conversions
fjwillemsen Jul 3, 2026
79009bd
Implemented the CPU backend for Julia
fjwillemsen Jul 22, 2026
baa7cc6
Big merge to bring up to date with main, minor improvements to tests
fjwillemsen Jul 24, 2026
7278eba
Now working with Nox
fjwillemsen Jul 27, 2026
e075ee8
Improved calculation of ndrange
fjwillemsen Aug 5, 2026
fa3f18f
Improved parameter passing structure via immutable JuliaKernel class …
fjwillemsen Aug 6, 2026
c2a7fcf
Added conversion of strategy options
fjwillemsen Aug 6, 2026
d171e13
Fix Julia undue argument list warning
fjwillemsen Aug 7, 2026
f2acd88
Restored linting in noxfile to commented
fjwillemsen Aug 10, 2026
4c204a4
Removed unused parameters from backend interface
fjwillemsen Aug 10, 2026
b1d1245
Added Julia setup to github action test
fjwillemsen Aug 10, 2026
0858f6a
Added SonarQube to project settings
fjwillemsen Aug 10, 2026
2093fbe
Fixed an issue where parameter could be None
fjwillemsen Aug 10, 2026
038ce1c
Fixed an issue with pymoo module name
fjwillemsen Aug 10, 2026
1e39e3c
Added comments to Julia warmup observer
fjwillemsen Aug 10, 2026
52836cc
Refactored to simplify
fjwillemsen Aug 10, 2026
8160ada
Refactored to simplify
fjwillemsen Aug 10, 2026
ec5add5
Various improvements to code quality
fjwillemsen Aug 10, 2026
54b4892
Much simplified _default_verify_function
fjwillemsen Aug 10, 2026
a618388
Defined Julia GPU backend names
fjwillemsen Aug 10, 2026
f1157be
Fix an issue with unitialized cupy
fjwillemsen Aug 10, 2026
972ad0e
Split Julia backend streams initialization into separate function'
fjwillemsen Aug 10, 2026
ae70d64
Split Julia backend streams initialization into separate function'
fjwillemsen Aug 10, 2026
ee59bb9
Removed duplicate nox test instantiation
fjwillemsen Aug 10, 2026
e431b36
Split Julia tests into separate CI segment to reduce compute time
fjwillemsen Aug 10, 2026
e202ea3
Rewrote various functions to reduce complexity
fjwillemsen Aug 10, 2026
f4fca35
Rewrote various functions to reduce complexity
fjwillemsen Aug 10, 2026
e072fcc
Rewrote various functions to reduce complexity
fjwillemsen Aug 10, 2026
c984b69
Updated CI test flow
fjwillemsen Aug 10, 2026
8bb9d4e
Commented not yet implemented feature
fjwillemsen Aug 10, 2026
83aab9c
Improved handling of argument checking
fjwillemsen Aug 10, 2026
f2d2df1
Enable multiple positional arguments for nox
fjwillemsen Aug 10, 2026
55f74a2
Enable multiple positional arguments for nox
fjwillemsen Aug 10, 2026
2aadbb4
Improved session specification for Nox
fjwillemsen Aug 10, 2026
ec13c6d
Switched to using JuliaPKG for managing environments, made it work wi…
fjwillemsen Aug 11, 2026
303ed27
Added julia compat specifier
fjwillemsen Aug 11, 2026
1441e97
Improved Julia compat version handling for CI and Nox
fjwillemsen Aug 11, 2026
6b9be35
Switch back to Julia 1.11 for CI tests
fjwillemsen Aug 11, 2026
98e97d8
Switch back to Julia 1.12 for CI tests
fjwillemsen Aug 11, 2026
476bce8
Consistent setting of environment variables in Nox
fjwillemsen Aug 11, 2026
14ccd8d
Testing forced resolution
fjwillemsen Aug 11, 2026
fbb0fd8
Testing forced resolution
fjwillemsen Aug 11, 2026
d3a6cdb
Testing forced deletion of old nox folder
fjwillemsen Aug 11, 2026
53443ce
Switch back to Julia 1.11 for CI tests
fjwillemsen Aug 11, 2026
4b9d757
Create registries folder in CI
fjwillemsen Aug 11, 2026
06ac66f
Create registries folder in CI
fjwillemsen Aug 11, 2026
5b7ed91
Provide more overhead for timed tests if running on a CI
fjwillemsen Aug 12, 2026
c5f82e9
Improved required directory structure creation before tests
fjwillemsen Aug 12, 2026
b4224ab
Improved required directory structure creation before tests
fjwillemsen Aug 12, 2026
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
14 changes: 12 additions & 2 deletions .github/workflows/test-python-package.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,26 @@ jobs:
os: [ubuntu-latest, macos-latest]

steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Setup Nox
uses: fjwillemsen/setup-nox2@v3.0.0
- name: Setup Poetry
uses: Gr1N/setup-poetry@v9
- run: poetry self add poetry-plugin-export
- uses: julia-actions/setup-julia@v3
with:
version: '1.11' # when changed, also see `require_julia` in noxfile.py and the Julia version in Project.toml
- name: Run tests with Nox
run: |
rm -rf .nox
pip install nox-poetry
nox -- skip-gpu github-action
nox -- skip-gpu skip-julia github-action
- name: Run Julia tests with Nox
run: |
rm -rf .nox
pip install nox-poetry
nox --session tests-3.14 -- skip-gpu github-action
# [ -d "~" ] && mkdir -p ~/.julia/registries
# - name: Upload Coverage report to CodeCov
# uses: codecov/codecov-action@v3
# with:
Expand Down
25 changes: 13 additions & 12 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=827846 to learn about workspace recommendations.
// Extension identifier format: ${publisher}.${name}. Example: vscode.csharp
// List of extensions which should be recommended for users of this workspace.
"recommendations": [
"ms-python.python",
"ms-python.black-formatter",
"charliermarsh.ruff",
"bungcip.better-toml",
"njpwerner.autodocstring",
],
// List of extensions recommended by VS Code that should not be recommended for users of this workspace.
"unwantedRecommendations": []
// See https://go.microsoft.com/fwlink/?LinkId=827846 to learn about workspace recommendations.
// Extension identifier format: ${publisher}.${name}. Example: vscode.csharp
// List of extensions which should be recommended for users of this workspace.
"recommendations": [
"ms-python.python",
"ms-python.black-formatter",
"charliermarsh.ruff",
"bungcip.better-toml",
"njpwerner.autodocstring",
"julialang.language-julia",
],
// List of extensions recommended by VS Code that should not be recommended for users of this workspace.
"unwantedRecommendations": []
}
10 changes: 6 additions & 4 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,16 @@
"black-formatter.args": [
"--config=pyproject.toml"
],
"ruff.args": [
"--config=pyproject.toml"
],
"ruff.configuration": "pyproject.toml",
"autoDocstring.docstringFormat": "google-notypes",
"esbonio.sphinx.confDir": "",
"python.testing.pytestArgs": [
"test"
],
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true,
}
"sonarlint.connectedMode.project": {
"projectKey": "KernelTuner_kernel_tuner",
"connectionId": "kerneltuner",
}
}
2 changes: 1 addition & 1 deletion CONTRIBUTING.rst
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ Before creating a pull request please ensure the following:

* You are working in an up-to-date development environment
* You are a human developer. We are not interested in purely AI generated code contributions.
* You have written unit tests to test your additions and all unit tests pass (run :bash:`nox`). If you do not have the required hardware, you can run :bash:`nox -- skip-gpu`, or :bash:`skip-cuda`, :bash:`skip-hip`, :bash:`skip-opencl`.
* You have written unit tests to test your additions and all unit tests pass (run :bash:`nox`). If you do not have the required hardware, you can run :bash:`nox -- skip-gpu`, or :bash:`skip-cuda`, :bash:`skip-hip`, :bash:`skip-opencl`, :bash:`skip-julia`.
* The examples still work and produce the same (or better) results
* An entry about the change or addition is created in :bash:`CHANGELOG.md`

Expand Down
10 changes: 6 additions & 4 deletions doc/source/dev-environment.rst
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ Steps with :bash:`sudo` access (e.g. on a local device):
* Activate the environment with :bash:`pyenv activate kerneltuner`.
* Make sure :bash:`which python` and :bash:`which pip` point to the expected Python location and version.
* Update Pip with :bash:`pip install --upgrade pip`.
#. Install the project, dependencies and extras: :bash:`poetry install --with test,docs -E cuda -E opencl -E hip`, leaving out :bash:`-E cuda`, :bash:`-E opencl` or :bash:`-E hip` if this does not apply on your system. To go all-out, use :bash:`--all-extras`
#. Install the project, dependencies and extras: :bash:`poetry install --with test,docs -E cuda -E opencl -E hip -E julia`, leaving out :bash:`-E cuda`, :bash:`-E opencl` etc. if this does not apply on your system. To go all-out, use :bash:`--all-extras`
* Depending on the environment, it may be necessary or convenient to install extra packages such as :bash:`cupy-cuda11x` / :bash:`cupy-cuda12x`, and :bash:`cuda-python`. These are currently not defined as dependencies for kernel-tuner, but can be part of tests.
* Do not forget to make sure the paths are set correctly. If you're using CUDA, the desired CUDA version should be in :bash:`$PATH`, :bash:`$LD_LIBARY_PATH` and :bash:`$CPATH`.
* Re-open the shell for changes to take effect.
Expand Down Expand Up @@ -72,8 +72,9 @@ Steps without :bash:`sudo` access (e.g. on a cluster):
#. `Install Poetry <https://python-poetry.org/docs/#installing-with-the-official-installer>`__.
* Use :bash:`curl -sSL https://install.python-poetry.org | python3 -` to install Poetry.
* Add the poetry export plugin with :bash:`poetry self add poetry-plugin-export`.
#. Install the project, dependencies and extras: :bash:`poetry install --with test,docs -E cuda -E opencl -E hip`, leaving out :bash:`-E cuda`, :bash:`-E opencl` or :bash:`-E hip` if this does not apply on your system. To go all-out, use :bash:`--all-extras`.
#. Install the project, dependencies and extras: :bash:`poetry install --with test,docs -E cuda -E opencl -E hip -E julia`, leaving out :bash:`-E cuda`, :bash:`-E opencl` etc. if this does not apply on your system. To go all-out, use :bash:`--all-extras`.
* If you run into "keyring" or other seemingly weird issues, this is a known issue with Poetry on some systems. Do: :bash:`pip install keyring`, :bash:`python3 -m keyring --disable`.
* Kernel Tuner has a dependency on Python-Constraint, which provides binaries for most systems. On some older systems, these binaries may not be compatible (on Linux usually due to an outdated LDD version, check with :bash:`ldd --version`, must be >=2.35). Without binaries, your system will try to build it yourself, so make sure build tools are available (e.g. with :bash:`module load gcc/13.2.0`).
* Depending on the environment, it may be necessary or convenient to install extra packages such as :bash:`cupy-cuda11x` / :bash:`cupy-cuda12x`, and :bash:`cuda-python`. These are currently not defined as dependencies for kernel-tuner, but can be part of tests.
* Verify that your development environment has no missing installs or updates with :bash:`poetry install --sync --dry-run --with test`.
#. Check if the environment is setup correctly by running :bash:`pytest`. All tests should pass, except if you're not on a GPU node, or one or more extras has been left out in the previous step, then these tests will skip gracefully.
Expand Down Expand Up @@ -102,9 +103,10 @@ If you do not have fully compatible hardware or environment, you can use the fol
* :bash:`nox -- skip-cuda` to skip tests involving CUDA.
* :bash:`nox -- skip-hip` to skip tests involving HIP.
* :bash:`nox -- skip-opencl` to skip tests involving OpenCL.
* :bash:`nox -- skip-gpu` to skip all tests on the GPU (the same as :bash:`nox -- skip-cuda skip-hip skip-opencl`), especially helpful if you don't have a GPU locally.
* :bash:`nox -- skip-julia` to skip tests involving Julia.
* :bash:`nox -- skip-gpu` to skip all tests on the GPU (the same as :bash:`nox -- skip-cuda skip-hip skip-opencl`), especially helpful if you don't have a GPU in your system.

Contributions you make to the Kernel Tuner should not break any of the tests even if you cannot run them locally!
Contributions you make to Kernel Tuner should not break any of the tests even if you cannot run them locally!

Running with :bash:`pytest` will test against your local Python version and PIP packages.
In this case, tests that require PyCuda and/or a CUDA capable GPU will be skipped automatically if these are not installed/present.
Expand Down
67 changes: 38 additions & 29 deletions kernel_tuner/accuracy.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,25 @@
"""Module for accuracy measurement and tunable parameters."""

import logging
import re
from collections import UserDict
from typing import Dict

import numpy as np
import logging
import re

from kernel_tuner.observers import OutputObserver


class Tunable(UserDict):
"""``Tunable`` can be used as a parameter value dependent input argument when tuning kernels."""

def __init__(self, param_key: str, arrays: Dict):
"""The ``Tunable`` object can be used as an input argument when tuning
kernels. It is a container that holds several arrays internally and
"""The ``Tunable`` object can be used as an input argument when tuning kernels.

It is a container that holds several arrays internally and
selects one array during benchmarking based on the value of a tunable parameter.

Example
Example:
-------
Consider this example::

Expand All @@ -37,6 +43,7 @@
self.param_key = param_key

def select_for_configuration(self, params):
"""Select the array for the given configuration."""
if callable(self.param_key):
option = self.param_key(params)
elif self.param_key in params:
Expand All @@ -46,13 +53,16 @@

if option not in self.data:
list = ", ".join(map(str, self.data.keys()))
raise KeyError(
f"'{option}' is not a valid parameter value, should be one of: {list}"
)
raise KeyError(f"'{option}' is not a valid parameter value, should be one of: {list}")

return self.data[option]
# continue recursively until we find a non-Tunable
el = self.data[option]
if isinstance(el, Tunable):
return el.select_for_configuration(params)
else:
return el

def __call__(self, params):
def __call__(self, params): # noqa: D102

Check warning on line 65 in kernel_tuner/accuracy.py

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Move this trailing comment on the previous empty line.

See more on https://sonarcloud.io/project/issues?id=KernelTuner_kernel_tuner&issues=AZ_guQ955lzukk0W37vz&open=AZ_guQ955lzukk0W37vz&pullRequest=397
return self.select_for_configuration(params)


Expand All @@ -70,6 +80,7 @@
if dtype is None:
try:
from ml_dtypes import bfloat16

dtype = bfloat16
except ImportError:
pass
Expand All @@ -78,6 +89,7 @@
if dtype is None:
try:
from jax.numpy import bfloat16

dtype = bfloat16
except ImportError:
pass
Expand All @@ -86,6 +98,7 @@
if dtype is None:
try:
from tensorflow import bfloat16

dtype = bfloat16.as_numpy_dtype
except ImportError:
pass
Expand All @@ -100,9 +113,9 @@


def _to_float_dtype(x: str) -> np.dtype:
"""Convert a string to a numpy data type (``dtype``). This function recognizes
common names (such as ``f16`` or ``kfloat``), and uses ``np.dtype(x)`` as a
fallback.
"""Convert a string to a numpy data type (``dtype``).

This function recognizes common names (such as ``f16`` or ``kfloat``), and uses ``np.dtype(x)`` as a fallback.
"""
if isinstance(x, str):
x = x.lower()
Expand All @@ -123,16 +136,17 @@


class TunablePrecision(Tunable):
def __init__(
self, param_key: str, array: np.ndarray, dtypes: Dict[str, np.dtype] = None
):
"""The ``Tunable`` object can be used as an input argument when tuning
kernels. It is a container that internally holds several arrays
"""``TunablePrecision`` can be used as a precision-level dependent input argument when tuning kernels."""

def __init__(self, param_key: str, array: np.ndarray, dtypes: Dict[str, np.dtype] = None):
"""The ``Tunable`` object can be used as an input argument when tuning kernels.

It is a container that internally holds several arrays
containing the same data, but stored in using different levels of
precision. During benchamrking, one array is selected based on the value
of the tunable parameter called ``param_key``.

Example
Example:
-------
Consider this example::

Expand All @@ -156,7 +170,6 @@
if bfloat16 is not None:
dtypes["bfloat16"] = bfloat16


# If dtype is a list, convert it to a dictionary
if isinstance(dtypes, (list, tuple)):
dtypes = dict((name, _to_float_dtype(name)) for name in dtypes)
Expand Down Expand Up @@ -197,7 +210,6 @@
The value of `EPS` is used for relative errors to prevent division by zero.
``
"""

# Prepocess the provided name:
# - convert to lowercase
# - remove the word "error"
Expand Down Expand Up @@ -278,17 +290,13 @@
raise ValueError(f"invalid error metric provided: {user_key}")

# cast both arguments to f64 before passing them to the metric
return lambda a, b: metric(
a.astype(np.float64, copy=False), b.astype(np.float64, copy=False)
)
return lambda a, b: metric(a.astype(np.float64, copy=False), b.astype(np.float64, copy=False))


class AccuracyObserver(OutputObserver):
"""``AccuracyObserver`` measures the error on the output produced by a kernel
by comparing the output against a reference output.
"""``AccuracyObserver`` measures the error on the output produced by a kernel by comparing to a reference output.

By default, it uses the root mean-squared error (RMSE) and uses the
metric name ``"error"``.
By default, it uses the root mean-squared error (RMSE) and uses the metric name ``"error"``.
"""

def __init__(self, metric=None, key="error", *, atol=1e-8):
Expand All @@ -303,7 +311,6 @@
:param atol: The tolerance used in relative metrics to prevent
division by zero. It is ignored by absolute error metrics.
"""

# Default metric is RMSE
if not metric:
metric = "rmse"
Expand All @@ -317,6 +324,7 @@
self.result = None

def process_output(self, answers, outputs):
"""Process the output produced by the kernel and compare it to the reference answers."""
errors = []

for answer, output in zip(answers, outputs):
Expand All @@ -326,4 +334,5 @@
self.result = max(errors)

def get_results(self):
"""Get the results produced by this observer."""
return dict([(self.key, self.result)])
Loading
Loading