python_code
stringlengths
0
1.02M
repo_name
stringlengths
9
48
file_path
stringlengths
5
114
import os import sysconfig import keopscore.config.config from keopscore.config.config import get_build_folder from keopscore.utils.Cache import Cache_partial from pykeops.common.keops_io.LoadKeOps import LoadKeOps from pykeops.common.utils import pyKeOps_Message from keopscore.utils.misc_utils import KeOps_OS_Run from pykeops.config import pykeops_cpp_name, python_includes class LoadKeOps_cpp_class(LoadKeOps): def __init__(self, *args, fast_init=False): super().__init__(*args, fast_init=fast_init) def init_phase1(self): srcname = pykeops_cpp_name(tag=self.params.tag, extension=".cpp") dllname = pykeops_cpp_name( tag=self.params.tag, extension=sysconfig.get_config_var("EXT_SUFFIX") ) if not os.path.exists(dllname): f = open(srcname, "w") f.write(self.get_pybind11_code()) f.close() compile_command = f"{keopscore.config.config.cxx_compiler} {keopscore.config.config.cpp_flags} {python_includes} {srcname} -o {dllname}" pyKeOps_Message( "Compiling pykeops cpp " + self.params.tag + " module ... ", flush=True, end="", ) KeOps_OS_Run(compile_command) pyKeOps_Message("OK", use_tag=False, flush=True) def init_phase2(self): import importlib mylib = importlib.import_module( os.path.basename(pykeops_cpp_name(tag=self.params.tag)) ) self.launch_keops_cpu = mylib.launch_pykeops_cpu def call_keops(self, nx, ny): self.launch_keops_cpu( self.params.dimy, nx, ny, self.params.tagI, self.params.tagZero, self.params.use_half, self.params.dimred, self.params.use_chunk_mode, self.params.indsi, self.params.indsj, self.params.indsp, self.params.dim, self.params.dimsx, self.params.dimsy, self.params.dimsp, self.ranges_ptr_new, self.outshape, self.out_ptr, self.args_ptr_new, self.argshapes_new, ) def get_pybind11_code(self): return f""" #include "{self.params.source_name}" #include <pybind11/pybind11.h> namespace py = pybind11; template < typename TYPE > int launch_pykeops_{self.params.tag}_cpu(int dimY, int nx, int ny, int tagI, int tagZero, int use_half, int dimred, int use_chunk_mode, py::tuple py_indsi, py::tuple py_indsj, py::tuple py_indsp, int dimout, py::tuple py_dimsx, py::tuple py_dimsy, py::tuple py_dimsp, py::tuple py_ranges, py::tuple py_shapeout, long out_void, py::tuple py_arg, py::tuple py_argshape){{ /*------------------------------------*/ /* Cast input args */ /*------------------------------------*/ std::vector< int > indsi_v(py_indsi.size()); for (auto i = 0; i < py_indsi.size(); i++) indsi_v[i] = py::cast< int >(py_indsi[i]); std::vector< int > indsj_v(py_indsj.size()); for (auto i = 0; i < py_indsj.size(); i++) indsj_v[i] = py::cast< int >(py_indsj[i]); std::vector< int > indsp_v(py_indsp.size()); for (auto i = 0; i < py_indsp.size(); i++) indsp_v[i] = py::cast< int >(py_indsp[i]); std::vector< int > dimsx_v(py_dimsx.size()); for (auto i = 0; i < py_dimsx.size(); i++) dimsx_v[i] = py::cast< int >(py_dimsx[i]); std::vector< int > dimsy_v(py_dimsy.size()); for (auto i = 0; i < py_dimsy.size(); i++) dimsy_v[i] = py::cast< int >(py_dimsy[i]); std::vector< int > dimsp_v(py_dimsp.size()); for (auto i = 0; i < py_dimsp.size(); i++) dimsp_v[i] = py::cast< int >(py_dimsp[i]); // Cast the ranges arrays std::vector< int* > ranges_v(py_ranges.size()); for (int i = 0; i < py_ranges.size(); i++) ranges_v[i] = (int*) py::cast< long >(py_ranges[i]); int **ranges = (int**) ranges_v.data(); std::vector< int > shapeout_v(py_shapeout.size()); for (auto i = 0; i < py_shapeout.size(); i++) shapeout_v[i] = py::cast< int >(py_shapeout[i]); TYPE *out = (TYPE*) out_void; // std::cout << "out_ptr : " << (long) out << std::endl; std::vector< TYPE* > arg_v(py_arg.size()); for (int i = 0; i < py_arg.size(); i++) arg_v[i] = (TYPE*) py::cast< long >(py_arg[i]); TYPE **arg = (TYPE**) arg_v.data(); std::vector< std::vector< int > > argshape_v(py_argshape.size()); for (auto i = 0; i < py_argshape.size(); i++){{ py::tuple tmp = py_argshape[i]; std::vector< int > tmp_v(tmp.size()); for (auto j =0; j < tmp.size(); j++) tmp_v[j] = py::cast< int >(tmp[j]); argshape_v[i] = tmp_v; }} return launch_keops_cpu_{self.params.tag}< TYPE >(dimY, nx, ny, tagI, tagZero, use_half, dimred, use_chunk_mode, indsi_v, indsj_v, indsp_v, dimout, dimsx_v, dimsy_v, dimsp_v, ranges, shapeout_v, out, arg, argshape_v); }} PYBIND11_MODULE(pykeops_cpp_{self.params.tag}, m) {{ m.doc() = "pyKeOps: KeOps for pytorch through pybind11 (pytorch flavour)."; m.def("launch_pykeops_cpu", &launch_pykeops_{self.params.tag}_cpu < {cpp_dtype[self.params.dtype]} >, "Entry point to keops."); }} """ LoadKeOps_cpp = Cache_partial( LoadKeOps_cpp_class, use_cache_file=True, save_folder=get_build_folder() ) cpp_dtype = { "float": "float", "float32": "float", "double": "double", "float64": "double", }
keops-main
pykeops/pykeops/common/keops_io/LoadKeOps_cpp.py
# Test for gaussian kernel operation using LazyTensors. import time import math import torch from pykeops.torch import LazyTensor M, N, D, DV = 10000, 10000, 3, 1 dtype = torch.float32 test_grad = True test_grad2 = False device_id = "cpu" # "cuda" if torch.cuda.is_available() else "cpu" do_warmup = True x = torch.rand(M, 1, D, device=device_id, dtype=dtype) / math.sqrt(D) y = torch.rand(1, N, D, device=device_id, dtype=dtype) / math.sqrt(D) b = torch.randn(N, DV, requires_grad=test_grad, device=device_id, dtype=dtype) def fun(x, y, b, backend): if "keops" in backend: x = LazyTensor(x) y = LazyTensor(y) Dxy = ((x - y) ** 2).sum(dim=2) Kxy = (-Dxy).exp() if backend == "keops": out = LazyTensor.__matmul__(Kxy, b, backend="CPU") else: out = Kxy @ b if device_id != "cpu": torch.cuda.synchronize() # print("out:",out.flatten()[:10]) return out backends = ["keops", "torch"] # "keops_old" out = [] for backend in backends: if do_warmup: fun( x[: min(M, 100), :, :], y[:, : min(N, 100), :], b[: min(N, 100), :], backend ) fun( x[: min(M, 100), :, :], y[:, : min(N, 100), :], b[: min(N, 100), :], backend ) start = time.time() out.append(fun(x, y, b, backend).squeeze()) end = time.time() print("time for " + backend + ":", end - start) if len(out) > 1: print("relative error:", (torch.norm(out[0] - out[1]) / torch.norm(out[0])).item()) if test_grad: out_g = [] for k, backend in enumerate(backends): start = time.time() out_g.append( torch.autograd.grad((out[k] ** 2).sum(), [b], create_graph=True)[0] ) end = time.time() print("time for " + backend + " (grad):", end - start) if len(out_g) > 1: print( "relative error grad:", (torch.norm(out_g[0] - out_g[1]) / torch.norm(out_g[0])).item(), ) if test_grad2: out_g2 = [] for k, backend in enumerate(backends): start = time.time() out_g2.append(torch.autograd.grad((out_g[k] ** 2).sum(), [b])[0]) end = time.time() print("time for " + backend + " (grad):", end - start) if len(out_g2) > 1: print( "relative error grad:", (torch.norm(out_g2[0] - out_g2[1]) / torch.norm(out_g2[0])).item(), ) if len(out_g) > 1: print( "relative error grad:", (torch.norm(out_g[0] - out_g[1]) / torch.norm(out_g[0])).item(), )
keops-main
pykeops/pykeops/sandbox/test_lazytensor_gaussian_cpu.py
import pykeops import torch import math from pykeops.torch import LazyTensor device = "cuda" if torch.cuda.is_available() else "cpu" # rounds to the nearest integer (0 decimal) x = torch.FloatTensor(1000, 1).uniform_(-10, 10) y = x.data.clone() x = x.to(device) y = y.to(device) x.requires_grad = True y.requires_grad = True x_i = LazyTensor(x[:, None]) s1 = x_i.round().sum(0) s2 = torch.sum(torch.round(y)) print("s1 - s2", torch.abs(s1 - s2).item()) assert torch.abs(s1 - s2) < 1e-3, torch.abs(s1 - s2) s1.backward() s2.backward() print("grad_s1 - grad_s2", torch.max(torch.abs(x.grad - y.grad)).item()) assert torch.max(torch.abs(x.grad - y.grad)) < 1e-3 # rounds to 3 decimal places x = torch.FloatTensor(1000, 1).uniform_(-1, 1) y = x.data.clone() x = x.to(device) y = y.to(device) x.requires_grad = True y.requires_grad = True x_i = LazyTensor(x[:, None]) s1 = x_i.round(3).sum(0) s2 = torch.sum(torch.round(y * 1e3) * 1e-3) print("s1 - s2", torch.abs(s1 - s2).item()) assert torch.abs(s1 - s2) < 1e-3, torch.abs(s1 - s2) s1.backward() s2.backward() print("grad_s1 - grad_s2", torch.max(torch.abs(x.grad - y.grad)).item()) assert torch.max(torch.abs(x.grad - y.grad)) < 1e-3
keops-main
pykeops/pykeops/sandbox/test_round.py
import torch from pykeops.torch import LazyTensor x, y = torch.randn(1000, 3), torch.randn(2000, 3) x_i, y_j = LazyTensor(x[:, None, :]), LazyTensor(y[None, :, :]) K = (-((x_i - y_j) ** 2).sum(2)).exp() # Symbolic (1000,2000) Gaussian kernel matrix K_ = ( -((x[:, None, :] - y[None, :, :]) ** 2).sum(2) ).exp() # Explicit (1000,2000) Gaussian kernel matrix w = torch.rand(1000, 2) print((K.t() @ w - K_.t() @ w).abs().mean())
keops-main
pykeops/pykeops/sandbox/test_transpose.py
# Test for Clamp operation using LazyTensors import time import math import torch from pykeops.torch import LazyTensor M, N, D = 1000, 1000, 3 test_grad = True device_id = "cuda:0" if torch.cuda.is_available() else "cpu" do_warmup = True x = torch.randn(M, 1, D, requires_grad=test_grad, device=device_id) y = torch.randn(1, N, D, device=device_id) a = -1.23 b = 1.54 def fun(x, y, a, b, backend): if backend == "keops": x = LazyTensor(x) y = LazyTensor(y) elif backend != "torch": raise ValueError("wrong backend") Dxy = ((x * y).clamp(a, b)).sum(dim=2) Kxy = (-(Dxy**2)).exp() return Kxy.sum(dim=1) backends = ["torch", "keops"] out = [] for backend in backends: if do_warmup: fun(x[: min(M, 100), :, :], y[:, : min(N, 100), :], a, b, backend) fun(x[: min(M, 100), :, :], y[:, : min(N, 100), :], a, b, backend) start = time.time() out.append(fun(x, y, a, b, backend).squeeze()) end = time.time() # print(out[-1].squeeze()[:10]) print("time for " + backend + ":", end - start) if len(out) > 1: print("relative error:", (torch.norm(out[0] - out[1]) / torch.norm(out[0])).item()) if test_grad: out_g = [] for k, backend in enumerate(backends): start = time.time() out_g.append(torch.autograd.grad((out[k] ** 2).sum(), [x])[0]) end = time.time() print("time for " + backend + " (grad):", end - start) if len(out_g) > 1: print( "relative error grad:", (torch.norm(out_g[0] - out_g[1]) / torch.norm(out_g[0])).item(), )
keops-main
pykeops/pykeops/sandbox/test_lazytensor_clamp.py
from pykeops.numpy import LazyTensor import numpy as np a1 = np.random.rand(2, 1000, 5) a2 = np.ascontiguousarray(a1.transpose(2, 0, 1)).transpose(1, 2, 0) b = np.random.rand(2, 1000, 5) c = np.random.rand(2, 1000, 5) b_j = LazyTensor(b[:, None]) a1_i = LazyTensor(a1[:, :, None]) dist1 = a1_i.sqdist(b_j) kernel1 = dist1.exp() d1 = kernel1 @ c a2_i = LazyTensor(a2[:, :, None]) dist2 = a2_i.sqdist(b_j) kernel2 = dist2.exp() d2 = kernel2 @ c print(np.linalg.norm(d2 - d1))
keops-main
pykeops/pykeops/sandbox/test_contiguous_numpy.py
# Test for gaussian kernel operation using LazyTensors. import time import math import torch from pykeops.torch import LazyTensor M, N, D, DV = 10000, 10000, 3, 1 dtype = torch.float32 test_grad = True test_grad2 = False device_id = "cuda:0" if torch.cuda.is_available() else "cpu" do_warmup = True x = torch.rand( M, 1, D, requires_grad=test_grad, device=device_id, dtype=dtype ) / math.sqrt(D) y = torch.rand(1, N, D, device=device_id, dtype=dtype) / math.sqrt(D) b = torch.randn(N, DV, device=device_id, dtype=dtype) def fun(x, y, b, backend): if "keops" in backend: x = LazyTensor(x) y = LazyTensor(y) Dxy = ((x - y) ** 2).sum(dim=2) Kxy = (-Dxy).exp() if backend == "keops_old": out = LazyTensor.__matmul__(Kxy, b, optional_flags=["-DENABLE_FINAL_CHUNKS=0"]) else: out = Kxy @ b if device_id != "cpu": torch.cuda.synchronize() # print("out:",out.flatten()[:10]) return out backends = ["keops", "torch"] # "keops_old" out = [] for backend in backends: if do_warmup: fun( x[: min(M, 100), :, :], y[:, : min(N, 100), :], b[: min(N, 100), :], backend ) fun( x[: min(M, 100), :, :], y[:, : min(N, 100), :], b[: min(N, 100), :], backend ) start = time.time() out.append(fun(x, y, b, backend).squeeze()) end = time.time() print("time for " + backend + ":", end - start) if len(out) > 1: print("relative error:", (torch.norm(out[0] - out[1]) / torch.norm(out[0])).item()) if test_grad: out_g = [] for k, backend in enumerate(backends): start = time.time() out_g.append( torch.autograd.grad((out[k] ** 2).sum(), [x], create_graph=True)[0] ) end = time.time() print("time for " + backend + " (grad):", end - start) if len(out_g) > 1: print( "relative error grad:", (torch.norm(out_g[0] - out_g[1]) / torch.norm(out_g[0])).item(), ) if test_grad2: out_g2 = [] for k, backend in enumerate(backends): start = time.time() out_g2.append(torch.autograd.grad((out_g[k] ** 2).sum(), [x])[0]) end = time.time() print("time for " + backend + " (grad):", end - start) if len(out_g2) > 1: print( "relative error grad:", (torch.norm(out_g2[0] - out_g2[1]) / torch.norm(out_g2[0])).item(), ) if len(out_g) > 1: print( "relative error grad:", (torch.norm(out_g[0] - out_g[1]) / torch.norm(out_g[0])).item(), )
keops-main
pykeops/pykeops/sandbox/test_lazytensor_gaussian.py
import pykeops import torch import math from pykeops.torch import LazyTensor device = "cuda" if torch.cuda.is_available() else "cpu" x = torch.rand(5, 1) * 2 * math.pi y = x.data.clone() x = x.to(device) y = y.to(device) x.requires_grad = True y.requires_grad = True x_i = LazyTensor(x[:, None]) s1 = x_i.sinc().sum(0) s1.backward() if torch.__version__ >= "1.8": s2 = torch.sum(torch.sinc(y)) print("s1 - s2", torch.abs(s1 - s2).item()) assert torch.abs(s1 - s2) < 1e-3, torch.abs(s1 - s2) s2.backward() print("grad_s1 - grad_s2", torch.max(torch.abs(x.grad - y.grad)).item()) assert torch.max(torch.abs(x.grad - y.grad)) < 1e-3 else: print("ok")
keops-main
pykeops/pykeops/sandbox/test_sinc.py
import pykeops import torch import math from pykeops.torch import LazyTensor # test for modulus operation def torch_mod(input, modulus, offset=0): return input - modulus * torch.floor((input - offset) / modulus) device = "cuda" if torch.cuda.is_available() else "cpu" offset = -math.pi / 2 x = torch.rand(10000, 1) * 2 * math.pi y = x.data.clone() x = x.to(device) y = y.to(device) x.requires_grad = True y.requires_grad = True x_i = LazyTensor(x[:, None]) s1 = x_i.mod(math.pi, offset).sum(0) s2 = torch.sum(torch_mod(y, math.pi, offset)) print("relative error : ", (torch.abs(s1 - s2) / torch.abs(s2)).item()) assert torch.abs(s1 - s2) / torch.abs(s2) < 1e-3 s1.backward() s2.backward() print( "relative error grad : ", (torch.norm(x.grad - y.grad) / torch.norm(y.grad)).item() ) assert torch.norm(x.grad - y.grad) / torch.norm(y.grad) < 1e-3
keops-main
pykeops/pykeops/sandbox/test_mod.py
# Test for Clamp operation using LazyTensors import time import math import torch from pykeops.torch import LazyTensor dtype = torch.float16 M, N, D = 5, 5, 1 test_grad = True device_id = "cuda" if torch.cuda.is_available() else "cpu" do_warmup = False x = torch.zeros(M, 1, D, dtype=dtype, requires_grad=test_grad, device=device_id) y = torch.ones(1, N, D, dtype=dtype, device=device_id) a = -1.23 b = 1.54 def fun(x, y, a, b, backend): if backend == "keops": x = LazyTensor(x) y = LazyTensor(y) elif backend != "torch": raise ValueError("wrong backend") Dxy = (x - y).sum(dim=2) Kxy = Dxy return Kxy.sum(dim=0) backends = ["torch", "keops"] out = [] for backend in backends: if do_warmup: fun(x[: min(M, 100), :, :], y[:, : min(N, 100), :], a, b, backend) fun(x[: min(M, 100), :, :], y[:, : min(N, 100), :], a, b, backend) start = time.time() out.append(fun(x, y, a, b, backend).squeeze()) end = time.time() print("time for " + backend + ":", end - start) if len(out) > 1: print("relative error:", (torch.norm(out[0] - out[1]) / torch.norm(out[0])).item()) if test_grad: out_g = [] for k, backend in enumerate(backends): start = time.time() out_g.append(torch.autograd.grad(out[k][0], [x])[0]) end = time.time() print("time for " + backend + " (grad):", end - start) if len(out_g) > 1: print( "relative error grad:", (torch.norm(out_g[0] - out_g[1]) / torch.norm(out_g[0])).item(), )
keops-main
pykeops/pykeops/sandbox/test_float16.py
# Test for gaussian kernel operation using LazyTensors. import time import math import torch from pykeops.torch import LazyTensor M, N, D, DV = 1000, 1000, 3, 1 dtype = torch.float32 device_id = "cpu" # "cuda:1" if torch.cuda.is_available() else "cpu" do_warmup = True x = torch.rand(M, 1, D, device=device_id, dtype=dtype) / math.sqrt(D) y = torch.rand(1, N, D, device=device_id, dtype=dtype) / math.sqrt(D) b = torch.randn(N, DV, device=device_id, dtype=dtype) def fun(x, y, b, backend): if "keops" in backend: x = LazyTensor(x) y = LazyTensor(y) Dxy = ((x - y) ** 2).sum(dim=2) Kxy = (-Dxy).exp() if "keops" in backend: if backend.split("_")[1] == "gpu": out = Kxy.__matmul__(b, backend="GPU_1D") elif backend.split("_")[1] == "cpu": out = Kxy.__matmul__(b, backend="CPU") else: out = Kxy @ b return out backends = ["torch", "keops_cpu", "keops_gpu"] out = [] for backend in backends: if do_warmup: fun( x[: min(M, 100), :, :], y[:, : min(N, 100), :], b[: min(N, 100), :], backend ) fun( x[: min(M, 100), :, :], y[:, : min(N, 100), :], b[: min(N, 100), :], backend ) start = time.time() out.append(fun(x, y, b, backend).squeeze()) end = time.time() print("time for " + backend + ":", end - start) for k in range(1, len(out)): print( f"relative error for {backends[k]}:", (torch.norm(out[0] - out[k]) / torch.norm(out[0])).item(), )
keops-main
pykeops/pykeops/sandbox/test_gpu_cpu.py
import time import math import numpy as np from pykeops.numpy import LazyTensor, ComplexLazyTensor M, N, D = 1000, 1000, 3 dtype = "float32" do_warmup = False x = np.random.rand(M, 1, D).astype(dtype) + 1j * np.random.rand(M, 1, D).astype(dtype) y = np.random.rand(1, N, D).astype(dtype) + 1j * np.random.rand(1, N, D).astype(dtype) a = -1.23 b = 1.54 def view_as_real(x): if x.dtype == complex: return torch.view_as_real(x) else: return x def fun(x, y, a, b, backend): if backend == "keops": x = LazyTensor(x) y = LazyTensor(y) conj = ComplexLazyTensor.conj angle = ComplexLazyTensor.angle else: conj = np.conj angle = np.angle Kxy = ((x * y) * y.real + x + x.real).sum(axis=2) return Kxy.sum(axis=0) backends = ["numpy", "keops"] out = [] for backend in backends: if do_warmup: fun(x[: min(M, 100), :, :], y[:, : min(N, 100), :], a, b, backend) fun(x[: min(M, 100), :, :], y[:, : min(N, 100), :], a, b, backend) start = time.time() out.append(fun(x, y, a, b, backend).squeeze()) end = time.time() print("time for " + backend + ":", end - start) if len(out) > 1: # print(out[0]) # print(out[1]) print( "relative error:", ( np.linalg.norm((out[0] - out[1]).view("float")) / np.linalg.norm((out[0]).view("float")) ).item(), )
keops-main
pykeops/pykeops/sandbox/test_complex_numpy.py
# Non-Uniform Discrete Fourier Tranform example import time import math import torch from pykeops.torch import LazyTensor dtype = torch.float32 dtype_c = torch.complex64 M, N, D = 1000, 1000, 1 test_grad = False device_id = "cuda" if torch.cuda.is_available() else "cpu" do_warmup = False x = torch.rand(1, N, D, dtype=dtype_c, requires_grad=test_grad, device=device_id) p = torch.rand(1, N, D, dtype=dtype, device=device_id) f = torch.rand(M, 1, D, dtype=dtype, device=device_id) def view_as_real(x): if torch.is_complex(x): return torch.view_as_real(x) else: return x def fun(x, p, f, backend): if "keops" in backend: x = LazyTensor(x) p = LazyTensor(p) f = LazyTensor(f) X = x * (-2 * math.pi * 1j * p * f).exp() return X.sum(dim=0) backends = ["keops", "torch"] out = [] for backend in backends: if do_warmup: fun( x[:, : min(N, 100), :], p[:, : min(N, 100), :], f[: min(M, 100), :, :], backend, ) fun( x[:, : min(N, 100), :], p[:, : min(N, 100), :], f[: min(M, 100), :, :], backend, ) start = time.time() out.append(fun(x, p, f, backend).squeeze()) end = time.time() print("time for " + backend + ":", end - start) if len(out) > 1: print( "relative error:", ( torch.norm(view_as_real(out[0] - out[1]).cpu()) / torch.norm(view_as_real(out[0]).cpu()) ).item(), ) if test_grad: out_g = [] for k, backend in enumerate(backends): start = time.time() if out[k].is_complex(): out_g.append( torch.autograd.grad((out[k].real ** 2 + out[k].imag ** 2).sum(), [x])[0] ) else: out_g.append(torch.autograd.grad((out[k] ** 2).sum(), [x])[0]) end = time.time() print("time for " + backend + " (grad):", end - start) if len(out_g) > 1: print( "relative error grad:", ( torch.norm(view_as_real(out_g[0] - out_g[1]).cpu()) / torch.norm(view_as_real(out_g[0]).cpu()) ).item(), )
keops-main
pykeops/pykeops/sandbox/test_complex.py
# Test for gaussian kernel operation using LazyTensors. import time import math import numpy as np from pykeops.numpy import LazyTensor M, N, D, DV = 10000, 10000, 3, 1 dtype = np.float32 do_warmup = True x = np.random.rand(M, 1, D).astype(dtype) / math.sqrt(D) y = np.random.rand(1, N, D).astype(dtype) / math.sqrt(D) b = np.random.randn(N, DV).astype(dtype) def fun(x, y, b, backend): if "keops" in backend: x = LazyTensor(x) y = LazyTensor(y) Dxy = ((x - y) ** 2).sum(axis=2) if "keops" in backend: Kxy = (-Dxy).exp() else: Kxy = np.exp(-Dxy) out = Kxy @ b return out backends = ["keops", "numpy"] # "keops_old" out = [] for backend in backends: if do_warmup: fun( x[: min(M, 100), :, :], y[:, : min(N, 100), :], b[: min(N, 100), :], backend ) fun( x[: min(M, 100), :, :], y[:, : min(N, 100), :], b[: min(N, 100), :], backend ) start = time.time() out.append(fun(x, y, b, backend).squeeze()) end = time.time() print("time for " + backend + ":", end - start) if len(out) > 1: print( "relative error:", (np.linalg.norm(out[0] - out[1]) / np.linalg.norm(out[0])).item(), )
keops-main
pykeops/pykeops/sandbox/test_lazytensor_gaussian_numpy.py
""" Block-sparse reductions =========================== This script showcases the use of the optional **ranges** argument to compute block-sparse reductions with **sub-quadratic time complexity**. """ ######################################################################## # Setup # ------------ # Standard imports: # import time import numpy as np from matplotlib import pyplot as plt from pykeops.numpy import LazyTensor import pykeops.config dtype = "float32" ######################################################################## # Define our dataset: two point clouds on the unit square. # M, N = (5000, 5000) if pykeops.config.gpu_available else (2000, 2000) t = np.linspace(0, 2 * np.pi, M + 1)[:-1] x = np.stack((0.4 + 0.4 * (t / 7) * np.cos(t), 0.5 + 0.3 * np.sin(t)), 1) x = x + 0.01 * np.random.randn(*x.shape) x = x.astype(dtype) y = np.random.randn(N, 2).astype(dtype) y = y / 10 + np.array([0.6, 0.6]).astype(dtype) #################################################################### # Computing a block-sparse reduction # --------------------------------------- # # On the GPU, **contiguous memory accesses** are key to high performances. # To enable the implementation of algorithms with **sub-quadratic time complexity** # under this constraint, KeOps provides access to # **block-sparse reduction routines** through the optional # **ranges** argument, which is supported by :class:`numpy.Genred <pykeops.numpy.Genred>` # and all its children. # # Pre-processing # ~~~~~~~~~~~~~~~~~~~ # # To leverage this feature through the :mod:`pykeops.torch` API, # the first step is to **clusterize your data** # into groups which should neither be too **small** (performances on clusters # with less than ~200 points each are suboptimal) # nor too **many** (the :func:`from_matrix() <pykeops.numpy.cluster.from_matrix>` # pre-processor can become a bottleneck when working with >2,000 clusters # per point cloud). # # In this tutorial, we use the :func:`grid_cluster() <pykeops.numpy.cluster.grid_cluster>` # routine which simply groups points into **cubic bins** of arbitrary size: from pykeops.numpy.cluster import grid_cluster eps = 0.05 # Size of our square bins Start = time.time() start = time.time() x_labels = grid_cluster(x, eps) # class labels y_labels = grid_cluster(y, eps) # class labels end = time.time() print("Perform clustering : {:.4f}s".format(end - start)) ########################################################################## # Once (integer) cluster labels have been computed, # we can compute the **centroids** and **memory footprint** of each class: from pykeops.numpy.cluster import cluster_ranges_centroids # Compute one range and centroid per class: start = time.time() x_ranges, x_centroids, _ = cluster_ranges_centroids(x, x_labels) y_ranges, y_centroids, _ = cluster_ranges_centroids(y, y_labels) end = time.time() print("Compute ranges+centroids : {:.4f}s".format(end - start)) ######################################################################### # Finally, we can **sort** our points according to their # labels, making sure that **all clusters are stored contiguously in memory**: from pykeops.numpy.cluster import sort_clusters start = time.time() x, x_labels = sort_clusters(x, x_labels) y, y_labels = sort_clusters(y, y_labels) end = time.time() print("Sort the points : {:.4f}s".format(end - start)) #################################################################### # Cluster-Cluster binary mask # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # The key idea behind KeOps's block-sparsity mode # is that as soon as data points are sorted, # **we can manage the reduction scheme through a small, coarse boolean mask** # whose values encode whether or not we should perform computations # at a finer scale. # # In this example, we compute a simple Gaussian # convolution of radius :math:`\sigma` # and decide to **skip** points-to-points **interactions** between # blocks whose **centroids are further apart** than :math:`4\sigma`, # as :math:`\exp(- (4\sigma)^2 / 2\sigma^2 ) = e^{-8} \ll 1`, # with 99% of the mass of a Gaussian kernel located in the :math:`3\sigma` range. sigma = 0.05 # Characteristic length of interaction start = time.time() # Compute a coarse Boolean mask: D = np.sum((x_centroids[:, None, :] - y_centroids[None, :, :]) ** 2, 2) keep = D < (4 * sigma) ** 2 ############################################################################## # To turn this mask into a set of integer Tensors which # is more palatable to KeOps's low-level CUDA API, # we then use the :func:`from_matrix <pykeops.numpy.cluster.from_matrix>` # routine... from pykeops.numpy.cluster import from_matrix ranges_ij = from_matrix(x_ranges, y_ranges, keep) end = time.time() print("Process the ranges : {:.4f}s".format(end - start)) End = time.time() t_cluster = End - Start print("Total time (synchronized): {:.4f}s".format(End - Start)) print("") ############################################################################### # And we're done: here is the **ranges** argument that can # be fed to the KeOps reduction routines! # For large point clouds, we can expect a speed-up that is directly # proportional to the ratio of mass between our **fine binary mask** # (encoded in **ranges_ij**) and the full, N-by-M kernel matrix: areas = (x_ranges[:, 1] - x_ranges[:, 0])[:, None] * (y_ranges[:, 1] - y_ranges[:, 0])[ None, : ] total_area = np.sum(areas) # should be equal to N*M sparse_area = np.sum(areas[keep]) print( "We keep {:.2e}/{:.2e} = {:2d}% of the original kernel matrix.".format( sparse_area, total_area, int(100 * sparse_area / total_area) ) ) print("") #################################################################### # Benchmark a block-sparse Gaussian convolution # ------------------------------------------------- # # Define a Gaussian kernel matrix from 2d point clouds: x_, y_ = x / sigma, y / sigma x_i, y_j = LazyTensor(x_[:, None, :]), LazyTensor(y_[None, :, :]) D_ij = ((x_i - y_j) ** 2).sum(dim=2) # Symbolic (M,N,1) matrix of squared distances K = (-D_ij / 2).exp() # Symbolic (M,N,1) Gaussian kernel matrix ##################################################################### # And create a random signal supported by the points :math:`y_j`: b = np.random.randn(N, 1).astype(dtype) ############################################################################## # Compare the performances of our **block-sparse** code # with those of a **dense** implementation, on both CPU and GPU backends: # # .. note:: # The standard KeOps routine are already *very* efficient: # on the GPU, speed-ups with multiscale, block-sparse schemes only start to # kick on around the "20,000 points" mark as the skipped computations # make up for the clustering and branching overheads. # backends = ( (["CPU", "GPU"] if M * N < 4e8 else ["GPU"]) if pykeops.config.gpu_available else ["CPU"] ) for backend in backends: K.backend = backend # Switch to CPU or GPU mode # GPU warm-up: a = K @ b start = time.time() K.ranges = None # default a_full = K @ b end = time.time() t_full = end - start print(" Full convolution, {} backend: {:2.4f}s".format(backend, end - start)) start = time.time() K.ranges = ranges_ij # block-sparsity pattern a_sparse = K @ b end = time.time() t_sparse = end - start print("Sparse convolution, {} backend: {:2.4f}s".format(backend, end - start)) print( "Relative time : {:3d}% ({:3d}% including clustering), ".format( int(100 * t_sparse / t_full), int(100 * (t_sparse + t_cluster) / t_full) ) ) print( "Relative error: {:3.4f}%".format( 100 * np.sum(np.abs(a_sparse - a_full)) / np.sum(np.abs(a_full)) ) ) print("") #################################################################### # Fancy visualization: we display our coarse binary mask # and highlight one of its lines, that corresponds to the **cyan** cluster # and its **magenta** neighbors: # # Find the cluster centroid which is closest to the (.43,.6) point: dist_target = np.sum(((x_centroids - np.array([0.43, 0.6]).astype(dtype)) ** 2), axis=1) clust_i = np.argmin(dist_target) if M + N <= 500000: ranges_i, slices_j, redranges_j = ranges_ij[0:3] start_i, end_i = ranges_i[clust_i] # Indices of the points that make up our cluster start, end = ( slices_j[clust_i - 1], slices_j[clust_i], ) # Ranges of the cluster's neighbors keep = keep.astype(float) keep[clust_i] += 2 plt.ion() plt.matshow(keep) plt.figure(figsize=(10, 10)) plt.scatter( x[:, 0], x[:, 1], c=x_labels, cmap=plt.cm.Wistia, s=25 * 500 / len(x), label="Target points", ) plt.scatter( y[:, 0], y[:, 1], c=y_labels, cmap=plt.cm.winter, s=25 * 500 / len(y), label="Source points", ) # Target clusters: for start_j, end_j in redranges_j[start:end]: plt.scatter( y[start_j:end_j, 0], y[start_j:end_j, 1], c="magenta", s=50 * 500 / len(y) ) # Source cluster: plt.scatter( x[start_i:end_i, 0], x[start_i:end_i, 1], c="cyan", s=10, label="Cluster {}".format(clust_i), ) plt.scatter( x_centroids[:, 0], x_centroids[:, 1], c="black", s=10, alpha=0.5, label="Cluster centroids", ) plt.legend(loc="lower right") # sphinx_gallery_thumbnail_number = 2 plt.axis("equal") plt.axis([0, 1, 0, 1]) plt.tight_layout() plt.show(block=True)
keops-main
pykeops/pykeops/sandbox/test_gpu_cpu2.py
from pykeops.torch import LazyTensor import torch # a = torch.rand(2, 1000, 5) a = torch.rand(1000, 5, 2).permute(2, 0, 1) a.requires_grad = True b = torch.rand(2, 1000, 5) c1 = torch.rand(2, 1000, 5) c2 = torch.rand(2, 1000, 5) a_i = LazyTensor(a[:, :, None]) b_j = LazyTensor(b[:, None]) dist = a_i.sqdist(b_j) kernel = dist.exp() d1 = kernel @ c1 d2 = kernel @ c2 # case 1 d_permute = d1.permute(0, 2, 1) d_permute.clone().mean().backward() # case 2 # d_cat = torch.cat([d1,d2],2) # d_cat.mean().backward()
keops-main
pykeops/pykeops/sandbox/test_contiguous.py
# Test for gaussian kernel operation using LazyTensors. import time import math import torch from pykeops.torch import LazyTensor B1, B2, M, N, D, DV = 3, 4, 20, 25, 3, 2 test_grad = True device_id = "cuda" if torch.cuda.is_available() else "cpu" do_warmup = False x = torch.rand(1, B2, M, 1, D, device=device_id) / math.sqrt(D) y = torch.rand(B1, B2, 1, N, D, device=device_id) / math.sqrt(D) b = torch.randn(B1, 1, N, DV, requires_grad=test_grad, device=device_id) def fun(x, y, b, backend): if backend == "keops": x = LazyTensor(x) y = LazyTensor(y) elif backend != "torch": raise ValueError("wrong backend") Dxy = ((x - y) ** 2).sum(dim=4) Kxy = (-Dxy).exp() out = Kxy @ b if device_id != "cpu": torch.cuda.synchronize() # print("out:",out.flatten()[:10]) return out backends = ["torch", "keops"] out = [] for backend in backends: if do_warmup: fun( x[:, :, : min(M, 100), :, :].contiguous(), y[:, :, :, : min(N, 100), :].contiguous(), b[:, :, : min(N, 100), :].contiguous(), backend, ) fun( x[:, :, : min(M, 100), :, :].contiguous(), y[:, :, :, : min(N, 100), :].contiguous(), b[:, :, : min(N, 100), :].contiguous(), backend, ) start = time.time() out.append(fun(x, y, b, backend).squeeze()) end = time.time() print("time for " + backend + ":", end - start) if len(out) > 1: print("relative error:", (torch.norm(out[0] - out[1]) / torch.norm(out[0])).item()) if test_grad: out_g = [] for k, backend in enumerate(backends): start = time.time() out_g.append(torch.autograd.grad((out[k] ** 2).sum(), [b])[0]) end = time.time() print("time for " + backend + " (grad):", end - start) if len(out_g) > 1: print() print("out_g[0]:", out_g[0].flatten()[:10]) print("out_g[1]:", out_g[1].flatten()[:10]) print( "relative error grad:", (torch.norm(out_g[0] - out_g[1]) / torch.norm(out_g[0])).item(), )
keops-main
pykeops/pykeops/sandbox/test_lazytensor_gaussian_batch.py
import torch import pykeops from pykeops.torch import LazyTensor ttypes = ( (torch.cuda.FloatTensor,) if torch.cuda.is_available() else (torch.FloatTensor,) ) # Test when LazyTensors share underlying data for ttype in ttypes: torch.set_default_tensor_type(ttype) # Input f = torch.randn([1000, 1]) f.requires_grad = True f_i = LazyTensor(f[:, None, :]) f_ref = f.detach().clone() f_ref.requires_grad = True # Values first = lambda x: x.sqrt() second = lambda x: x * x * x # Keops val = f_i.ifelse(first(f_i), second(f_i)).sum(dim=0) # Torch val_refs = torch.zeros_like(f_ref) val_refs[f_ref >= 0] = first(f_ref[f_ref >= 0]) val_refs[f_ref < 0] = second(f_ref[f_ref < 0]) val_ref = val_refs.sum(dim=0) print("Checking values") print(f"|val - val_ref|: {(val - val_ref).abs()}\n") assert torch.allclose(val, val_ref) # Gradients val.backward() val_ref.backward() print("Checking gradients:") print(f"max(|grad - grad_ref|): {(f.grad - f_ref.grad).abs().max()}\n") assert torch.allclose(f.grad, f_ref.grad) # Test when other LazyTensors don't share underlying data (maybe unnecessary) for ttype in ttypes: torch.set_default_tensor_type(ttype) # Input f = torch.randn([1000, 1]) g = torch.randn_like(f).abs() h = torch.randn_like(f) f.requires_grad = True g.requires_grad = True h.requires_grad = True f_i = LazyTensor(f[:, None, :]) g_i = LazyTensor(g[:, None, :]) h_i = LazyTensor(h[:, None, :]) f_ref = f.detach().clone() g_ref = g.detach().clone() h_ref = h.detach().clone() f_ref.requires_grad = True g_ref.requires_grad = True h_ref.requires_grad = True # Values first = lambda x: x.sqrt() second = lambda x: x * x * x val = f_i.ifelse(first(g_i), second(h_i)).sum(dim=0) val_refs = torch.zeros_like(f_ref) val_refs[f_ref >= 0] = first(g_ref[f_ref >= 0]) val_refs[f_ref < 0] = second(h_ref[f_ref < 0]) val_ref = val_refs.sum(dim=0) print("Checking values") print(f"|val - val_ref|: {(val - val_ref).abs()}\n") assert torch.allclose(val, val_ref) # Gradients val.backward() val_ref.backward() print("Checking gradients:") print(f"f: max(|grad|): {f.grad.abs().max()}\n") assert torch.allclose(f.grad, torch.zeros_like(f.grad)) print(f"g: max(|grad - grad_ref|): {(g.grad - g_ref.grad).abs().max()}\n") print(f"h: max(|grad - grad_ref|): {(h.grad - h_ref.grad).abs().max()}\n") assert torch.allclose(f.grad, torch.zeros_like(f.grad))
keops-main
pykeops/pykeops/sandbox/test_ifelse.py
keops-main
pykeops/pykeops/examples/__init__.py
""" KernelSolve reduction (with LazyTensors) ======================================== Let's see how to solve discrete deconvolution problems using the **conjugate gradient solver** provided by the :meth:`pykeops.numpy.LazyTensor.solve` method of KeOps :class:`pykeops.numpy.LazyTensor`. """ ############################################################################### # Setup # ---------------- # # Standard imports: # import time import matplotlib.pyplot as plt import numpy as np from pykeops.numpy import Vi, Vj, Pm import pykeops.config ############################################################################### # Define our dataset: # N = 5000 if pykeops.config.gpu_available else 500 # Number of points D = 2 # Dimension of the ambient space Dv = 2 # Dimension of the vectors (= number of linear problems to solve) sigma = 0.1 # Radius of our RBF kernel x = np.random.rand(N, D) b = np.random.rand(N, Dv) g = np.array([0.5 / sigma**2]) # Parameter of the Gaussian RBF kernel alpha = 0.01 ############################################################################### # KeOps internal conjugate gradient solver # ---------------------------------------- # print("Solving a Gaussian linear system, with {} points in dimension {}.".format(N, D)) start = time.time() Kxx = (-Pm(g) * Vi(x).sqdist(Vj(x))).exp() c = Kxx.solve(Vi(b), alpha=alpha) end = time.time() print("Timing (KeOps implementation):", round(end - start, 5), "s") ############################################################################### # .. note:: # The :meth:`pykeops.numpy.LazyTensor.solve` method uses a conjugate gradient solver and assumes # that **Kxx** defines a **symmetric**, positive and definite # **linear** reduction with respect to the alias ``"b"`` # specified trough the third argument. # # Apply our solver on arbitrary point clouds: # ############################################################################### # Scipy conjugate gradient # ------------------------ from scipy.sparse import diags from scipy.sparse.linalg import aslinearoperator, cg from scipy.sparse.linalg.interface import IdentityOperator print("Solving a Gaussian linear system, with {} points in dimension {}.".format(N, D)) start = time.time() A = aslinearoperator(diags(alpha * np.ones(N))) + aslinearoperator(Kxx) c_sp = np.zeros((N, Dv)) for i in range(Dv): c_sp[:, i] = cg(A, b[:, i])[0] end = time.time() print("Timing (KeOps + scipy implementation):", round(end - start, 5), "s") ############################################################################### # Compare with a straightforward Numpy implementation: # start = time.time() K_xx = alpha * np.eye(N) + np.exp( -g * np.sum((x[:, None, :] - x[None, :, :]) ** 2, axis=2) ) c_np = np.linalg.solve(K_xx, b) end = time.time() print("Timing (Numpy implementation):", round(end - start, 5), "s") print("Relative error (KeOps) = ", np.linalg.norm(c - c_np) / np.linalg.norm(c)) print("Relative error (KeOps + scipy)= ", np.linalg.norm(c - c_sp) / np.linalg.norm(c)) # Plot the results next to each other: for i in range(Dv): plt.subplot(Dv, 1, i + 1) plt.plot(c[:40, i], "-", label="KeOps") plt.plot(c_sp[:40, i], "--", label="KeOps + Scipy") plt.plot(c_np[:40, i], "--", label="NumPy") plt.legend(loc="lower right") plt.tight_layout() plt.show()
keops-main
pykeops/pykeops/examples/numpy/plot_test_invkernel_numpy_helper.py
""" KernelSolve reduction =========================== Let's see how to solve discrete deconvolution problems using the **conjugate gradient solver** provided by :class:`numpy.KernelSolve <pykeops.numpy.KernelSolve>`. """ ############################################################################### # Setup # ---------------- # # Standard imports: # import numpy as np import time import matplotlib.pyplot as plt from pykeops.numpy import KernelSolve import pykeops.config ############################################################################### # Define our dataset: # N = 5000 if pykeops.config.gpu_available else 500 # Number of points D = 2 # Dimension of the ambient space Dv = 2 # Dimension of the vectors (= number of linear problems to solve) sigma = 0.1 # Radius of our RBF kernel dtype = "float32" x = np.random.rand(N, D).astype(dtype) b = np.random.rand(N, Dv).astype(dtype) g = np.array([0.5 / sigma**2]).astype(dtype) # Parameter of the Gaussian RBF kernel ############################################################################### # KeOps kernel # --------------- # # Define a Gaussian RBF kernel: # formula = "Exp(- g * SqDist(x,y)) * b" aliases = [ "x = Vi(" + str(D) + ")", # First arg: i-variable of size D "y = Vj(" + str(D) + ")", # Second arg: j-variable of size D "b = Vj(" + str(Dv) + ")", # Third arg: j-variable of size Dv "g = Pm(1)", ] # Fourth arg: scalar parameter ############################################################################### # Define the inverse kernel operation, with a ridge regularization **alpha**: # alpha = 0.01 Kinv = KernelSolve(formula, aliases, "b", axis=1, dtype=dtype) ############################################################################### # .. note:: # This operator uses a conjugate gradient solver and assumes # that **formula** defines a **symmetric**, positive and definite # **linear** reduction with respect to the alias ``"b"`` # specified trough the third argument. # # Apply our solver on arbitrary point clouds: # # Warmup of gpu Kinv(x, x, b, g, alpha=alpha) print("Solving a Gaussian linear system, with {} points in dimension {}.".format(N, D)) start = time.time() c = Kinv(x, x, b, g, alpha=alpha) end = time.time() print("Timing (KeOps implementation):", round(end - start, 5), "s") ############################################################################### # Compare with a straightforward Numpy implementation: # start = time.time() K_xx = alpha * np.eye(N) + np.exp( -g * np.sum((x[:, None, :] - x[None, :, :]) ** 2, axis=2) ) c_np = np.linalg.solve(K_xx, b) end = time.time() print("Timing (Numpy implementation):", round(end - start, 5), "s") print("Relative error = ", np.linalg.norm(c - c_np) / np.linalg.norm(c_np)) # Plot the results next to each other: for i in range(Dv): plt.subplot(Dv, 1, i + 1) plt.plot(c[:40, i], "-", label="KeOps") plt.plot(c_np[:40, i], "--", label="NumPy") plt.legend(loc="lower right") plt.tight_layout() plt.show()
keops-main
pykeops/pykeops/examples/numpy/plot_test_invkernel_numpy.py
""" SumSoftMaxWeight reduction (with LazyTensors) =================================================== """ ############################################################################### # Using the :mod:`pykeops.numpy.Genred` API, # we show how to perform a computation specified through: # # * Its **inputs**: # # - :math:`x`, an array of size :math:`M\times 3` made up of :math:`M` vectors in :math:`\mathbb R^3`, # - :math:`y`, an array of size :math:`N\times 3` made up of :math:`N` vectors in :math:`\mathbb R^3`, # - :math:`b`, an array of size :math:`N\times 2` made up of :math:`N` vectors in :math:`\mathbb R^2`. # # * Its **output**: # # - :math:`c`, an array of size :math:`M\times 2` made up of # :math:`M` vectors in :math:`\mathbb R^2` such that # # .. math:: # # c_i = \frac{\sum_j \exp(K(x_i,y_j))\,\cdot\,b_j }{\sum_j \exp(K(x_i,y_j))}, # # with :math:`K(x_i,y_j) = \|x_i-y_j\|^2`. # ############################################################################### # Setup # ---------------- # # Standard imports: import time import matplotlib.pyplot as plt import numpy as np from pykeops.numpy import LazyTensor as kf from pykeops.numpy import Vi, Vj from pykeops.numpy.utils import WarmUpGpu ############################################################################### # Define our dataset: # M = 5000 # Number of "i" points N = 4000 # Number of "j" points D = 3 # Dimension of the ambient space Dv = 2 # Dimension of the vectors x = 2 * np.random.randn(M, D) y = 2 * np.random.randn(N, D) b = np.random.rand(N, Dv) # KeOps implementation with the helper WarmUpGpu() start = time.time() c = kf.sum((Vi(x) - Vj(y)) ** 2, axis=2) c = kf.sumsoftmaxweight(c, Vj(b), axis=1) print("Timing (KeOps implementation): ", round(time.time() - start, 5), "s") # compare with direct implementation start = time.time() cc = np.sum((x[:, None, :] - y[None, :, :]) ** 2, axis=2) cc -= np.max(cc, axis=1)[:, None] # Subtract the max to prevent numeric overflows cc = np.exp(cc) @ b / np.sum(np.exp(cc), axis=1)[:, None] print("Timing (Numpy implementation): ", round(time.time() - start, 5), "s") print("Relative error : ", (np.linalg.norm(c - cc) / np.linalg.norm(c)).item()) # Plot the results next to each other: for i in range(Dv): plt.subplot(Dv, 1, i + 1) plt.plot(c[:40, i], "-", label="KeOps") plt.plot(cc[:40, i], "--", label="NumPy") plt.legend(loc="lower right") plt.tight_layout() plt.show()
keops-main
pykeops/pykeops/examples/numpy/plot_test_softmax_numpy_helper.py
""" Sum reduction ===================== """ #################################################################### # Let's compute the (3000,3) tensor :math:`c` whose entries # :math:`c_i^u` are given by: # # .. math:: # c_i^u = \sum_j (p-a_j)^2 \exp(x_i^u+y_j^u) # # where # # * :math:`x` is a (3000,3) tensor, with entries :math:`x_i^u`. # * :math:`y` is a (5000,3) tensor, with entries :math:`y_j^u`. # * :math:`a` is a (5000,1) tensor, with entries :math:`a_j`. # * :math:`p` is a scalar, encoded as a vector of size (1,). # #################################################################### # Setup # ----- # # Standard imports: import matplotlib.pyplot as plt import numpy as np from pykeops.numpy import Genred ##################################################################### # Declare random inputs: M = 30 N = 50 dtype = "float32" # May be 'float32' or 'float64' x = np.random.randn(M, 3).astype(dtype) y = np.random.randn(N, 3).astype(dtype) a = np.random.randn(N, 1).astype(dtype) p = np.random.randn(1).astype(dtype) #################################################################### # Define a custom formula # ----------------------- formula = "Square(p-a)*Exp(x+y)" variables = [ "x = Vi(3)", # First arg : i-variable, of size 3 "y = Vj(3)", # Second arg : j-variable, of size 3 "a = Vj(1)", # Third arg : j-variable, of size 1 (scalar) "p = Pm(1)", ] # Fourth arg : Parameter, of size 1 (scalar) #################################################################### # Our sum reduction is performed over the index :math:`j`, # i.e. on the axis ``1`` of the kernel matrix. # The output c is an :math:`x`-variable indexed by :math:`i`. my_routine = Genred(formula, variables, reduction_op="Sum", axis=1) c = my_routine(x, y, a, p, backend="auto") #################################################################### # The equivalent code in NumPy: c_np = ( ( (p - a.T)[:, np.newaxis] ** 2 * np.exp(x.T[:, :, np.newaxis] + y.T[:, np.newaxis, :]) ) .sum(2) .T ) # Plot the results next to each other: for i in range(3): plt.subplot(3, 1, i + 1) plt.plot(c[:40, i], "-", label="KeOps") plt.plot(c_np[:40, i], "--", label="NumPy") plt.legend(loc="lower right") plt.tight_layout() plt.show() #################################################################### # Compute the gradient # -------------------- # Now, let's compute the gradient of :math:`c` with # respect to :math:`y`. Since :math:`c` is not scalar valued, # its "gradient" :math:`\partial c` should be understood as the adjoint of the # differential operator, i.e. as the linear operator that: # # - takes as input a new tensor :math:`e` with the shape of :math:`c` # - outputs a tensor :math:`g` with the shape of :math:`y` # # such that for all variation :math:`\delta y` of :math:`y` we have: # # .. math:: # # \langle \text{d} c . \delta y , e \rangle = \langle g , \delta y \rangle = \langle \delta y , \partial c . e \rangle # # Backpropagation is all about computing the tensor :math:`g=\partial c . e` efficiently, for arbitrary values of :math:`e`: # Declare a new tensor of shape (M,3) used as the input of the gradient operator. # It can be understood as a "gradient with respect to the output c" # and is thus called "grad_output" in the documentation of PyTorch. e = np.random.randn(M, 3).astype(dtype) #################################################################### # KeOps provides an autodiff engine for formulas. Unfortunately though, as NumPy does not provide any support for backpropagation, we need to specify some informations by hand and add the gradient operator around the formula: ``Grad(formula , variable_to_differentiate, input_of_the_gradient)`` formula_grad = "Grad(" + formula + ", y, e)" # This new formula makes use of a new variable (the input tensor e) variables_grad = variables + [ "e = Vi(3)" ] # Fifth arg: an i-variable of size 3... Just like "c"! # The summation is done with respect to the 'i' index (axis=0) in order to get a 'j'-variable my_grad = Genred(formula_grad, variables_grad, reduction_op="Sum", axis=0) g = my_grad(x, y, a, p, e) #################################################################### # To generate an equivalent code in numpy, we must compute explicitly the adjoint # of the differential (a.k.a. the derivative). # To do so, let see :math:`c^i_u` as a function of :math:`y_j`: # # .. math:: # # g_j^u = [(\partial_{y} c^u(y)) . e^u]_j = \sum_{i} (p-a_j)^2 \exp(x_i^u+y_j^u) \cdot e_i^u # # and implement the formula: g_np = ( ( (p - a.T)[:, np.newaxis, :] ** 2 * np.exp(x.T[:, :, np.newaxis] + y.T[:, np.newaxis, :]) * e.T[:, :, np.newaxis] ) .sum(1) .T ) # Plot the results next to each other: for i in range(3): plt.subplot(3, 1, i + 1) plt.plot(g[:40, i], "-", label="KeOps") plt.plot(g_np[:40, i], "--", label="NumPy") plt.legend(loc="lower right") plt.tight_layout() plt.show()
keops-main
pykeops/pykeops/examples/numpy/plot_generic_syntax_numpy.py
""" SumSoftMaxWeight reduction ========================== """ ############################################################################### # Using the :class:`numpy.Genred <pykeops.numpy.Genred>` class, # we show how to perform a computation specified through: # # * Its **inputs**: # # - :math:`x`, an array of size :math:`M\times 3` made up of :math:`M` vectors in :math:`\mathbb R^3`, # - :math:`y`, an array of size :math:`N\times 3` made up of :math:`N` vectors in :math:`\mathbb R^3`, # - :math:`b`, an array of size :math:`N\times 2` made up of :math:`N` vectors in :math:`\mathbb R^2`. # # * Its **output**: # # - :math:`c`, an array of size :math:`M\times 2` made up of # :math:`M` vectors in :math:`\mathbb R^2` such that # # .. math:: # # c_i = \frac{\sum_j \exp(K(x_i,y_j))\,\cdot\,b_j }{\sum_j \exp(K(x_i,y_j))}, # # with :math:`K(x_i,y_j) = \|x_i-y_j\|^2`. # ############################################################################### # Setup # ---------------- # # Standard imports: import time import numpy as np from pykeops.numpy import Genred import matplotlib.pyplot as plt ############################################################################### # Define our dataset: # M = 5000 # Number of "i" points N = 4000 # Number of "j" points D = 3 # Dimension of the ambient space Dv = 2 # Dimension of the vectors x = 2 * np.random.randn(M, D) y = 2 * np.random.randn(N, D) b = np.random.rand(N, Dv) ############################################################################### # KeOps kernel # --------------- # # Create a new generic routine using the :class:`numpy.Genred <pykeops.numpy.Genred>` # constructor: formula = "SqDist(x,y)" formula_weights = "b" aliases = [ "x = Vi(" + str(D) + ")", # First arg: i-variable of size D "y = Vj(" + str(D) + ")", # Second arg: j-variable of size D "b = Vj(" + str(Dv) + ")", ] # Third arg: j-variable of size Dv softmax_op = Genred( formula, aliases, reduction_op="SumSoftMaxWeight", axis=1, formula2=formula_weights ) # Dummy first call to warmup the GPU and get accurate timings: _ = softmax_op(x, y, b) ############################################################################### # Use our new function on arbitrary Numpy arrays: # start = time.time() c = softmax_op(x, y, b) print("Timing (KeOps implementation): ", round(time.time() - start, 5), "s") # compare with direct implementation start = time.time() cc = np.sum((x[:, None, :] - y[None, :, :]) ** 2, axis=2) cc -= np.max(cc, axis=1)[:, None] # Subtract the max to prevent numeric overflows cc = np.exp(cc) @ b / np.sum(np.exp(cc), axis=1)[:, None] print("Timing (Numpy implementation): ", round(time.time() - start, 5), "s") print("Relative error : ", (np.linalg.norm(c - cc) / np.linalg.norm(c)).item()) # Plot the results next to each other: for i in range(Dv): plt.subplot(Dv, 1, i + 1) plt.plot(c[:40, i], "-", label="KeOps") plt.plot(cc[:40, i], "--", label="NumPy") plt.legend(loc="lower right") plt.tight_layout() plt.show()
keops-main
pykeops/pykeops/examples/numpy/plot_test_softmax_numpy.py
""" Block-sparse reductions =========================== This script showcases the use of the optional **ranges** argument to compute block-sparse reductions with **sub-quadratic time complexity**. """ ######################################################################## # Setup # ------------ # Standard imports: # import time import numpy as np from matplotlib import pyplot as plt from pykeops.numpy import LazyTensor import pykeops.config dtype = "float32" ######################################################################## # Define our dataset: two point clouds on the unit square. # M, N = (5000, 5000) if pykeops.config.gpu_available else (2000, 2000) t = np.linspace(0, 2 * np.pi, M + 1)[:-1] x = np.stack((0.4 + 0.4 * (t / 7) * np.cos(t), 0.5 + 0.3 * np.sin(t)), 1) x = x + 0.01 * np.random.randn(*x.shape) x = x.astype(dtype) y = np.random.randn(N, 2).astype(dtype) y = y / 10 + np.array([0.6, 0.6]).astype(dtype) #################################################################### # Computing a block-sparse reduction # --------------------------------------- # # On the GPU, **contiguous memory accesses** are key to high performances. # To enable the implementation of algorithms with **sub-quadratic time complexity** # under this constraint, KeOps provides access to # **block-sparse reduction routines** through the optional # **ranges** argument, which is supported by :class:`numpy.Genred <pykeops.numpy.Genred>` # and all its children. # # Pre-processing # ~~~~~~~~~~~~~~~~~~~ # # To leverage this feature through the :mod:`pykeops.torch` API, # the first step is to **clusterize your data** # into groups which should neither be too **small** (performances on clusters # with less than ~200 points each are suboptimal) # nor too **many** (the :func:`from_matrix() <pykeops.numpy.cluster.from_matrix>` # pre-processor can become a bottleneck when working with >2,000 clusters # per point cloud). # # In this tutorial, we use the :func:`grid_cluster() <pykeops.numpy.cluster.grid_cluster>` # routine which simply groups points into **cubic bins** of arbitrary size: from pykeops.numpy.cluster import grid_cluster eps = 0.05 # Size of our square bins Start = time.time() start = time.time() x_labels = grid_cluster(x, eps) # class labels y_labels = grid_cluster(y, eps) # class labels end = time.time() print("Perform clustering : {:.4f}s".format(end - start)) ########################################################################## # Once (integer) cluster labels have been computed, # we can compute the **centroids** and **memory footprint** of each class: from pykeops.numpy.cluster import cluster_ranges_centroids # Compute one range and centroid per class: start = time.time() x_ranges, x_centroids, _ = cluster_ranges_centroids(x, x_labels) y_ranges, y_centroids, _ = cluster_ranges_centroids(y, y_labels) end = time.time() print("Compute ranges+centroids : {:.4f}s".format(end - start)) ######################################################################### # Finally, we can **sort** our points according to their # labels, making sure that **all clusters are stored contiguously in memory**: from pykeops.numpy.cluster import sort_clusters start = time.time() x, x_labels = sort_clusters(x, x_labels) y, y_labels = sort_clusters(y, y_labels) end = time.time() print("Sort the points : {:.4f}s".format(end - start)) #################################################################### # Cluster-Cluster binary mask # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # The key idea behind KeOps's block-sparsity mode # is that as soon as data points are sorted, # **we can manage the reduction scheme through a small, coarse boolean mask** # whose values encode whether or not we should perform computations # at a finer scale. # # In this example, we compute a simple Gaussian # convolution of radius :math:`\sigma` # and decide to **skip** points-to-points **interactions** between # blocks whose **centroids are further apart** than :math:`4\sigma`, # as :math:`\exp(- (4\sigma)^2 / 2\sigma^2 ) = e^{-8} \ll 1`, # with 99% of the mass of a Gaussian kernel located in the :math:`3\sigma` range. sigma = 0.05 # Characteristic length of interaction start = time.time() # Compute a coarse Boolean mask: D = np.sum((x_centroids[:, None, :] - y_centroids[None, :, :]) ** 2, 2) keep = D < (4 * sigma) ** 2 ############################################################################## # To turn this mask into a set of integer Tensors which # is more palatable to KeOps's low-level CUDA API, # we then use the :func:`from_matrix <pykeops.numpy.cluster.from_matrix>` # routine... from pykeops.numpy.cluster import from_matrix ranges_ij = from_matrix(x_ranges, y_ranges, keep) end = time.time() print("Process the ranges : {:.4f}s".format(end - start)) End = time.time() t_cluster = End - Start print("Total time (synchronized): {:.4f}s".format(End - Start)) print("") ############################################################################### # And we're done: here is the **ranges** argument that can # be fed to the KeOps reduction routines! # For large point clouds, we can expect a speed-up that is directly # proportional to the ratio of mass between our **fine binary mask** # (encoded in **ranges_ij**) and the full, N-by-M kernel matrix: areas = (x_ranges[:, 1] - x_ranges[:, 0])[:, None] * (y_ranges[:, 1] - y_ranges[:, 0])[ None, : ] total_area = np.sum(areas) # should be equal to N*M sparse_area = np.sum(areas[keep]) print( "We keep {:.2e}/{:.2e} = {:2d}% of the original kernel matrix.".format( sparse_area, total_area, int(100 * sparse_area / total_area) ) ) print("") #################################################################### # Benchmark a block-sparse Gaussian convolution # ------------------------------------------------- # # Define a Gaussian kernel matrix from 2d point clouds: x_, y_ = x / sigma, y / sigma x_i, y_j = LazyTensor(x_[:, None, :]), LazyTensor(y_[None, :, :]) D_ij = ((x_i - y_j) ** 2).sum(dim=2) # Symbolic (M,N,1) matrix of squared distances K = (-D_ij / 2).exp() # Symbolic (M,N,1) Gaussian kernel matrix ##################################################################### # And create a random signal supported by the points :math:`y_j`: b = np.random.randn(N, 1).astype(dtype) ############################################################################## # Compare the performances of our **block-sparse** code # with those of a **dense** implementation, on both CPU and GPU backends: # # .. note:: # The standard KeOps routine are already *very* efficient: # on the GPU, speed-ups with multiscale, block-sparse schemes only start to # kick on around the "20,000 points" mark as the skipped computations # make up for the clustering and branching overheads. # backends = ( (["CPU", "GPU"] if M * N < 4e8 else ["GPU"]) if pykeops.config.gpu_available else ["CPU"] ) for backend in backends: K.backend = backend # Switch to CPU or GPU mode # GPU warm-up: a = K @ b start = time.time() K.ranges = None # default a_full = K @ b end = time.time() t_full = end - start print(" Full convolution, {} backend: {:2.4f}s".format(backend, end - start)) start = time.time() K.ranges = ranges_ij # block-sparsity pattern a_sparse = K @ b end = time.time() t_sparse = end - start print("Sparse convolution, {} backend: {:2.4f}s".format(backend, end - start)) print( "Relative time : {:3d}% ({:3d}% including clustering), ".format( int(100 * t_sparse / t_full), int(100 * (t_sparse + t_cluster) / t_full) ) ) print( "Relative error: {:3.4f}%".format( 100 * np.sum(np.abs(a_sparse - a_full)) / np.sum(np.abs(a_full)) ) ) print("") #################################################################### # Fancy visualization: we display our coarse binary mask # and highlight one of its lines, that corresponds to the **cyan** cluster # and its **magenta** neighbors: # # Find the cluster centroid which is closest to the (.43,.6) point: dist_target = np.sum(((x_centroids - np.array([0.43, 0.6]).astype(dtype)) ** 2), axis=1) clust_i = np.argmin(dist_target) if M + N <= 500000: ranges_i, slices_j, redranges_j = ranges_ij[0:3] start_i, end_i = ranges_i[clust_i] # Indices of the points that make up our cluster start, end = ( slices_j[clust_i - 1], slices_j[clust_i], ) # Ranges of the cluster's neighbors keep = keep.astype(float) keep[clust_i] += 2 plt.ion() plt.matshow(keep) plt.figure(figsize=(10, 10)) plt.scatter( x[:, 0], x[:, 1], c=x_labels, cmap=plt.cm.Wistia, s=25 * 500 / len(x), label="Target points", ) plt.scatter( y[:, 0], y[:, 1], c=y_labels, cmap=plt.cm.winter, s=25 * 500 / len(y), label="Source points", ) # Target clusters: for start_j, end_j in redranges_j[start:end]: plt.scatter( y[start_j:end_j, 0], y[start_j:end_j, 1], c="magenta", s=50 * 500 / len(y) ) # Source cluster: plt.scatter( x[start_i:end_i, 0], x[start_i:end_i, 1], c="cyan", s=10, label="Cluster {}".format(clust_i), ) plt.scatter( x_centroids[:, 0], x_centroids[:, 1], c="black", s=10, alpha=0.5, label="Cluster centroids", ) plt.legend(loc="lower right") # sphinx_gallery_thumbnail_number = 2 plt.axis("equal") plt.axis([0, 1, 0, 1]) plt.tight_layout() plt.show(block=True)
keops-main
pykeops/pykeops/examples/numpy/plot_grid_cluster_numpy.py
""" Arg-K-Min reduction =================== Using the :mod:`pykeops.numpy` API, we define a dataset of N points in :math:`\mathbb R^D` and compute for each point the indices of its K nearest neighbours (including itself). """ ############################################################### # Setup # ---------- # # Standard imports: import time import matplotlib.pyplot as plt import numpy as np from pykeops.numpy import Genred ############################################################### # Define our dataset: N = 100000 # Number of points D = 2 # Dimension of the ambient space K = 3 # Number of neighbors to look for dtype = "float32" # May be 'float32' or 'float64' x = np.random.rand(N, D).astype(dtype) ############################################################### # KeOps Kernel # ------------- formula = "SqDist(x,y)" # Use a simple Euclidean (squared) norm variables = [ "x = Vi(" + str(D) + ")", # First arg : i-variable, of size D "y = Vj(" + str(D) + ")", ] # Second arg: j-variable, of size D # N.B.: The number K is specified as an optional argument `opt_arg` my_routine = Genred(formula, variables, reduction_op="ArgKMin", axis=1, opt_arg=K) ############################################################### # Using our new :class:`pykeops.numpy.Genred` routine, # we perform a K-nearest neighbor search ( **reduction_op** = ``"ArgKMin"`` ) # over the :math:`j` variable :math:`y_j` ( **axis** = 1): # # .. note:: # If CUDA is available and **backend** is ``"auto"`` or not specified, # KeOps will: # # 1. Load the data on the GPU # 2. Perform the computation on the device # 3. Unload the result back to the CPU # # as it is assumed to be most efficient for large-scale problems. # By specifying **backend** = ``"CPU"`` in the call to ``my_routine``, # you can bypass this procedure and use a simple C++ ``for`` loop instead. # Dummy first call to warm-up the GPU and thus get an accurate timing: my_routine(np.random.rand(10, D).astype(dtype), np.random.rand(10, D).astype(dtype)) # Actually perform our K-nn search: start = time.time() ind = my_routine(x, x, backend="auto") print("Time to perform the K-nn search: ", round(time.time() - start, 5), "s") # The result is now an (N,K) array of integers: print("Output values :") print(ind) plt.figure(figsize=(8, 8)) plt.scatter(x[:, 0], x[:, 1], s=25 * 500 / len(x)) for k in range(K): # Highlight some points and their nearest neighbors plt.scatter(x[ind[:4, k], 0], x[ind[:4, k], 1], s=100) plt.axis("equal") plt.axis([0, 1, 0, 1]) plt.tight_layout() plt.show()
keops-main
pykeops/pykeops/examples/numpy/plot_test_ArgKMin.py
""" ============= GPU Selection ============= On multi-device clusters, let's see how to select the card on which a KeOps operation will be performed. """ ############################################################### # Setup # ------------- # Standard imports: import matplotlib.pyplot as plt import numpy as np from pykeops.numpy import Genred, Vi, Vj from pykeops.common.gpu_utils import get_gpu_number import pykeops.config #################################################################### # Define the list of gpu ids to be tested: # By default we assume that there are two GPUs available with 0 and 1 labels: gpuids = [0, 1] if get_gpu_number() > 1 else [0] #################################################################### # KeOps Kernel using Genred # ------------------------- # Define some arbitrary KeOps routine: formula = "Square(p-a) * Exp(x+y)" variables = ["x = Vi(3)", "y = Vj(3)", "a = Vj(1)", "p = Pm(1)"] dtype = "float32" # May be 'float32' or 'float64' my_routine = Genred(formula, variables, reduction_op="Sum", axis=1) #################################################################### # Generate some data, stored on the CPU (host) memory: # M = 1000 N = 2000 x = np.random.randn(M, 3).astype(dtype) y = np.random.randn(N, 3).astype(dtype) a = np.random.randn(N, 1).astype(dtype) p = np.random.randn(1).astype(dtype) #################################################################### # Launch our routine on the CPU: # c = my_routine(x, y, a, p, backend="CPU") #################################################################### # And on our GPUs, with copies between # the Host and Device memories: # if pykeops.config.gpu_available: for gpuid in gpuids: d = my_routine(x, y, a, p, backend="GPU", device_id=gpuid) print( "Relative error on gpu {}: {:1.3e}".format( gpuid, float(np.sum(np.abs(c - d)) / np.sum(np.abs(c))) ) ) # Plot the results next to each other: for i in range(3): plt.subplot(3, 1, i + 1) plt.plot(c[:40, i], "-", label="CPU") plt.plot(d[:40, i], "--", label="GPU {}".format(gpuid)) plt.legend(loc="lower right") plt.tight_layout() plt.show() #################################################################### # Using LazyTensor # ---------------- # Launch our routine on the CPU: # xi, yj, aj = Vi(x), Vj(y), Vj(a) # c = ((p - aj) ** 2 * (xi + yj).exp()).sum(axis=1, backend="CPU") c = ((aj - p) ** 2 * (yj + xi).exp()).sum(axis=1, backend="CPU") #################################################################### # And on the GPUs, with copies between the Host and Device memories: # if pykeops.config.gpu_available: for gpuid in gpuids: d = ((p - aj) ** 2 * (xi + yj).exp()).sum( axis=1, backend="GPU", device_id=gpuid ) print( "Relative error on gpu {}: {:1.3e}".format( gpuid, float(np.sum(np.abs(c - d)) / np.sum(np.abs(c))) ) ) # Plot the results next to each other: for i in range(3): plt.subplot(3, 1, i + 1) plt.plot(c[:40, i], "-", label="CPU") plt.plot(d[:40, i], "--", label="GPU {}".format(gpuid)) plt.legend(loc="lower right") plt.tight_layout() plt.show()
keops-main
pykeops/pykeops/examples/numpy/plot_gpu_select_numpy.py
""" Advanced syntax in formulas =========================== Let's write generic formulas using the KeOps syntax. """ #################################################################### # Setup # ------------------ # First, the standard imports: import torch from pykeops.torch import Genred import matplotlib.pyplot as plt # Choose the storage place for our data : CPU (host) or GPU (device) memory. device = torch.device("cuda" if torch.cuda.is_available() else "cpu") #################################################################### # Then, the definition of our dataset: # # - :math:`p`, a vector of size 2. # - :math:`x = (x_i)`, an N-by-D array. # - :math:`y = (y_j)`, an M-by-D array. N = 1000 M = 2000 D = 3 # PyTorch tip: do not 'require_grad' of 'x' if you do not intend to # actually compute a gradient wrt. said variable 'x'. # Given this info, PyTorch (+ KeOps) is smart enough to # skip the computation of unneeded gradients. p = torch.randn(2, requires_grad=True, device=device) x = torch.randn(N, D, requires_grad=False, device=device) y = torch.randn(M, D, requires_grad=True, device=device) # + some random gradient to backprop: g = torch.randn(N, D, requires_grad=True, device=device) #################################################################### # Computing an arbitrary formula # ------------------------------------- # # Thanks to the `Elem` operator, # we can now compute :math:`(a_i)`, an N-by-D array given by: # # .. math:: # # a_i = \sum_{j=1}^M (\langle x_i,y_j \rangle^2) (p_0 x_i + p_1 y_j) # # where the two real parameters are stored in a 2-vector :math:`p=(p_0,p_1)`. # Keops implementation. # Note that Square(...) is more efficient than Pow(...,2) formula = "Square((X|Y)) * ((Elem(P, 0) * X) + (Elem(P, 1) * Y))" variables = [ "P = Pm(2)", # 1st argument, a parameter, dim 2. "X = Vi(3)", # 2nd argument, indexed by i, dim D. "Y = Vj(3)", ] # 3rd argument, indexed by j, dim D. my_routine = Genred(formula, variables, reduction_op="Sum", axis=1) a_keops = my_routine(p, x, y) # Vanilla PyTorch implementation scals = (torch.mm(x, y.t())) ** 2 # Memory-intensive computation! a_pytorch = p[0] * scals.sum(1).view(-1, 1) * x + p[1] * (torch.mm(scals, y)) # Plot the results next to each other: for i in range(D): plt.subplot(D, 1, i + 1) plt.plot(a_keops.detach().cpu().numpy()[:40, i], "-", label="KeOps") plt.plot(a_pytorch.detach().cpu().numpy()[:40, i], "--", label="PyTorch") plt.legend(loc="lower right") plt.tight_layout() plt.show()
keops-main
pykeops/pykeops/examples/pytorch/plot_advanced_formula.py
""" Vectorial LogSumExp reduction ========================================= """ #################################################################### # Let's compute the (3000,1) tensor :math:`c` whose entries # :math:`c_i` are given by: # # .. math:: # c_i = \log \left[ \sum_j \exp\left( (p-a_j)^2 \exp(x_i+y_j) \right) b_j\right] # # where # # * :math:`x` is a (3000,1) tensor, with entries :math:`x_i`. # * :math:`y` is a (5000,1) tensor, with entries :math:`y_j`. # * :math:`a` is a (5000,1) tensor, with entries :math:`a_j`. # * :math:`p` is a scalar, encoded as a vector of size (1,). # * :math:`b` is a (5000,3) tensor, with entries :math:`b_j`. # #################################################################### # Setup # ----- # # Standard imports: import time import matplotlib.pyplot as plt import torch from torch.autograd import grad from pykeops.torch import Genred ##################################################################### # Declare random inputs: M = 3000 N = 5000 dtype = "float32" # Could be 'float32' or 'float64' torchtype = torch.float32 if dtype == "float32" else torch.float64 x = torch.rand(M, 1, dtype=torchtype) y = torch.rand(N, 1, dtype=torchtype, requires_grad=True) a = torch.rand(N, 1, dtype=torchtype) p = torch.rand(1, dtype=torchtype) b = torch.rand(N, 3, dtype=torchtype) #################################################################### # Define a custom formula # ----------------------- formula = "Square(p-a)*Exp(x+y)" formula2 = "b" variables = [ "x = Vi(1)", # First arg : i-variable, of size 1 (scalar) "y = Vj(1)", # Second arg : j-variable, of size 1 (scalar) "a = Vj(1)", # Third arg : j-variable, of size 1 (scalar) "p = Pm(1)", # Fourth arg : Parameter, of size 1 (scalar) "b = Vj(3)", ] # Fifth arg : j-variable, of size 3 (vector) start = time.time() #################################################################### # Our log-sum-exp reduction is performed over the index :math:`j`, # i.e. on the axis ``1`` of the kernel matrix. # The output c is an :math:`x`-variable indexed by :math:`i`. my_routine = Genred( formula, variables, reduction_op="LogSumExp", axis=1, dtype=dtype, formula2=formula2 ) c = my_routine(x, y, a, p, b, backend="CPU") # N.B.: By specifying backend='CPU', we can make sure that the result is computed using a simple C++ for loop. print( "Time to compute the convolution operation on the cpu: ", round(time.time() - start, 5), "s", end=" ", ) ####################################################################### # We compare with the unstable, naive computation "Log of Sum of Exp": my_routine2 = Genred( "Exp(" + formula + ")*" + formula2, variables, reduction_op="Sum", axis=1, dtype=dtype, ) c2 = torch.log(my_routine2(x, y, a, p, b, backend="CPU")) print("(relative error: ", ((c2 - c).norm() / c.norm()).item(), ")") # Plot the results next to each other: for i in range(3): plt.subplot(3, 1, i + 1) plt.plot(c.detach().cpu().numpy()[:40, i], "-", label="KeOps - Stable") plt.plot(c2.detach().cpu().numpy()[:40, i], "--", label="KeOps - Unstable") plt.legend(loc="lower right") plt.tight_layout() plt.show() #################################################################### # Compute the gradient # -------------------- # Now, let's compute the gradient of :math:`c` with # respect to :math:`y`. Since :math:`c` is not scalar valued, # its "gradient" :math:`\partial c` should be understood as the adjoint of the # differential operator, i.e. as the linear operator that: # # - takes as input a new tensor :math:`e` with the shape of :math:`c` # - outputs a tensor :math:`g` with the shape of :math:`y` # # such that for all variation :math:`\delta y` of :math:`y` we have: # # .. math:: # # \langle \text{d} c . \delta y , e \rangle = \langle g , \delta y \rangle = \langle \delta y , \partial c . e \rangle # # Backpropagation is all about computing the tensor :math:`g=\partial c . e` efficiently, for arbitrary values of :math:`e`: # Declare a new tensor of shape (M,1) used as the input of the gradient operator. # It can be understood as a "gradient with respect to the output c" # and is thus called "grad_output" in the documentation of PyTorch. e = torch.rand_like(c) # Call the gradient op: start = time.time() g = grad(c, y, e)[0] # PyTorch remark : grad(c, y, e) alone outputs a length 1 tuple, hence the need for [0] at the end. print( "Time to compute gradient of convolution operation on the cpu: ", round(time.time() - start, 5), "s", end=" ", ) #################################################################### # We compare with gradient of Log of Sum of Exp: g2 = grad(c2, y, e)[0] print("(relative error: ", ((g2 - g).norm() / g.norm()).item(), ")") # Plot the results next to each other: plt.plot(g.detach().cpu().numpy()[:40], "-", label="KeOps - Stable") plt.plot(g2.detach().cpu().numpy()[:40], "--", label="KeOps - Unstable") plt.legend(loc="lower right") plt.tight_layout() plt.show() #################################################################### # Same operations performed on the Gpu # ------------------------------------ # # Of course, this will only work if you own a Gpu... if torch.cuda.is_available(): # first transfer data on gpu pc, ac, xc, yc, bc, ec = p.cuda(), a.cuda(), x.cuda(), y.cuda(), b.cuda(), e.cuda() # then call the operations start = time.time() c3 = my_routine(xc, yc, ac, pc, bc, backend="GPU") print( "Time to compute convolution operation on the gpu:", round(time.time() - start, 5), "s ", end="", ) print("(relative error:", float(torch.abs((c2 - c3.cpu()) / c2).mean()), ")") start = time.time() g3 = grad(c3, yc, ec)[0] print( "Time to compute gradient of convolution operation on the gpu:", round(time.time() - start, 5), "s ", end="", ) print("(relative error:", float(torch.abs((g2 - g3.cpu()) / g2).mean()), ")") # Plot the results next to each other: for i in range(3): plt.subplot(3, 1, i + 1) plt.plot(c.detach().cpu().numpy()[:40, i], "-", label="KeOps - CPU") plt.plot(c3.detach().cpu().numpy()[:40, i], "--", label="KeOps - GPU") plt.legend(loc="lower right") plt.tight_layout() plt.show() # Plot the results next to each other: plt.plot(g.detach().cpu().numpy()[:40], "-", label="KeOps - CPU") plt.plot(g3.detach().cpu().numpy()[:40], "--", label="KeOps - GPU") plt.legend(loc="lower right") plt.tight_layout() plt.show()
keops-main
pykeops/pykeops/examples/pytorch/plot_generic_syntax_pytorch_LSE_vect.py
""" LogSumExp reduction ============================== """ #################################################################### # Let's compute the (3000,1) tensor :math:`c` whose entries # :math:`c_i` are given by: # # .. math:: # c_i = \log \left[ \sum_j \exp\left( (p-a_j)^2 \exp(x_i+y_j) \right) \right] # # where # # * :math:`x` is a (3000,1) tensor, with entries :math:`x_i`. # * :math:`y` is a (5000,1) tensor, with entries :math:`y_j`. # * :math:`a` is a (5000,1) tensor, with entries :math:`a_j`. # * :math:`p` is a scalar, encoded as a vector of size (1,). # #################################################################### # Setup # ----- # # Standard imports: import time import torch from matplotlib import pyplot as plt from torch.autograd import grad from pykeops.torch import Genred ##################################################################### # Declare random inputs: M = 3000 N = 5000 dtype = "float32" # Could be 'float32' or 'float64' torchtype = torch.float32 if dtype == "float32" else torch.float64 x = torch.rand(M, 1, dtype=torchtype) y = torch.rand(N, 1, dtype=torchtype, requires_grad=True) a = torch.rand(N, 1, dtype=torchtype) p = torch.rand(1, dtype=torchtype) #################################################################### # Define a custom formula # ----------------------- formula = "Square(p-a)*Exp(x+y)" variables = [ "x = Vi(1)", # First arg : i-variable, of size 1 (scalar) "y = Vj(1)", # Second arg : j-variable, of size 1 (scalar) "a = Vj(1)", # Third arg : j-variable, of size 1 (scalar) "p = Pm(1)", ] # Fourth arg : Parameter, of size 1 (scalar) start = time.time() #################################################################### # Our log-sum-exp reduction is performed over the index :math:`j`, # i.e. on the axis ``1`` of the kernel matrix. # The output c is an :math:`x`-variable indexed by :math:`i`. my_routine = Genred(formula, variables, reduction_op="LogSumExp", axis=1) c = my_routine(x, y, a, p, backend="CPU") # N.B.: By specifying backend='CPU', we can make sure that the result is computed using a simple C++ for loop. print( "Time to compute the convolution operation on the cpu: ", round(time.time() - start, 5), "s", end=" ", ) ####################################################################### # We compare with the unstable, naive computation "Log of Sum of Exp": my_routine2 = Genred( "Exp(" + formula + ")", variables, reduction_op="Sum", axis=1, dtype=dtype ) c2 = torch.log(my_routine2(x, y, a, p, backend="CPU")) print("(relative error: ", ((c2 - c).norm() / c.norm()).item(), ")") # Plot the results next to each other: plt.plot(c.detach().cpu().numpy()[:40], "-", label="KeOps - Stable") plt.plot(c2.detach().cpu().numpy()[:40], "--", label="KeOps - Unstable") plt.legend(loc="lower right") plt.tight_layout() plt.show() #################################################################### # Compute the gradient # -------------------- # Now, let's compute the gradient of :math:`c` with # respect to :math:`y`. Since :math:`c` is not scalar valued, # its "gradient" :math:`\partial c` should be understood as the adjoint of the # differential operator, i.e. as the linear operator that: # # - takes as input a new tensor :math:`e` with the shape of :math:`c` # - outputs a tensor :math:`g` with the shape of :math:`y` # # such that for all variation :math:`\delta y` of :math:`y` we have: # # .. math:: # # \langle \text{d} c . \delta y , e \rangle = \langle g , \delta y \rangle = \langle \delta y , \partial c . e \rangle # # Backpropagation is all about computing the tensor :math:`g=\partial c . e` efficiently, for arbitrary values of :math:`e`: # Declare a new tensor of shape (M,1) used as the input of the gradient operator. # It can be understood as a "gradient with respect to the output c" # and is thus called "grad_output" in the documentation of PyTorch. e = torch.rand_like(c) # Call the gradient op: start = time.time() g = grad(c, y, e)[0] # PyTorch remark : grad(c, y, e) alone outputs a length 1 tuple, hence the need for [0] at the end. print( "Time to compute gradient of convolution operation on the cpu: ", round(time.time() - start, 5), "s", end=" ", ) #################################################################### # We compare with gradient of Log of Sum of Exp: g2 = grad(c2, y, e)[0] print("(relative error: ", ((g2 - g).norm() / g.norm()).item(), ")") # Plot the results next to each other: plt.plot(g.detach().cpu().numpy()[:40], "-", label="KeOps - Stable") plt.plot(g2.detach().cpu().numpy()[:40], "--", label="KeOps - Unstable") plt.legend(loc="lower right") plt.tight_layout() plt.show() #################################################################### # Same operations performed on the Gpu # ------------------------------------ # # Of course, this will only work if you own a Gpu... if torch.cuda.is_available(): # first transfer data on gpu pc, ac, xc, yc, ec = p.cuda(), a.cuda(), x.cuda(), y.cuda(), e.cuda() # then call the operations start = time.time() c3 = my_routine(xc, yc, ac, pc, backend="GPU") print( "Time to compute convolution operation on the gpu:", round(time.time() - start, 5), "s ", end="", ) print("(relative error:", float(torch.abs((c2 - c3.cpu()) / c2).mean()), ")") start = time.time() g3 = grad(c3, yc, ec)[0] print( "Time to compute gradient of convolution operation on the gpu:", round(time.time() - start, 5), "s ", end="", ) print("(relative error:", float(torch.abs((g2 - g3.cpu()) / g2).mean()), ")") # Plot the results next to each other: plt.plot(c.detach().cpu().numpy()[:40], "-", label="KeOps - CPU") plt.plot(c3.detach().cpu().numpy()[:40], "--", label="KeOps - GPU") plt.legend(loc="lower right") plt.tight_layout() plt.show() # Plot the results next to each other: plt.plot(g.detach().cpu().numpy()[:40], "-", label="KeOps - CPU") plt.plot(g3.detach().cpu().numpy()[:40], "--", label="KeOps - GPU") plt.legend(loc="lower right") plt.tight_layout() plt.show()
keops-main
pykeops/pykeops/examples/pytorch/plot_generic_syntax_pytorch_LSE.py
""" Anisotropic kernels =================== Let's see how to encode anisotropic kernels with a minimal amount of effort. """ ############################################## # Setup # ------- # # Standard imports: import numpy as np from matplotlib import pyplot as plt import matplotlib.cm as cm import torch from pykeops.torch import Vi, Vj, Pm, LazyTensor ############################################## # Dataset: # Choose the storage place for our data : CPU (host) or GPU (device) memory. dtype = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor # Three points in the plane R^2 y = torch.tensor([[0.2, 0.7], [0.5, 0.3], [0.7, 0.5]]).type(dtype) # Three scalar weights b = torch.tensor([1.0, 1.0, 0.5]).type(dtype) # Remember that KeOps is super-picky on the input shapes: # b is not a vector, but a 'list of unidimensional vectors'! b = b.view(-1, 1) # Create a uniform grid on the unit square: res = 100 ticks = np.linspace(0, 1, res + 1)[:-1] + 0.5 / res X, Y = np.meshgrid(ticks, ticks) # Beware! By default, numpy uses float64 precision whereas pytorch uses float32. # If you don't convert explicitely your data to compatible dtypes, # PyTorch or Keops will throw an error. x = torch.from_numpy(np.vstack((X.ravel(), Y.ravel())).T).contiguous().type(dtype) ############################################### # Kernel definition # --------------------- # Let's use a **Gaussian kernel** given through # # .. math:: # # k(x_i,y_j) = \exp( -\|x - y\|_{\Gamma}^2) = \exp( - (x_i - y_j)^t \Gamma (x_i-y_j) ), # # which is equivalent to the KeOps formula ``exp(-WeightedSquareNorm(gamma, x_i-y_j ))``. # Using the high-level :class:`pykeops.torch.LazyTensor`, we can simply define: def plot_kernel(gamma): """Samples 'x -> ∑_j b_j * k_j(x - y_j)' on the grid, and displays it as a heatmap.""" if gamma.dim() == 2: heatmap = (-Vi(x).weightedsqdist(Vj(y), Vj(gamma))).exp() @ b else: heatmap = (-Vi(x).weightedsqdist(Vj(y), Pm(gamma))).exp() @ b heatmap = heatmap.view(res, res).cpu().numpy() # reshape as a 'background' image plt.imshow( -heatmap, interpolation="bilinear", origin="lower", vmin=-1, vmax=1, cmap=cm.RdBu, extent=(0, 1, 0, 1), ) plt.show() ############################################### # The precise meaning of the computation is then defined through the entry ``gamma``, # which will is to be used as a 'metric multiplier'. Denoting ``D == x.shape[1] == y.shape[1]`` the size of the feature space, the integer ``K`` can be ``1``, ``D`` or ``D*D``. Rules are: # # - if ``gamma`` is a vector (``gamma.shape = [K]``), it is seen as a fixed parameter # - if ``gamma`` is a 2d-tensor (``gamma.shape = [M,K]``), it is seen as a ``j``-variable # # N.B.: Beware of ``Shape([K]) != Shape([1,K])`` confusions! ############################################### # # Isotropic Kernels # ----------------- # # If ``K == 1`` (ie ``gamma`` is a float): :math:`\Gamma = \gamma Id_D` is a scalar factor in front of a simple Euclidean squared norm. In this case, ``WeightedSquareNorm(gamma, x-y )`` corresponds to # # .. math:: # # \|x - y\|_{\Gamma}^2 = \gamma \|x-y\|^2 ################################################ # Uniform kernels # ^^^^^^^^^^^^^^^ # # Providing a single scalar we get uniform kernels sigma = torch.tensor([0.1]).type(dtype) gamma = 1.0 / sigma**2 plt.plot() plot_kernel(gamma) ############################################### # Variable kernels # ^^^^^^^^^^^^^^^^ # # Providing a list of scalar we get variable kernels sigma = torch.tensor([[0.15], [0.07], [0.3]]).type(dtype) gamma = 1.0 / sigma**2 plot_kernel(gamma) ############################################### # Diagonal Kernels # ---------------- # # If ``K == D`` (ie ``gamma`` is a vector): :math:`\Gamma = \text{diag}(\gamma)` is a diagonal matrix. In that case, ``WeightedSquareNorm(gamma, x-y)`` corresponds to # # .. math:: # # \|x - y\|_{\Gamma}^2 = \langle (x-y), \Gamma (x-y) \rangle = \langle (x-y), \text{diag}(\gamma) (x-y) \rangle = \sum_d \gamma_d (x_d-y_d)^2 ############################################### # Uniform kernels # ^^^^^^^^^^^^^^^ # # Providing a single vector we get uniform kernels sigma = torch.tensor([0.2, 0.1]).type(dtype) gamma = 1.0 / sigma**2 plot_kernel(gamma) ############################################### # Variable kernels # ^^^^^^^^^^^^^^^^ # # Providing a list of vector (ie a 2d-tensor) we get variable kernels sigma = torch.tensor([[0.2, 0.1], [0.05, 0.15], [0.2, 0.2]]).type(dtype) gamma = 1.0 / sigma**2 plot_kernel(gamma) ############################################### # Fully-Anisotropic kernels # ------------------------- # # If ``K == D*D`` (ie ``gamma`` is a vector of size the dimension of the ambiant space squared): :math:`\Gamma` is a symmetric matrix whose entries are stored in :math:`\gamma`. In that case, ``WeightedSquareNorm(gamma, x-y)`` corresponds to # # .. math:: # # \|x - y\|_{\Gamma}^2 = \langle (x-y), \Gamma (x-y) \rangle = \sum_{k}\sum_{\ell} g_{k,\ell} (x_k-y_k)(x_\ell-y_\ell) ) ############################################### # Uniform kernels # ^^^^^^^^^^^^^^^ # # Providing a single vector we get uniform kernels Sigma = torch.tensor([1 / 0.2**2, 1 / 0.25**2, 1 / 0.25**2, 1 / 0.1**2]).type( dtype ) gamma = Sigma plot_kernel(gamma) ############################################### # Variable kernels # ^^^^^^^^^^^^^^^^ # # Providing a list of vector (ie a 2d-tensor) we get variable kernels Sigma = torch.tensor( [ [1 / 0.2**2, 1 / 0.25**2, 1 / 0.25**2, 1 / 0.1**2], [1 / 0.1**2, 0, 0, 1 / 0.12**2], [1 / 0.3**2, -1 / 0.25**2, -1 / 0.25**2, 1 / 0.12**2], ] ).type(dtype) gamma = Sigma # sphinx_gallery_thumbnail_number = 6 plot_kernel(gamma)
keops-main
pykeops/pykeops/examples/pytorch/plot_anisotropic_kernels.py
""" ============= GPU Selection ============= On multi-device clusters, let's see how to make use of several Gpus for further speedups """ ############################################################### # Setup # ------------- # Standard imports: import math import time import torch from pykeops.torch import LazyTensor from concurrent.futures import ThreadPoolExecutor, wait ############################################################### # Define the number of gpus ngpus = torch.cuda.device_count() ############################################################### # Generate some data, stored on the CPU (host) memory: # M = 1000000 N = 1000000 x = torch.randn(M, 3) y = torch.randn(N, 3) ############################################################### # Define a symbolic gaussian kernel # reduction using LazyTensor syntax # def GaussKernelSum(x, y, gpuid=-1): x_i = LazyTensor(x[:, None, :]) # x_i.shape = (M, 1, 3) y_j = LazyTensor(y[None, :, :]) # y_j.shape = (1, N, 3) D_ij = ((x_i - y_j) ** 2).sum(dim=2) # Symbolic (M,N,1) matrix of squared distances K_ij = (-D_ij).exp() # Symbolic (M,N,1) Gaussian kernel matrix return K_ij.sum(dim=1, device_id=gpuid) ############################################################### # dummy calls to the routine # for gpuid in range(ngpus): GaussKernelSum(x[:100, :], y[:100, :], gpuid) ############################################################### # Compute on several GPUs in parallel, # (block parallelizing over the reduction index) # start = time.time() pool = ThreadPoolExecutor(ngpus) subsize_y = math.ceil(N / ngpus) futures = [] for gpuid in range(ngpus): y_chunk = y[gpuid * subsize_y : (gpuid + 1) * subsize_y, :] future = pool.submit(GaussKernelSum, x, y_chunk, gpuid) futures.append(future) wait(futures) out_multi_1 = 0 for gpuid in range(ngpus): out_multi_1 += futures[gpuid].result().cpu() elapsed = time.time() - start print( "time for multi-Gpu computation (block parallelized over reduction index):{:.2f} s".format( elapsed ) ) ############################################################### # Compute on several GPUs in parallel, # (block parallelizing over the output index) # start = time.time() pool = ThreadPoolExecutor(ngpus) subsize_y = math.ceil(N / ngpus) futures = [] for gpuid in range(ngpus): x_chunk = x[gpuid * subsize_y : (gpuid + 1) * subsize_y, :] future = pool.submit(GaussKernelSum, x_chunk, y, gpuid) futures.append(future) wait(futures) out_multi_2 = torch.zeros(M, 3) for gpuid in range(ngpus): out_multi_2[gpuid * subsize_y : (gpuid + 1) * subsize_y, :] = ( futures[gpuid].result().cpu() ) elapsed = time.time() - start print( "time for multi-Gpu computation (block parallelized over output index):{:.2f} s".format( elapsed ) ) ######################################### # Compare with single Gpu computation # start = time.time() out_single = GaussKernelSum(x, y) elapsed = time.time() - start print("time for single-Gpu computation: {:.2f} s".format(elapsed)) ######################################### # Check outputs are the same # rel_err1 = (torch.norm(out_single - out_multi_1) / torch.norm(out_single)).item() rel_err2 = (torch.norm(out_single - out_multi_2) / torch.norm(out_single)).item() print("relative errors: {:.1e}, {:.1e}".format(rel_err1, rel_err2))
keops-main
pykeops/pykeops/examples/pytorch/plot_multi_gpu.py
""" KernelSolve reduction =========================== Let's see how to solve discrete deconvolution problems using the **conjugate gradient solver** provided by :class:`pykeops.torch.KernelSolve`. """ ############################################################################### # Setup # ---------------- # # Standard imports: # import time import torch from matplotlib import pyplot as plt from pykeops.torch import KernelSolve if torch.__version__ >= "1.8": torchsolve = lambda A, B: torch.linalg.solve(A, B) else: torchsolve = lambda A, B: torch.solve(B, A)[0] ############################################################################### # Define our dataset: # N = 5000 if torch.cuda.is_available() else 500 # Number of points D = 2 # Dimension of the ambient space Dv = 2 # Dimension of the vectors (= number of linear problems to solve) sigma = 0.1 # Radius of our RBF kernel x = torch.rand(N, D, requires_grad=True) b = torch.rand(N, Dv) g = torch.Tensor([0.5 / sigma**2]) # Parameter of the Gaussian RBF kernel if torch.cuda.is_available(): sync = torch.cuda.synchronize else: def sync(): pass ############################################################################### # KeOps kernel # --------------- # # Define a Gaussian RBF kernel: # formula = "Exp(- g * SqDist(x,y)) * b" aliases = [ "x = Vi(" + str(D) + ")", # First arg: i-variable of size D "y = Vj(" + str(D) + ")", # Second arg: j-variable of size D "b = Vj(" + str(Dv) + ")", # Third arg: j-variable of size Dv "g = Pm(1)", ] # Fourth arg: scalar parameter ############################################################################### # Define the inverse kernel operation, with a ridge regularization **alpha**: # alpha = 0.01 Kinv = KernelSolve(formula, aliases, "b", axis=1) ############################################################################### # .. note:: # This operator uses a conjugate gradient solver and assumes # that **formula** defines a **symmetric**, positive and definite # **linear** reduction with respect to the alias ``"b"`` # specified trough the third argument. # # Apply our solver on arbitrary point clouds: # print("Solving a Gaussian linear system, with {} points in dimension {}.".format(N, D)) sync() start = time.time() c = Kinv(x, x, b, g, alpha=alpha) sync() end = time.time() print("Timing (KeOps implementation):", round(end - start, 5), "s") ############################################################################### # Compare with a straightforward PyTorch implementation: # sync() start = time.time() K_xx = alpha * torch.eye(N) + torch.exp( -torch.sum((x[:, None, :] - x[None, :, :]) ** 2, dim=2) / (2 * sigma**2) ) c_py = torchsolve(K_xx, b) sync() end = time.time() print("Timing (PyTorch implementation):", round(end - start, 5), "s") print("Relative error = ", (torch.norm(c - c_py) / torch.norm(c_py)).item()) # Plot the results next to each other: for i in range(Dv): plt.subplot(Dv, 1, i + 1) plt.plot(c.cpu().detach().numpy()[:40, i], "-", label="KeOps") plt.plot(c_py.cpu().detach().numpy()[:40, i], "--", label="PyTorch") plt.legend(loc="lower right") plt.tight_layout() plt.show() ############################################################################### # Compare the derivatives: # print("1st order derivative") e = torch.randn(N, D) start = time.time() (u,) = torch.autograd.grad(c, x, e) end = time.time() print("Timing (KeOps derivative):", round(end - start, 5), "s") start = time.time() (u_py,) = torch.autograd.grad(c_py, x, e) end = time.time() print("Timing (PyTorch derivative):", round(end - start, 5), "s") print("Relative error = ", (torch.norm(u - u_py) / torch.norm(u_py)).item()) # Plot the results next to each other: for i in range(Dv): plt.subplot(Dv, 1, i + 1) plt.plot(u.cpu().detach().numpy()[:40, i], "-", label="KeOps") plt.plot(u_py.cpu().detach().numpy()[:40, i], "--", label="PyTorch") plt.legend(loc="lower right") plt.tight_layout() plt.show()
keops-main
pykeops/pykeops/examples/pytorch/plot_test_invkernel_torch.py
""" SumSoftMaxWeight reduction =========================== """ ############################################################################### # Using the :class:`torch.Genred <pykeops.torch.Genred>` API, # we show how to perform a computation specified through: # # * Its **inputs**: # # - :math:`x`, an array of size :math:`M\times 3` made up of :math:`M` vectors in :math:`\mathbb R^3`, # - :math:`y`, an array of size :math:`N\times 3` made up of :math:`N` vectors in :math:`\mathbb R^3`, # - :math:`b`, an array of size :math:`N\times 2` made up of :math:`N` vectors in :math:`\mathbb R^2`. # # * Its **output**: # # - :math:`c`, an array of size :math:`M\times 2` made up of # :math:`M` vectors in :math:`\mathbb R^2` such that # # .. math:: # # c_i = \frac{\sum_j \exp(K(x_i,y_j))\,\cdot\,b_j }{\sum_j \exp(K(x_i,y_j))}, # # with :math:`K(x_i,y_j) = \|x_i-y_j\|^2`. # ############################################################################### # Setup # ---------------- # # Standard imports: import time import torch from matplotlib import pyplot as plt from pykeops.torch import Genred ############################################################################### # Define our dataset: # M = 500 # Number of "i" points N = 400 # Number of "j" points D = 3 # Dimension of the ambient space Dv = 2 # Dimension of the vectors x = 2 * torch.randn(M, D) y = 2 * torch.randn(N, D) b = torch.rand(N, Dv) ############################################################################### # KeOps kernel # --------------- # # Create a new generic routine using the :class:`pykeops.numpy.Genred` # constructor: formula = "SqDist(x,y)" formula_weights = "b" aliases = [ "x = Vi(" + str(D) + ")", # First arg: i-variable of size D "y = Vj(" + str(D) + ")", # Second arg: j-variable of size D "b = Vj(" + str(Dv) + ")", ] # Third arg: j-variable of size Dv softmax_op = Genred( formula, aliases, reduction_op="SumSoftMaxWeight", axis=1, formula2=formula_weights ) # Dummy first call to warmup the GPU and get accurate timings: _ = softmax_op(x, y, b) ############################################################################### # Use our new function on arbitrary Numpy arrays: # start = time.time() c = softmax_op(x, y, b) print("Timing (KeOps implementation): ", round(time.time() - start, 5), "s") # compare with direct implementation start = time.time() cc = torch.sum((x[:, None, :] - y[None, :, :]) ** 2, 2) cc -= torch.max(cc, dim=1)[0][:, None] # subtract the max for robustness cc = torch.exp(cc) @ b / torch.sum(torch.exp(cc), dim=1)[:, None] print("Timing (PyTorch implementation): ", round(time.time() - start, 5), "s") print("Relative error : ", (torch.norm(c - cc) / torch.norm(c)).item()) # Plot the results next to each other: for i in range(Dv): plt.subplot(Dv, 1, i + 1) plt.plot(c.cpu().detach().numpy()[:40, i], "-", label="KeOps") plt.plot(cc.cpu().detach().numpy()[:40, i], "--", label="PyTorch") plt.legend(loc="lower right") plt.tight_layout() plt.show()
keops-main
pykeops/pykeops/examples/pytorch/plot_test_softmax_torch.py
""" ========= Multi GPU ========= On multi-device clusters, let's see how to select the card on which a KeOps operation will be performed. """ ############################################################### # Setup # ------------- # Standard imports: import numpy as np import torch from matplotlib import pyplot as plt from pykeops.numpy import Genred ############################################################### # Define the list of gpu ids to be tested: # By default we assume that there are two GPUs available with 0 and 1 labels: gpuids = [0, 1] if torch.cuda.device_count() > 1 else [0] ############################################################### # KeOps Kernel # ------------- # Define some arbitrary KeOps routine: formula = "Square(p-a) * Exp(x+y)" variables = ["x = Vi(3)", "y = Vj(3)", "a = Vj(1)", "p = Pm(1)"] dtype = "float32" # May be 'float32' or 'float64' ############################################################### # Tests with the NumPy API # ------------------------------ my_routine = Genred(formula, variables, reduction_op="Sum", axis=1, dtype=dtype) ############################################################### # Generate some data, stored on the CPU (host) memory: # M = 3000 N = 5000 x = np.random.randn(M, 3).astype(dtype) y = np.random.randn(N, 3).astype(dtype) a = np.random.randn(N, 1).astype(dtype) p = np.random.randn(1).astype(dtype) ######################################### # Launch our routine on the CPU, for reference: # c = my_routine(x, y, a, p, backend="CPU") ######################################### # And on our GPUs, with copies between # the Host and Device memories: # for gpuid in gpuids: d = my_routine(x, y, a, p, backend="GPU", device_id=gpuid) print( "Relative error on gpu {}: {:1.3e}".format( gpuid, float(np.mean(np.abs((c - d) / c))) ) ) # Plot the results next to each other: for i in range(3): plt.subplot(3, 1, i + 1) plt.plot(c[:40, i], "-", label="CPU") plt.plot(d[:40, i], "--", label="GPU {}".format(gpuid)) plt.legend(loc="lower right") plt.tight_layout() plt.show() ############################################################### # Tests with the PyTorch API # --------------------------- import torch from pykeops.torch import Genred my_routine = Genred(formula, variables, reduction_op="Sum", axis=1, dtype=dtype) ########################################### # First, we keep the data on the CPU (host) memory: # x = torch.from_numpy(x) y = torch.from_numpy(y) a = torch.from_numpy(a) p = torch.from_numpy(p) c = torch.from_numpy(c) for gpuid in gpuids: d = my_routine(x, y, a, p, backend="GPU", device_id=gpuid) print( "Relative error on gpu {}: {:1.3e}".format( gpuid, float(torch.abs((c - d.cpu()) / c).mean()) ) ) # Plot the results next to each other: for i in range(3): plt.subplot(3, 1, i + 1) plt.plot(c.cpu().numpy()[:40, i], "-", label="CPU") plt.plot(d.cpu().numpy()[:40, i], "--", label="GPU {}".format(gpuid)) plt.legend(loc="lower right") plt.tight_layout() plt.show() ########################################### # Second, we load the data on the GPU (device) of our choice # and let KeOps infer the **device_id** automatically: for gpuid in gpuids: with torch.cuda.device(gpuid): # Transfer the data from Host to Device memory. # N.B.: The first call to ".cuda()" may take several seconds for each device. # This is a known PyTorch issue. p, a, x, y = p.cuda(), a.cuda(), x.cuda(), y.cuda() # Call our KeOps routine: d = my_routine(x, y, a, p, backend="GPU") print( "Relative error on gpu {}: {:1.3e}".format( gpuid, float(torch.abs((c - d.cpu()) / c).mean()) ) ) # Plot the results next to each other: for i in range(3): plt.subplot(3, 1, i + 1) plt.plot(c.cpu().numpy()[:40, i], "-", label="CPU") plt.plot(d.cpu().numpy()[:40, i], "--", label="GPU {}".format(gpuid)) plt.legend(loc="lower right") plt.tight_layout() plt.show()
keops-main
pykeops/pykeops/examples/pytorch/plot_gpu_select_example.py
""" Block-sparse reductions =========================== This script showcases the use of the optional **ranges** argument to compute block-sparse reductions with **sub-quadratic time complexity**. """ ######################################################################## # Setup # ------------ # Standard imports: # import time import numpy as np import torch from matplotlib import pyplot as plt from pykeops.torch import LazyTensor nump = lambda t: t.cpu().numpy() use_cuda = torch.cuda.is_available() dtype = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor ######################################################################### # Define our dataset: two point clouds on the unit square. # M, N = (5000, 5000) if use_cuda else (2000, 2000) t = torch.linspace(0, 2 * np.pi, M + 1)[:-1] x = torch.stack((0.4 + 0.4 * (t / 7) * t.cos(), 0.5 + 0.3 * t.sin()), 1) x = x + 0.01 * torch.randn(x.shape) x = x.type(dtype) y = torch.randn(N, 2).type(dtype) y = y / 10 + dtype([0.6, 0.6]) #################################################################### # Computing a block-sparse reduction # --------------------------------------- # # On the GPU, **contiguous memory accesses** are key to high performances. # To enable the implementation of algorithms with **sub-quadratic time complexity** # under this constraint, KeOps provides access to # **block-sparse reduction routines** through the optional # **ranges** argument, which is supported by :class:`torch.Genred <pykeops.torch.Genred>` # and all its children. # # Pre-processing # ^^^^^^^^^^^^^^ # # To leverage this feature through the :mod:`pykeops.torch` API, # the first step is to **clusterize your data** # into groups which should neither be too **small** (performances on clusters # with less than ~200 points each are suboptimal) # nor too **many** (the :func:`from_matrix() <pykeops.torch.cluster.from_matrix>` # pre-processor can become a bottleneck when working with >2,000 clusters # per point cloud). # # In this tutorial, we use the :func:`grid_cluster() <pykeops.torch.cluster.grid_cluster>` # routine which simply groups points into **cubic bins** of arbitrary size: from pykeops.torch.cluster import grid_cluster eps = 0.05 # Size of our square bins if use_cuda: torch.cuda.synchronize() Start = time.time() start = time.time() x_labels = grid_cluster(x, eps) # class labels y_labels = grid_cluster(y, eps) # class labels if use_cuda: torch.cuda.synchronize() end = time.time() print("Perform clustering : {:.4f}s".format(end - start)) ############################################### # Once (integer) cluster labels have been computed, # we can compute the **centroids** and **memory footprint** of each class: from pykeops.torch.cluster import cluster_ranges_centroids # Compute one range and centroid per class: start = time.time() x_ranges, x_centroids, _ = cluster_ranges_centroids(x, x_labels) y_ranges, y_centroids, _ = cluster_ranges_centroids(y, y_labels) if use_cuda: torch.cuda.synchronize() end = time.time() print("Compute ranges+centroids : {:.4f}s".format(end - start)) ############################################### # Finally, we can **sort** our points according to their # labels, making sure that **all clusters are stored contiguously in memory**: from pykeops.torch.cluster import sort_clusters start = time.time() x, x_labels = sort_clusters(x, x_labels) y, y_labels = sort_clusters(y, y_labels) if use_cuda: torch.cuda.synchronize() end = time.time() print("Sort the points : {:.4f}s".format(end - start)) #################################################################### # Cluster-Cluster binary mask # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ # # The key idea behind KeOps's block-sparsity mode # is that as soon as data points are sorted, # **we can manage the reduction scheme through a small, coarse boolean mask** # whose values encode whether or not we should perform computations # at a finer scale. # # In this example, we compute a simple Gaussian # convolution of radius :math:`\sigma` # and decide to **skip** points-to-points **interactions** between # blocks whose **centroids are further apart** than :math:`4\sigma`, # as :math:`\exp(- (4\sigma)^2 / 2\sigma^2 ) = e^{-8} \ll 1`, # with 99% of the mass of a Gaussian kernel located in the :math:`3\sigma` range. sigma = 0.05 # Characteristic length of interaction start = time.time() # Compute a coarse Boolean mask: D = ((x_centroids[:, None, :] - y_centroids[None, :, :]) ** 2).sum(2) keep = D < (4 * sigma) ** 2 ######################################## # To turn this mask into a set of integer Tensors which # is more palatable to KeOps's low-level CUDA API, # we then use the :func:`from_matrix <pykeops.torch.cluster.from_matrix>` # routine... from pykeops.torch.cluster import from_matrix ranges_ij = from_matrix(x_ranges, y_ranges, keep) if use_cuda: torch.cuda.synchronize() end = time.time() print("Process the ranges : {:.4f}s".format(end - start)) if use_cuda: torch.cuda.synchronize() End = time.time() t_cluster = End - Start print("Total time (synchronized): {:.4f}s".format(End - Start)) print("") ######################################## # And we're done: here is the **ranges** argument that can # be fed to the KeOps reduction routines! # For large point clouds, we can expect a speed-up that is directly # proportional to the ratio of mass between our **fine binary mask** # (encoded in **ranges_ij**) and the full, N-by-M kernel matrix: areas = (x_ranges[:, 1] - x_ranges[:, 0])[:, None] * (y_ranges[:, 1] - y_ranges[:, 0])[ None, : ] total_area = areas.sum().item() # should be equal to N*M sparse_area = areas[keep].sum().item() print( "We keep {:.2e}/{:.2e} = {:2d}% of the original kernel matrix.".format( sparse_area, total_area, int(100 * sparse_area / total_area) ) ) print("") #################################################################### # Benchmark a block-sparse Gaussian convolution # ------------------------------------------------- # # Define a Gaussian kernel matrix from 2d point clouds: x_, y_ = x / sigma, y / sigma x_i, y_j = LazyTensor(x_[:, None, :]), LazyTensor(y_[None, :, :]) D_ij = ((x_i - y_j) ** 2).sum(dim=2) # Symbolic (M,N,1) matrix of squared distances K = (-D_ij / 2).exp() # Symbolic (M,N,1) Gaussian kernel matrix ##################################################################### # And create a random signal supported by the points :math:`y_j`: b = torch.randn(N, 1).type(dtype) ####################################################### # Compare the performances of our **block-sparse** code # with those of a **dense** implementation, on both CPU and GPU backends: # # .. note:: # The standard KeOps routine are already *very* efficient: # on the GPU, speed-ups with multiscale, block-sparse schemes only start to # kick on around the "20,000 points" mark as the skipped computations # make up for the clustering and branching overheads. # backend = "GPU" if use_cuda else "CPU" # GPU warm-up: a = K @ b start = time.time() a_full = K @ b end = time.time() t_full = end - start print(" Full convolution, {} backend: {:2.4f}s".format(backend, end - start)) start = time.time() K.ranges = ranges_ij a_sparse = K @ b end = time.time() t_sparse = end - start print("Sparse convolution, {} backend: {:2.4f}s".format(backend, end - start)) print( "Relative time : {:3d}% ({:3d}% including clustering), ".format( int(100 * t_sparse / t_full), int(100 * (t_sparse + t_cluster) / t_full) ) ) print( "Relative error: {:3.4f}%".format( 100 * (a_sparse - a_full).abs().sum() / a_full.abs().sum() ) ) print("") #################################################################### # Fancy visualization: we display our coarse binary mask # and highlight one of its lines, that corresponds to the **cyan** cluster # and its **magenta** neighbors: # # Find the cluster centroid which is closest to the (.43,.6) point: dist_target = ((x_centroids - torch.Tensor([0.43, 0.6]).type_as(x_centroids)) ** 2).sum( 1 ) clust_i = torch.argmin(dist_target) if M + N <= 500000: ranges_i, slices_j, redranges_j = ranges_ij[0:3] start_i, end_i = ranges_i[clust_i] # Indices of the points that make up our cluster start, end = ( slices_j[clust_i - 1], slices_j[clust_i], ) # Ranges of the cluster's neighbors keep = nump(keep.float()) keep[clust_i] += 2 plt.ion() plt.matshow(keep) plt.figure(figsize=(10, 10)) x, x_labels, x_centroids = nump(x), nump(x_labels), nump(x_centroids) y, y_labels, y_centroids = nump(y), nump(y_labels), nump(y_centroids) plt.scatter( x[:, 0], x[:, 1], c=x_labels, cmap=plt.cm.Wistia, s=25 * 500 / len(x), label="Target points", ) plt.scatter( y[:, 0], y[:, 1], c=y_labels, cmap=plt.cm.winter, s=25 * 500 / len(y), label="Source points", ) # Target clusters: for start_j, end_j in redranges_j[start:end]: plt.scatter( y[start_j:end_j, 0], y[start_j:end_j, 1], c="magenta", s=50 * 500 / len(y) ) # Source cluster: plt.scatter( x[start_i:end_i, 0], x[start_i:end_i, 1], c="cyan", s=10, label="Cluster {}".format(clust_i), ) plt.scatter( x_centroids[:, 0], x_centroids[:, 1], c="black", s=10, alpha=0.5, label="Cluster centroids", ) plt.legend(loc="lower right") # sphinx_gallery_thumbnail_number = 2 plt.axis("equal") plt.axis([0, 1, 0, 1]) plt.tight_layout() plt.show(block=True)
keops-main
pykeops/pykeops/examples/pytorch/plot_grid_cluster_pytorch.py
""" KernelSolve reduction (with LazyTensors) ========================================= Let's see how to solve discrete deconvolution problems using the **conjugate gradient solver** provided by the :meth:`pykeops.torch.LazyTensor.solve` method of KeOps :class:`pykeops.torch.LazyTensor`. """ ############################################################################### # Setup # ---------------- # # Standard imports: # import time import torch from matplotlib import pyplot as plt from pykeops.torch import LazyTensor as keops from pykeops.torch import Vi, Vj ############################################################################### # Define our dataset: # N = 5000 if torch.cuda.is_available() else 500 # Number of points D = 2 # Dimension of the ambient space Dv = 2 # Dimension of the vectors (= number of linear problems to solve) sigma = 0.1 # Radius of our RBF kernel x = torch.rand(N, D, requires_grad=True) b = torch.rand(N, Dv) g = torch.Tensor([0.5 / sigma**2]) # Parameter of the Gaussian RBF kernel alpha = 0.01 # ridge regularization ############################################################################### # .. note:: # This operator uses a conjugate gradient solver and assumes # that **formula** defines a **symmetric**, positive and definite # **linear** reduction with respect to the alias ``"b"`` # specified trough the third argument. # # Apply our solver on arbitrary point clouds: # print("Solving a Gaussian linear system, with {} points in dimension {}.".format(N, D)) start = time.time() K_xx = keops.exp(-keops.sum((Vi(x) - Vj(x)) ** 2, dim=2) / (2 * sigma**2)) cfun = keops.solve(K_xx, Vi(b), alpha=alpha, call=False) c = cfun() end = time.time() print("Timing (KeOps implementation):", round(end - start, 5), "s") ############################################################################### # Compare with a straightforward PyTorch implementation: # start = time.time() K_xx = alpha * torch.eye(N) + torch.exp( -torch.sum((x[:, None, :] - x[None, :, :]) ** 2, dim=2) / (2 * sigma**2) ) c_py = torch.solve(b, K_xx)[0] end = time.time() print("Timing (PyTorch implementation):", round(end - start, 5), "s") print("Relative error = ", (torch.norm(c - c_py) / torch.norm(c_py)).item()) # Plot the results next to each other: for i in range(Dv): plt.subplot(Dv, 1, i + 1) plt.plot(c.cpu().detach().numpy()[:40, i], "-", label="KeOps") plt.plot(c_py.cpu().detach().numpy()[:40, i], "--", label="PyTorch") plt.legend(loc="lower right") plt.tight_layout() plt.show() ############################################################################### # Compare the derivatives: # print(cfun.callfun) print("1st order derivative") e = torch.randn(N, D) start = time.time() (u,) = torch.autograd.grad(c, x, e) end = time.time() print("Timing (KeOps derivative):", round(end - start, 5), "s") start = time.time() (u_py,) = torch.autograd.grad(c_py, x, e) end = time.time() print("Timing (PyTorch derivative):", round(end - start, 5), "s") print("Relative error = ", (torch.norm(u - u_py) / torch.norm(u_py)).item()) # Plot the results next to each other: for i in range(Dv): plt.subplot(Dv, 1, i + 1) plt.plot(u.cpu().detach().numpy()[:40, i], "-", label="KeOps") plt.plot(u_py.cpu().detach().numpy()[:40, i], "--", label="PyTorch") plt.legend(loc="lower right") plt.tight_layout() plt.show()
keops-main
pykeops/pykeops/examples/pytorch/plot_test_invkernel_torch_helper.py
""" Sum reduction ================== """ #################################################################### # Let's compute the (3000,3) tensor :math:`c` whose entries # :math:`c_i^u` are given by: # # .. math:: # c_i^u = \sum_j (p-a_j)^2 \exp(x_i^u+y_j^u) # # where # # * :math:`x` is a (3000,3) tensor, with entries :math:`x_i^u`. # * :math:`y` is a (5000,3) tensor, with entries :math:`y_j^u`. # * :math:`a` is a (5000,1) tensor, with entries :math:`a_j`. # * :math:`p` is a scalar, encoded as a vector of size (1,). # #################################################################### # Setup # ----- # # Standard imports: import time import matplotlib.pyplot as plt import torch from torch.autograd import grad from pykeops.torch import Genred ##################################################################### # Declare random inputs: M = 3000 N = 5000 # Choose the storage place for our data : CPU (host) or GPU (device) memory. device = torch.device("cuda" if torch.cuda.is_available() else "cpu") dtype = "float32" # Could be 'float32' or 'float64' torchtype = torch.float32 if dtype == "float32" else torch.float64 x = torch.randn(M, 3, dtype=torchtype, device=device) y = torch.randn(N, 3, dtype=torchtype, device=device, requires_grad=True) a = torch.randn(N, 1, dtype=torchtype, device=device) p = torch.randn(1, dtype=torchtype, device=device) #################################################################### # Define a custom formula # ----------------------- formula = "Square(p-a)*Exp(x+y)" variables = [ "x = Vi(3)", # First arg : i-variable, of size 3 "y = Vj(3)", # Second arg : j-variable, of size 3 "a = Vj(1)", # Third arg : j-variable, of size 1 (scalar) "p = Pm(1)", ] # Fourth arg : Parameter, of size 1 (scalar) #################################################################### # Our sum reduction is performed over the index :math:`j`, # i.e. on the axis ``1`` of the kernel matrix. # The output c is an :math:`x`-variable indexed by :math:`i`. my_routine = Genred(formula, variables, reduction_op="Sum", axis=1) c = my_routine(x, y, a, p) #################################################################### # Compute the gradient # -------------------- # Now, let's compute the gradient of :math:`c` with # respect to :math:`y`. Since :math:`c` is not scalar valued, # its "gradient" :math:`\partial c` should be understood as the adjoint of the # differential operator, i.e. as the linear operator that: # # - takes as input a new tensor :math:`e` with the shape of :math:`c` # - outputs a tensor :math:`g` with the shape of :math:`y` # # such that for all variation :math:`\delta y` of :math:`y` we have: # # .. math:: # # \langle \text{d} c . \delta y , e \rangle = \langle g , \delta y \rangle = \langle \delta y , \partial c . e \rangle # # Backpropagation is all about computing the tensor :math:`g=\partial c . e` efficiently, for arbitrary values of :math:`e`: # Declare a new tensor of shape (M,3) used as the input of the gradient operator. # It can be understood as a "gradient with respect to the output c" # and is thus called "grad_output" in the documentation of PyTorch. e = torch.rand_like(c) # Call the gradient op: start = time.time() # PyTorch remark : grad(c, y, e) alone outputs a length 1 tuple, hence the need for [0]. g = grad(c, y, e)[0] # g = [∂_y c].e print( "Time to compute gradient of convolution operation with KeOps: ", round(time.time() - start, 5), "s", ) #################################################################### # The equivalent code with a "vanilla" pytorch implementation g_torch = ( ( (p - a.transpose(0, 1))[:, None] ** 2 * torch.exp(x.transpose(0, 1)[:, :, None] + y.transpose(0, 1)[:, None, :]) * e.transpose(0, 1)[:, :, None] ) .sum(dim=1) .transpose(0, 1) ) # Plot the results next to each other: for i in range(3): plt.subplot(3, 1, i + 1) plt.plot(g.detach().cpu().numpy()[:40, i], "-", label="KeOps") plt.plot(g_torch.detach().cpu().numpy()[:40, i], "--", label="PyTorch") plt.legend(loc="lower right") plt.tight_layout() plt.show()
keops-main
pykeops/pykeops/examples/pytorch/plot_generic_syntax_pytorch.py
""" Radial kernels convolutions =========================== This benchmark compares the performances of KeOps versus Numpy and PyTorch on various radial kernels convolutions. Namely it computes: .. math:: a_i = \sum_{j=1}^N f\Big(\\frac{\|x_i-y_j\|}{\sigma}\Big) b_j, \quad \\text{ for all } i=1,\cdots,M where :math:`f` is a Gauss or Cauchy or Laplace or inverse multiquadric kernel. See e.g. `wikipedia <https://en.wikipedia.org/wiki/Radial_basis_function>`_ """ ##################################################################### # Setup # ----- # Standard imports: import numpy as np import timeit import matplotlib from matplotlib import pyplot as plt from pykeops.numpy.utils import np_kernel from pykeops.torch.utils import torch_kernel from pykeops.torch import Vi, Vj, Pm ###################################################################### # Benchmark specifications: # M = 10000 # Number of points x_i N = 10000 # Number of points y_j D = 3 # Dimension of the x_i's and y_j's E = 3 # Dimension of the b_j's REPEAT = 10 # Number of loops per test dtype = "float32" ###################################################################### # Create some random input data: # x = np.random.randn(M, D).astype(dtype) # Target points y = np.random.randn(N, D).astype(dtype) # Source points b = np.random.randn(N, E).astype(dtype) # Source signal sigma = np.array([2.4]).astype(dtype) # Kernel radius ###################################################################### # And load it as PyTorch variables: # try: import torch use_cuda = torch.cuda.is_available() device = "cuda" if use_cuda else "cpu" torchtype = torch.float32 if dtype == "float32" else torch.float64 xc = torch.tensor(x, dtype=torchtype, device=device) yc = torch.tensor(y, dtype=torchtype, device=device) bc = torch.tensor(b, dtype=torchtype, device=device) sigmac = torch.tensor(sigma, dtype=torchtype, device=device) except: pass #################################################################### # Convolution Benchmarks # ---------------------- # # We loop over four different kernels: # kernel_to_test = ["gaussian", "laplacian", "cauchy", "inverse_multiquadric"] kernels = { "gaussian": lambda xc, yc, sigmac: ( -Pm(1 / sigmac**2) * Vi(xc).sqdist(Vj(yc)) ).exp(), "laplacian": lambda xc, yc, sigmac: ( -(Pm(1 / sigmac**2) * Vi(xc).sqdist(Vj(yc))).sqrt() ).exp(), "cauchy": lambda xc, yc, sigmac: ( 1 + Pm(1 / sigmac**2) * Vi(xc).sqdist(Vj(yc)) ).power(-1), "inverse_multiquadric": lambda xc, yc, sigmac: ( 1 + Pm(1 / sigmac**2) * Vi(xc).sqdist(Vj(yc)) ) .sqrt() .power(-1), } ##################################################################### # With four backends: Numpy, vanilla PyTorch, Generic KeOps reductions # and a specific, handmade legacy CUDA code for kernel convolutions: # speed_numpy = {i: np.nan for i in kernel_to_test} speed_pytorch = {i: np.nan for i in kernel_to_test} speed_pykeops = {i: np.nan for i in kernel_to_test} print("Timings for {}x{} convolutions:".format(M, N)) for k in kernel_to_test: print("kernel: " + k) # Pure numpy g_numpy = np.matmul(np_kernel(x, y, sigma, kernel=k), b) speed_numpy[k] = timeit.repeat( "gnumpy = np.matmul( np_kernel(x, y, sigma, kernel=k), b)", globals=globals(), repeat=5, number=1, ) print("Time for NumPy: {:.4f}s".format(np.median(speed_numpy[k]))) # Vanilla pytorch (with cuda if available, and cpu otherwise) try: g_pytorch = torch_kernel(xc, yc, sigmac, kernel=k) @ bc torch.cuda.synchronize() speed_pytorch[k] = ( np.array( timeit.repeat( "torch_kernel(xc, yc, sigmac, kernel=k) @ bc; torch.cuda.synchronize()", globals=globals(), repeat=REPEAT, number=4, ) ) / 4 ) print( "Time for PyTorch: {:.4f}s".format(np.median(speed_pytorch[k])), end="", ) print( " (absolute error: ", np.max(np.abs(g_pytorch.cpu().numpy() - g_numpy)), ")", ) except: print("Time for PyTorch: Not Done") # Keops: LazyTensors implementation (with cuda if available) try: g_pykeops = (kernels[k](xc, yc, sigmac) @ bc).cpu() torch.cuda.synchronize() speed_pykeops[k] = ( np.array( timeit.repeat( "kernels[k](xc, yc, sigmac) @ bc; torch.cuda.synchronize()", globals=globals(), repeat=REPEAT, number=4, ) ) / 4 ) print( "Time for KeOps LazyTensors: {:.4f}s".format( np.median(speed_pykeops[k]) ), end="", ) print( " (absolute error: ", np.max(np.abs(g_pykeops.data.numpy() - g_numpy)), ")", ) except: print("Time for KeOps LazyTensors: Not Done") #################################################################### # Display results # --------------- # # plot violin plot plt.violinplot( list(speed_numpy.values()), showmeans=False, showmedians=True, ) plt.violinplot( list(speed_pytorch.values()), showmeans=False, showmedians=True, ) plt.violinplot( list(speed_pykeops.values()), showmeans=False, showmedians=True, ) plt.xticks([1, 2, 3, 4], kernel_to_test) plt.yscale("log") # plt.ylim((0, .01)) plt.grid(True) plt.xlabel("kernel type") plt.ylabel("time in s.") cmap = plt.get_cmap("tab10") fake_handles = [matplotlib.patches.Patch(color=cmap(i)) for i in range(4)] plt.legend( fake_handles, ["NumPy", "PyTorch", "KeOps Lazytensors"], loc="best", ) plt.show()
keops-main
pykeops/pykeops/benchmarks/plot_benchmark_convolutions.py
""" Benchmarking Gaussian convolutions in high dimensions =========================================================== Let's compare the performances of PyTorch and KeOps on simple Gaussian RBF kernel products, as the dimension grows. """ ############################################## # Setup # --------------------- import importlib import os import time import numpy as np import torch from matplotlib import pyplot as plt from benchmark_utils import flatten, random_normal, full_benchmark use_cuda = torch.cuda.is_available() ############################################## # Benchmark specifications: # N = 10000 # Number of samples # Dimensions to test: Dims = [1, 3, 5, 10, 20, 30, 50, 80, 100, 120, 150, 200, 300, 500, 1000, 2000, 3000] ############################################## # Synthetic dataset. def generate_samples(D, device="cuda", lang="torch", batchsize=1, **kwargs): """Generates two point clouds x, y and a scalar signal b of size N. Args: D (int): dimension of the ambient space. device (str, optional): "cuda", "cpu", etc. Defaults to "cuda". lang (str, optional): "torch", "numpy", etc. Defaults to "torch". batchsize (int, optional): number of experiments to run in parallel. Defaults to None. Returns: 3-uple of arrays: x, y, b """ randn = random_normal(device=device, lang=lang) x = randn((batchsize, N, D)) y = randn((batchsize, N, D)) b = randn((batchsize, N, 1)) return x, y, b ############################################## # Define a simple Gaussian RBF product, using a **tensorized** implementation. # Note that expanding the squared norm :math:`\|x-y\|^2` as a sum # :math:`\|x\|^2 - 2 \langle x, y \rangle + \|y\|^2` allows us # to leverage the fast matrix-matrix product of the BLAS/cuBLAS # libraries. # def gaussianconv_pytorch(x, y, b, **kwargs): """(B,N,D), (B,N,D), (B,N,1) -> (B,N,1)""" D_xx = (x * x).sum(-1).unsqueeze(2) # (B,N,1) D_xy = torch.matmul(x, y.permute(0, 2, 1)) # (B,N,D) @ (B,D,M) = (B,N,M) D_yy = (y * y).sum(-1).unsqueeze(1) # (B,1,M) D_xy = D_xx - 2 * D_xy + D_yy # (B,N,M) K_xy = (-D_xy).exp() # (B,N,M) return K_xy @ b # (B,N,1) ############################################## # Define a simple Gaussian RBF product, using an **online** implementation: # from pykeops.torch import generic_sum def gaussianconv_keops(x, y, b, backend="GPU", **kwargs): D = x.shape[-1] fun = generic_sum( "Exp(X|Y) * B", # Formula "A = Vi(1)", # Output "X = Vi({})".format(D), # 1st argument "Y = Vj({})".format(D), # 2nd argument "B = Vj(1)", # 3rd argument ) ex = (-(x * x).sum(-1)).exp()[:, :, None] ey = (-(y * y).sum(-1)).exp()[:, :, None] return ex * fun(2 * x, y, b * ey, backend=backend) ############################################## # Same, but without the chunked computation mode: # def gaussianconv_keops_nochunks(x, y, b, backend="GPU", **kwargs): D = x.shape[-1] fun = generic_sum( "Exp(X|Y) * B", # Formula "A = Vi(1)", # Output "X = Vi({})".format(D), # 1st argument "Y = Vj({})".format(D), # 2nd argument "B = Vj(1)", # 3rd argument enable_chunks=False, ) ex = (-(x * x).sum(-1)).exp()[:, :, None] ey = (-(y * y).sum(-1)).exp()[:, :, None] return ex * fun(2 * x, y, b * ey, backend=backend) ############################################## # PyTorch vs. KeOps (Gpu) # -------------------------------------------------------- routines = [ (gaussianconv_pytorch, "PyTorch (GPU)", {}), (gaussianconv_keops_nochunks, "KeOps < 1.4.2 (GPU)", {}), (gaussianconv_keops, "KeOps >= 1.4.2 (GPU)", {}), ] full_benchmark( f"Gaussian Matrix-Vector products in high dimension, with N={N:,} (GPU)", routines, generate_samples, problem_sizes=Dims, xlabel="Dimension of the points", ) plt.show()
keops-main
pykeops/pykeops/benchmarks/plot_benchmark_high_dimension.py
""" Mixed-precision and accuracy settings =========================================================== We test various options of KeOps regarding accuracy of computations. """ ############################################## # Setup # --------------------- output_filename = "accuracy" import importlib import os import time import numpy as np import torch from matplotlib import pyplot as plt use_cuda = torch.cuda.is_available() D = 3 ############################################## # Benchmark specifications: # MAXTIME = 10 if use_cuda else 1 # Max number of seconds before we break the loop REDTIME = ( 2 if use_cuda else 0.2 ) # Decrease the number of runs if computations take longer than 2s... # Number of samples that we'll loop upon NS = [ 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000, 200000, 500000, 1000000, 2000000, 5000000, ] ############################################## # Synthetic dataset. def generate_samples(N, D, device, lang): """Create point clouds sampled non-uniformly on a sphere of diameter 1.""" if lang == "torch": if device == "cuda": torch.cuda.manual_seed_all(123) else: torch.manual_seed(123) x = torch.rand((N, D), device=device, dtype=torch.float64) y = torch.rand((N, D), device=device, dtype=torch.float64) # Draw a random source signal: b = torch.randn((N, 1), device=device, dtype=torch.float64) else: np.random.seed(1234) x = np.random.randn(*((N, D))) y = np.random.randn(*((N, D))) b = np.random.randn(*((N,))) return x, y, b ############################################## # Define a simple RBF product, using the :class:`pykeops.torch.LazyTensor` wrapper: from pykeops.torch import LazyTensor def conv_lazytensor(x, y, b, dtype, dtype_acc, sum_scheme): backend = "GPU" if use_cuda else "CPU" x_i = LazyTensor(x.unsqueeze(-2)) # (M, 1, D) y_j = LazyTensor(y.unsqueeze(-3)) # (1, N, D) K_ij = ((x_i - y_j) ** 2).sum(-1) # (M, N, 1) S_ij = K_ij * b.unsqueeze(-3) # (M, N, 1) * (1, N, 1) return S_ij.sum(dim=1, backend=backend, dtype_acc=dtype_acc, sum_scheme=sum_scheme) ############################################## # Benchmarking loops # ----------------------- def benchmark(Routine, dev, N, D, loops, lang, dtype, dtype_acc, sum_scheme): """Times a convolution on an N-by-N problem, and evaluate accuracy.""" importlib.reload(torch) # In case we had a memory overflow just before... device = torch.device(dev) x_, y_, b_ = generate_samples(N, D, device, lang) if dtype == "float16": torch_dtype = torch.float16 if dtype == "float32": torch_dtype = torch.float32 elif dtype == "float64": torch_dtype = torch.float64 x, y, b = x_.to(torch_dtype), y_.to(torch_dtype), b_.to(torch_dtype) # We simply benchmark a convolution N0 = min(N, 100) Routine( x[:N0, :], y[:N0, :], b[:N0, :], dtype, dtype_acc, sum_scheme ) # Warmup run, to compile and load everything # timings if loops > 0: code = "out = Routine( x, y, b, dtype, dtype_acc, sum_scheme ) " t_0 = time.perf_counter() # Actual benchmark -------------------- if use_cuda: torch.cuda.synchronize() for i in range(loops): exec(code, locals()) if use_cuda: torch.cuda.synchronize() elapsed = time.perf_counter() - t_0 # --------------------------- elapsed /= loops print( "timing of {:3} NxN convolution(s), with N ={:7}: {:3}x{:3.6f}s".format( loops, N, loops, elapsed / loops ) ) else: elapsed = np.NaN # accuracy ind = torch.randperm(y.shape[0]) M = min( N, 1000 ) # we evaluate accuracy on a subsample of outputs only because computations with full precisions are slow. out = Routine(x[:M, :], y[ind, :], b[ind, :], dtype, dtype_acc, sum_scheme) ref_out = Routine(x_[:M, :], y_, b_, "float64", "float64", "kahan_scheme") mean_err = ( (out.double() - ref_out.double()).abs().mean() / ref_out.double().abs().mean() ).item() mean_err = float("NaN") if mean_err == 0 else mean_err max_err = ( (out.double() - ref_out.double()).abs().max() / ref_out.double().abs().mean() ).item() max_err = float("NaN") if max_err == 0 else max_err print( "accuracy of an MxN convolution, with M = {}, N ={:7}: mean err={:.1e}, max err={:.1e}".format( M, N, mean_err, max_err ) ) return elapsed, mean_err, max_err def bench_config(Routine, backend, dev, lang, dtype, dtype_acc, sum_scheme): """Times a convolution for an increasing number of samples.""" print( "Backend : {}, Device : {}, dtype : {}, dtype_acc : {}, sum_scheme : {} -------------".format( backend, dev, dtype, dtype_acc, sum_scheme ) ) times = [] mean_errs = [] max_errs = [] try: Nloops = [100, 10, 1, 0] nloops = Nloops.pop(0) for n in NS: elapsed, mean_err, max_err = benchmark( Routine, dev, n, D, nloops, lang, dtype, dtype_acc, sum_scheme ) times.append(elapsed) mean_errs.append(mean_err) max_errs.append(max_err) if nloops > 0: if (nloops * elapsed > MAXTIME) or ( nloops * elapsed > REDTIME / 10 and nloops > 1 ): nloops = Nloops.pop(0) except RuntimeError: print("**\nMemory overflow !") except IndexError: print("**\nToo slow !") fill_nans = (len(NS) - len(times)) * [np.nan] return times + fill_nans, mean_errs + fill_nans, max_errs + fill_nans def full_bench(title, routines): """Benchmarks the varied options of a geometric loss function.""" backends = [backend for (_, backend, _, _, _, _) in routines] print("Benchmarking : {} ===============================".format(title)) lines_times = [NS] lines_mean_errs = [NS] lines_max_errs = [NS] for routine, backend, lang, dtype, dtype_acc, sum_scheme in routines: res = bench_config( routine, backend, "cuda" if use_cuda else "cpu", lang, dtype, dtype_acc, sum_scheme, ) lines_times.append(res[0]) lines_mean_errs.append(res[1]) lines_max_errs.append(res[2]) benches_times = np.array(lines_times).T benches_mean_errs = np.array(lines_mean_errs).T benches_max_errs = np.array(lines_max_errs).T for ind_benches, benches in enumerate( (benches_times, benches_mean_errs, benches_max_errs) ): # Creates a pyplot figure: plt.figure(figsize=(12, 8)) linestyles = ["o-", "s-", "^-", "<-", ">-", "v-", "+-", "*-", "x-", "p-", "d-"] for i, config in enumerate(routines): plt.plot( benches[:, 0], benches[:, i + 1], linestyles[i], linewidth=2, label='config = "{}"'.format(config[3:]), ) plt.xlabel("Number of samples") if ind_benches == 0: plt.title("Runtimes for {} in dimension {}".format(title, D)) plt.ylabel("Seconds") elif ind_benches == 1: plt.title("Mean errors for {} in dimension {}".format(title, D)) plt.ylabel("Relative mean error") elif ind_benches == 2: plt.title("Max errors for {} in dimension {}".format(title, D)) plt.ylabel("Relative max error") plt.yscale("log") plt.xscale("log") plt.legend(loc="upper left") plt.grid(True, which="major", linestyle="-") plt.grid(True, which="minor", linestyle="dotted") true_vals = benches[:, 1:].flatten() true_vals = true_vals[np.isfinite(true_vals)] if ind_benches == 0: plt.axis([NS[0], NS[-1], true_vals.min(), MAXTIME]) else: plt.axis([NS[0], NS[-1], true_vals.min(), 100 * true_vals.max()]) plt.tight_layout() # Save as a .csv to put a nice Tikz figure in the papers: header = "Npoints " + " ".join(backends) os.makedirs("output", exist_ok=True) np.savetxt( "output/" + output_filename + "_" + str(ind_benches) + ".csv", benches, fmt="%-9.5f", header=header, comments="", ) ############################################## # KeOps # -------------------------------------------------------- routines = [ ( conv_lazytensor, "float16, direct_sum", "torch", "float16", "float16", "direct_sum", ), (conv_lazytensor, "float16, block_sum", "torch", "float16", "float16", "block_sum"), ( conv_lazytensor, "float16, kahan_scheme", "torch", "float16", "float16", "kahan_scheme", ), ( conv_lazytensor, "float16, float32 acc", "torch", "float16", "float32", "block_sum", ), ( conv_lazytensor, "float32, direct_sum", "torch", "float32", "float32", "direct_sum", ), (conv_lazytensor, "float32, block_sum", "torch", "float32", "float32", "block_sum"), ( conv_lazytensor, "float32, kahan_scheme", "torch", "float32", "float32", "kahan_scheme", ), ( conv_lazytensor, "float32, float64 acc", "torch", "float32", "float64", "block_sum", ), ( conv_lazytensor, "float64, direct_sum", "torch", "float64", "float64", "direct_sum", ), (conv_lazytensor, "float64, block_sum", "torch", "float64", "float64", "block_sum"), ( conv_lazytensor, "float64, kahan_scheme", "torch", "float64", "float64", "kahan_scheme", ), ] full_bench(" Matrix-Vector products", routines) plt.show()
keops-main
pykeops/pykeops/benchmarks/plot_accuracy.py
""" Datasets for the benchmarks ========================================== """ import os import numpy as np import urllib.request synthetic = { # Key : metric, Ntrain, Ntest, D, "R^D a": ("euclidean", 10**4, 10**4, 3), "R^D b": ("euclidean", 10**6, 10**4, 3), "R^D c": ("euclidean", 10**6, 10**4, 10), "R^D d": ("euclidean", 10**6, 10**4, 100), "R^D e": ("euclidean", 10**7, 10**4, 100), "R^D f": ("manhattan", 10**6, 10**4, 10), "R^D g": ("manhattan", 10**6, 10**4, 100), "S^{D-1}": ("angular", 10**6, 10**4, 10), "H^D": ("hyperbolic", 10**6, 10**4, 10), } downloaded = { # Key : metric, filename, url "MNIST a": ( "euclidean", "mnist-784-euclidean.hdf5", "http://ann-benchmarks.com/mnist-784-euclidean.hdf5", ), "MNIST b": ( "manhattan", "mnist-784-euclidean.hdf5", "http://ann-benchmarks.com/mnist-784-euclidean.hdf5", ), "GloVe25": ( "angular", "glove-25-angular.hdf5", "http://ann-benchmarks.com/glove-25-angular.hdf5", ), "GloVe100": ( "angular", "glove-100-angular.hdf5", "http://ann-benchmarks.com/glove-100-angular.hdf5", ), } def get_dataset(key): data_folder = "benchmark_datasets/" filename = None true_indices = None true_values = None if key in synthetic.keys(): metric, Ntrain, Ntest, D = synthetic[key] if metric == "hyperbolic": x_train = 0.5 + np.random.rand(Ntrain, D) x_test = 0.5 + np.random.rand(Ntest, D) else: x_train = np.random.randn(Ntrain, D) x_test = np.random.randn(Ntest, D) else: import h5py metric, filename, url = downloaded[key] filename = data_folder + filename if not os.path.isfile(filename): os.makedirs(os.path.dirname(filename), exist_ok=True) urllib.request.urlretrieve(url, filename) f = h5py.File(filename, "r") x_train = f["train"][()] x_test = f["test"][()] true_indices = f["neighbors"][()] true_values = f["distances"][()] #  With the angular metric, all the points are normalized: if metric == "angular": x_train /= np.linalg.norm(x_train, axis=1, keepdims=True) x_test /= np.linalg.norm(x_test, axis=1, keepdims=True) x_train = x_train.astype("float32") x_test = x_test.astype("float32") return { "train": x_train, "test": x_test, "metric": metric, "output": true_indices, # "true_distances": true_values, } from benchmark_utils import tensor from pykeops.torch import LazyTensor def ground_truth(x_train, x_test, K, metric): # Setup the K-NN estimator: x_train = tensor(x_train) x_test = tensor(x_test) # Encoding as KeOps LazyTensors: X_i = LazyTensor(x_test[:, None, :]) X_j = LazyTensor(x_train[None, :, :]) # Symbolic distance matrix: if metric == "euclidean": D_ij = ((X_i - X_j) ** 2).sum(-1) elif metric == "manhattan": D_ij = (X_i - X_j).abs().sum(-1) elif metric == "angular": D_ij = -(X_i | X_j) elif metric == "hyperbolic": D_ij = ((X_i - X_j) ** 2).sum(-1) / (X_i[0] * X_j[0]) # K-NN query: indices = D_ij.argKmin(K, dim=1) return indices.cpu().numpy() from copy import deepcopy def generate_samples(key): dataset = get_dataset(key) def samples(K): KNN_dataset = deepcopy(dataset) KNN_dataset["output"] = ground_truth( KNN_dataset["train"], KNN_dataset["test"], K, KNN_dataset["metric"] ) return KNN_dataset return samples
keops-main
pykeops/pykeops/benchmarks/dataset_utils.py
""" Gradient of Radial kernels convolutions ======================================== This benchmark compares the performances of KeOps versus Numpy and Torch on various gradient of radial kernels convolutions. Namely it computes: .. math:: c_i^u = \sum_{j=1}^N \partial_{x_i^u} f\Big(\\frac{\|x_i-y_j\|}{\sigma}\Big) \langle b_j, a_i \\rangle, \quad \\text{ for all } i=1,\cdots,M, \, u=1,\cdots,D where :math:`f` is a Gauss or Cauchy or Laplace or inverse multiquadric kernel. See e.g. `wikipedia <https://en.wikipedia.org/wiki/Radial_basis_function>`_ """ ##################################################################### # Setup # ------ # Standard imports: import numpy as np import timeit import matplotlib from matplotlib import pyplot as plt from pykeops.numpy.utils import grad_np_kernel, chain_rules from pykeops.torch.utils import torch_kernel from pykeops.torch import Vi, Vj, Pm ###################################################################### # Benchmark specifications: # M = 10000 # Number of points x_i N = 10000 # Number of points y_j D = 3 # Dimension of the x_i's and y_j's E = 3 # Dimension of the b_j's REPEAT = 10 # Number of loops per test use_numpy = True use_vanilla = True dtype = "float32" ###################################################################### # Create some random input data: # a = np.random.rand(N, E).astype(dtype) # Gradient to backprop x = np.random.rand(N, D).astype(dtype) # Target points y = np.random.rand(M, D).astype(dtype) # Source points b = np.random.rand(M, E).astype(dtype) # Source signals sigma = np.array([0.4]).astype(dtype) # Kernel radius ###################################################################### # And load it as PyTorch variables: # try: import torch use_cuda = torch.cuda.is_available() device = "cuda" if use_cuda else "cpu" torchtype = torch.float32 if dtype == "float32" else torch.float64 ac = torch.tensor(a, dtype=torchtype, device=device) xc = torch.tensor(x, dtype=torchtype, device=device, requires_grad=True) yc = torch.tensor(y, dtype=torchtype, device=device) bc = torch.tensor(b, dtype=torchtype, device=device) sigmac = torch.tensor(sigma, dtype=torchtype, device=device) except: pass #################################################################### # Convolution Gradient Benchmarks # ----------------------------------- # # We loop over four different kernels: # kernel_to_test = ["gaussian", "laplacian", "cauchy", "inverse_multiquadric"] kernels = { "gaussian": lambda xc, yc, sigmac: ( -Pm(1 / sigmac**2) * Vi(xc).sqdist(Vj(yc)) ).exp(), "laplacian": lambda xc, yc, sigmac: ( -(Pm(1 / sigmac**2) * Vi(xc).sqdist(Vj(yc))).sqrt() ).exp(), "cauchy": lambda xc, yc, sigmac: ( 1 + Pm(1 / sigmac**2) * Vi(xc).sqdist(Vj(yc)) ).power(-1), "inverse_multiquadric": lambda xc, yc, sigmac: ( 1 + Pm(1 / sigmac**2) * Vi(xc).sqdist(Vj(yc)) ) .sqrt() .power(-1), } ##################################################################### # With four backends: Numpy, vanilla PyTorch, Generic KeOps reductions # and a specific, handmade legacy CUDA code for kernel convolution gradients: # speed_numpy = {i: np.nan for i in kernel_to_test} speed_pykeops = {i: np.nan for i in kernel_to_test} speed_pytorch = {i: np.nan for i in kernel_to_test} print("Timings for {}x{} convolution gradients:".format(M, N)) for k in kernel_to_test: print("kernel: " + k) # Pure numpy if use_numpy: gnumpy = chain_rules(a, x, y, grad_np_kernel(x, y, sigma, kernel=k), b) speed_numpy[k] = timeit.repeat( "gnumpy = chain_rules(a, x, y, grad_np_kernel(x, y, sigma, kernel=k), b)", globals=globals(), repeat=3, number=1, ) print("Time for NumPy: {:.4f}s".format(np.median(speed_numpy[k]))) else: gnumpy = torch.zeros_like(xc).data.cpu().numpy() # Vanilla pytorch (with cuda if available, and cpu otherwise) if use_vanilla: try: aKxy_b = torch.dot( ac.view(-1), (torch_kernel(xc, yc, sigmac, kernel=k) @ bc).view(-1) ) g3 = torch.autograd.grad(aKxy_b, xc, create_graph=False)[0].cpu() torch.cuda.synchronize() speed_pytorch[k] = np.array( timeit.repeat( setup="cost = torch.dot(ac.view(-1), (torch_kernel(xc, yc, sigmac, kernel=k) @ bc).view(-1))", stmt="g3 = torch.autograd.grad(cost, xc, create_graph=False)[0] ; torch.cuda.synchronize()", globals=globals(), repeat=REPEAT, number=1, ) ) print( "Time for PyTorch: {:.4f}s".format( np.median(speed_pytorch[k]) ), end="", ) print( " (absolute error: ", np.max(np.abs(g3.data.numpy() - gnumpy)), ")", ) except: print("Time for PyTorch: Not Done") # Keops: generic tiled implementation (with cuda if available, and cpu otherwise) try: aKxy_b = torch.dot(ac.view(-1), (kernels[k](xc, yc, sigmac) @ bc).view(-1)) g3 = torch.autograd.grad(aKxy_b, xc, create_graph=False)[0].cpu() torch.cuda.synchronize() speed_pykeops[k] = np.array( timeit.repeat( setup="cost = torch.dot(ac.view(-1), (kernels[k](xc, yc, sigmac) @ bc).view(-1))", stmt="g3 = torch.autograd.grad(cost, xc, create_graph=False)[0] ; torch.cuda.synchronize()", globals=globals(), repeat=REPEAT, number=1, ) ) print( "Time for KeOps LazyTensors: {:.4f}s".format( np.median(speed_pykeops[k]) ), end="", ) print( " (absolute error: ", np.max(np.abs(g3.data.numpy() - gnumpy)), ")" ) except: print("Time for KeOps LazyTensors: Not Done") #################################################################### # Display results # --------------- # # plot violin plot plt.violinplot( list(speed_numpy.values()), showmeans=False, showmedians=True, ) plt.violinplot( list(speed_pytorch.values()), showmeans=False, showmedians=True, ) plt.violinplot( list(speed_pykeops.values()), showmeans=False, showmedians=True, ) plt.xticks([1, 2, 3, 4], kernel_to_test) plt.yscale("log") # plt.ylim((0, .01)) plt.grid(True) plt.xlabel("kernel type") plt.ylabel("time in s.") cmap = plt.get_cmap("tab10") fake_handles = [matplotlib.patches.Patch(color=cmap(i)) for i in range(4)] plt.legend( fake_handles, ["NumPy", "PyTorch", "KeOps LazyTensors"], loc="best", ) plt.show()
keops-main
pykeops/pykeops/benchmarks/plot_benchmark_grad1convolutions.py
""" K-Nearest Neighbors search ========================================= We compare the performances of PyTorch, JAX, KeOps, Scikit-Learn and FAISS (when applicable) for K-NN queries on random samples and standard datasets. A detailed discussion of these results can be found in Section 5.2 of our `NeurIPS 2020 paper <https://www.jeanfeydy.com/Papers/KeOps_NeurIPS_2020.pdf>`_. Generally speaking, generic KeOps routines are orders of magnitude faster and more memory efficient than their PyTorch and JAX counterparts. They perform on par with the handcrafted CUDA kernels of the FAISS-Flat (bruteforce) method for problems with **up to 1M samples in dimension 1 to 50-100**, but are sub-optimal on larger datasets. Crucially, KeOps is easy to use with **any metric**: it provides the only competitive run times in the many settings that are not supported by existing C++ libraries. In this demo, we often use exact **bruteforce** computations (tensorized for PyTorch/JAX, on-the-fly for KeOps) and do not leverage any quantization scheme or multiscale decomposition of the distance matrix. First support for these approximation strategies with KeOps is scheduled for May-June 2021. Going forward, a major priority for KeOps is to get closer to the reference run times of the FAISS library in all settings. We intend to provide a versatile, generic and pythonic code that is easy to modify and integrate in other projects. Hopefully, this will **stimulate research on non-Euclidean metrics**, such as hyperbolic or discrete spaces. .. note:: Note that timings are always subject to change: libraries and hardware get better with time. If you find a way of improving these benchmarks, please `let us know <https://github.com/getkeops/keops/issues>`_! """ ############################################## # Setup # --------------------- # # First, we load some utility routines to run and display benchmarks: import numpy as np import torch from matplotlib import pyplot as plt from functools import partial from benchmark_utils import ( full_benchmark, timer, tensor, int_tensor, jax_tensor, globalize, ) from dataset_utils import generate_samples use_cuda = torch.cuda.is_available() ############################################## # We then specify the values of K that we will inspect: Ks = [1, 10, 50, 100] # Numbers of neighbors to find ############################################## # PyTorch bruteforce implementation # ------------------------------------------ # # As a first baseline, we benchmark a PyTorch K-NN routine on the GPU. # We implement a collection of distance-like matrices between # point clouds :math:`(x_i)` and :math:`(y_j)`: # # - The squared **Euclidean** distance :math:`\|x-y\|^2 = \sum_k (x[k] - y[k])^2`. # - The **Manhattan** distance :math:`\|x-y\|_{L^1} = \sum_k |x[k] - y[k]|`. # - The **cosine similarity** :math:`\langle x, y\rangle = \sum_k (x[k] \cdot y[k])`. # - The **hyperbolic** distance on the Poincare half-space :math:`\mathbb{H}` # of vectors :math:`x` such that :math:`x[0] > 0`, # :math:`\text{d}_{\mathbb{H}}(x, y)= \text{arcosh}(1+ \|x-y\|^2 / (2 \,x[0]y[0]))`. # Since :math:`d \mapsto \text{arcosh}(1+d/2)` is increasing, # we only compute the pseudo distance # :math:`\|x-y\|^2 / x[0]y[0]`. # # .. note:: # Expanding the squared norm :math:`\|x-y\|^2` as a sum # :math:`\|x\|^2 - 2 \langle x, y \rangle + \|y\|^2` allows us # to leverage the fast matrix-matrix product of the BLAS/cuBLAS # libraries. We rely on this identity whenever possible. # def KNN_torch_fun(x_train, x_train_norm, x_test, K, metric): largest = False # Default behaviour is to look for the smallest values if metric == "euclidean": x_test_norm = (x_test**2).sum(-1) diss = ( x_test_norm.view(-1, 1) + x_train_norm.view(1, -1) - 2 * x_test @ x_train.t() # Rely on cuBLAS for better performance! ) elif metric == "manhattan": diss = (x_test[:, None, :] - x_train[None, :, :]).abs().sum(dim=2) elif metric == "angular": diss = x_test @ x_train.t() largest = True elif metric == "hyperbolic": x_test_norm = (x_test**2).sum(-1) diss = ( x_test_norm.view(-1, 1) + x_train_norm.view(1, -1) - 2 * x_test @ x_train.t() ) diss /= x_test[:, 0].view(-1, 1) * x_train[:, 0].view(1, -1) else: raise NotImplementedError(f"The '{metric}' distance is not supported.") return diss.topk(K, dim=1, largest=largest).indices ############################################################################ # We rely on the **tensorized** # implementation above to define a simple K-NN query operator. # We follow the scikit-learn API with "train" and "test" methods: def KNN_torch(K, metric="euclidean", **kwargs): def fit(x_train): # Setup the K-NN estimator: x_train = tensor(x_train) start = timer() # The "training" time here should be negligible: x_train_norm = (x_train**2).sum(-1) elapsed = timer() - start def f(x_test): x_test = tensor(x_test) start = timer() # Actual K-NN query: out = KNN_torch_fun(x_train, x_train_norm, x_test, K, metric) elapsed = timer() - start indices = out.cpu().numpy() return indices, elapsed return f, elapsed return fit ############################################################################# # Unfortunately, the code above creates a full # :math:`\mathrm{N}_{\text{queries}}\times \mathrm{N}_{\text{points}}` # distance matrix that may not fit in the GPU memory. # To work around this problem and avoid memory overflows, we benchmark a second implementation # that works with small batches of queries at time: def KNN_torch_batch_loop(K, metric="euclidean", **kwargs): def fit(x_train): # Setup the K-NN estimator: x_train = tensor(x_train) Ntrain, D = x_train.shape start = timer() # The "training" time here should be negligible: x_train_norm = (x_train**2).sum(-1) elapsed = timer() - start def f(x_test): x_test = tensor(x_test) # Estimate the largest reasonable batch size: Ntest = x_test.shape[0] av_mem = int(5e8) # 500 Mb of GPU memory per batch # Remember that a vector of D float32 number takes up 4*D bytes: Ntest_loop = min(max(1, av_mem // (4 * D * Ntrain)), Ntest) Nloop = (Ntest - 1) // Ntest_loop + 1 out = int_tensor(Ntest, K) start = timer() # Actual K-NN query: for k in range(Nloop): x_test_k = x_test[Ntest_loop * k : Ntest_loop * (k + 1), :] out[Ntest_loop * k : Ntest_loop * (k + 1), :] = KNN_torch_fun( x_train, x_train_norm, x_test_k, K, metric ) # torch.cuda.empty_cache() elapsed = timer() - start indices = out.cpu().numpy() return indices, elapsed return f, elapsed return fit ############################################################################ # JAX bruteforce implementation # ------------------------------------------ # # We now re-implement the same method with JAX-XLA routines. # # Note that we run this script with the command line option # ``XLA_PYTHON_CLIENT_ALLOCATOR=platform``: this prevents JAX # from locking up GPU memory and allows # us to benchmark JAX, FAISS, PyTorch and KeOps next to each other. # This may impact performances - but as a general rule, # we found JAX to be orders of magnitude slower than PyTorch # and KeOps in these benchmarks, even with unrestrained access to the GPU device memory. # Needless to say, this is subject to change with future releases: # we stay tuned to keep this documentation up to date and welcome # all suggestions! from functools import partial import jax import jax.numpy as jnp @partial(jax.jit, static_argnums=(2, 3)) def knn_jax_fun(x_train, x_test, K, metric): if metric == "euclidean": diss = ( (x_test**2).sum(-1)[:, None] + (x_train**2).sum(-1)[None, :] - 2 * x_test @ x_train.T ) elif metric == "manhattan": diss = jax.lax.abs(x_test[:, None, :] - x_train[None, :, :]).sum(-1) elif metric == "angular": diss = -x_test @ x_train.T elif metric == "hyperbolic": diss = ( (x_test**2).sum(-1)[:, None] + (x_train**2).sum(-1)[None, :] - 2 * x_test @ x_train.T ) diss = diss / (x_test[:, 0][:, None] * x_train[:, 0][None, :]) else: raise NotImplementedError(f"The '{metric}' distance is not supported.") indices = jax.lax.top_k(-diss, K)[1] return indices ############################################################################ # Straightforward K-NN query, with a scikit-learn interface: def KNN_JAX(K, metric="euclidean", **kwargs): def fit(x_train): # Setup the K-NN estimator: start = timer(use_torch=False) x_train = jax_tensor(x_train) elapsed = timer(use_torch=False) - start def f(x_test): x_test = jax_tensor(x_test) # Actual K-NN query: start = timer(use_torch=False) indices = knn_jax_fun(x_train, x_test, K, metric) indices = np.array(indices) elapsed = timer(use_torch=False) - start return indices, elapsed return f, elapsed return fit ############################################################################# # Smarter routine, which relies on small batches to avoid memory overflows: def KNN_JAX_batch_loop(K, metric="euclidean", **kwargs): def fit(x_train): # Setup the K-NN estimator: start = timer(use_torch=False) x_train = jax_tensor(x_train) elapsed = timer(use_torch=False) - start def f(x_test): x_test = jax_tensor(x_test) # Estimate the largest reasonable batch size av_mem = int(5e8) # 500 Mb Ntrain, D = x_train.shape Ntest = x_test.shape[0] Ntest_loop = min(max(1, av_mem // (4 * D * Ntrain)), Ntest) Nloop = (Ntest - 1) // Ntest_loop + 1 indices = np.zeros((Ntest, K), dtype=int) start = timer(use_torch=False) # Actual K-NN query: for k in range(Nloop): x_test_k = x_test[Ntest_loop * k : Ntest_loop * (k + 1), :] indices[Ntest_loop * k : Ntest_loop * (k + 1), :] = knn_jax_fun( x_train, x_test_k, K, metric ) elapsed = timer(use_torch=False) - start return indices, elapsed return f, elapsed return fit ############################################################################ # KeOps bruteforce implementation # -------------------------------------- # # KeOps lets us implement a bruteforce K-NN search efficiently, # **without having to worry about memory overflows**. # We perform all the "symbolic" computations on the distance formulas # ahead of time, using the advanced ``Vi`` and ``Vj`` helpers that are described # in `this tutorial <../_auto_tutorials/a_LazyTensors/plot_lazytensors_c.html>`_. # Note that we could also rely on the simpler ``LazyTensor`` syntax, # at the cost of a small overhead that is negligible in most settings. from pykeops.torch import Vi, Vj def KNN_KeOps(K, metric="euclidean", **kwargs): def fit(x_train): # Setup the K-NN estimator: x_train = tensor(x_train) start = timer() # Encoding as KeOps LazyTensors: D = x_train.shape[1] X_i = Vi(0, D) # Purely symbolic "i" variable, without any data array X_j = Vj(1, D) # Purely symbolic "j" variable, without any data array # Symbolic distance matrix: if metric == "euclidean": D_ij = ((X_i - X_j) ** 2).sum(-1) elif metric == "manhattan": D_ij = (X_i - X_j).abs().sum(-1) elif metric == "angular": D_ij = -(X_i | X_j) elif metric == "hyperbolic": D_ij = ((X_i - X_j) ** 2).sum(-1) / (X_i[0] * X_j[0]) else: raise NotImplementedError(f"The '{metric}' distance is not supported.") # K-NN query operator: KNN_fun = D_ij.argKmin(K, dim=1) # N.B.: The "training" time here should be negligible. elapsed = timer() - start def f(x_test): x_test = tensor(x_test) start = timer() # Actual K-NN query: indices = KNN_fun(x_test, x_train) elapsed = timer() - start indices = indices.cpu().numpy() return indices, elapsed return f, elapsed return fit ################################################################################ # SciKit-Learn tree-based and bruteforce methods # ----------------------------------------------------- # # As a standard baseline, we include the scikit-learn K-NN operators # in our benchmark. Note that these routines only run on the CPU # and don't perform well on high-dimensional datasets: from sklearn.neighbors import NearestNeighbors def KNN_sklearn(K, metric="euclidean", algorithm=None, **kwargs): if metric in ["euclidean", "angular"]: p = 2 elif metric == "manhattan": p = 1 else: raise NotImplementedError(f"The '{metric}' distance is not supported.") KNN_meth = NearestNeighbors(n_neighbors=K, algorithm=algorithm, p=p, n_jobs=-1) def fit(x_train): # Setup the K-NN estimator: start = timer() KNN_fun = KNN_meth.fit(x_train).kneighbors elapsed = timer() - start def f(x_test): start = timer() distances, indices = KNN_fun(x_test) elapsed = timer() - start return indices, elapsed return f, elapsed return fit KNN_sklearn_auto = partial(KNN_sklearn, algorithm="auto") KNN_sklearn_ball_tree = partial(KNN_sklearn, algorithm="ball_tree") KNN_sklearn_kd_tree = partial(KNN_sklearn, algorithm="kd_tree") KNN_sklearn_brute = partial(KNN_sklearn, algorithm="brute") ######################################################## # FAISS approximate and brute-force methods # -------------------------------------------------- # # Finally, we include run times for the reference FAISS library: # out of the many (excellent) packages that are showcased on the # `ANN-benchmarks website <http://ann-benchmarks.com>`_, # it is probably the most popular option and the package that provides the # best GPU support. # # A first baseline method is given by the # Hierarchical Navigable Small World graphs algorithm (**HNSW**), on the **CPU**. # Note that the reference implementation provided by the # `Non-Metric Space Library <https://github.com/nmslib/nmslib>`_ # would probably be even more efficient. # import faiss def KNN_faiss_HNSW(K, metric="euclidean", M=36, **kwargs): def fit(x_train): from benchmark_utils import timer D = x_train.shape[1] if metric in ["euclidean", "angular"]: index = faiss.IndexHNSWFlat(D, M) index.hnsw.efConstruction = 500 else: raise NotImplementedError(f"The '{metric}' distance is not supported.") # Pre-processing: start = timer(use_torch=False) index.add(x_train) elapsed = timer(use_torch=False) - start # Return an operator for actual KNN queries: def f(x_test, efSearch=10): faiss.ParameterSpace().set_index_parameter(index, "efSearch", efSearch) start = timer(use_torch=False) distances, indices = index.search(x_test, K) elapsed = timer(use_torch=False) - start return indices, elapsed return f, elapsed return fit ################################################################## # Choosing good parameter values for approximate nearest neighbors schemes # is a non-trivial problem. # To keep things simple, we stick to the guidelines of the # reference `ANN-Benchmarks website <https://github.com/erikbern/ann-benchmarks/blob/cb954d1af7124c201aa2c8dfc77681e639fce586/algos.yaml#L95>`_ # and consider two configurations with an **increasing level of precision**, # but **slower run times**: # KNN_faiss_HNSW_fast = partial(KNN_faiss_HNSW, M=4) KNN_faiss_HNSW_slow = partial(KNN_faiss_HNSW, M=36) ############################################## # We also benchmark two of the **fast GPU methods** provided by the FAISS library: # # - a **bruteforce "Flat"** method, with no parameters; # - the **approximate "IVF-Flat"** method, with two main parameters (`nlist` and `nprobe`). # # Crucially, we do **not** benchmark the most advanced schemes # provided by FAISS, such as the quantization-based # **IVF-PQ** algorithm. These methods are powerful and very efficient, but come with many # caveats and parameters to tune: we lack the expertise to # use them properly and leave them aside for the moment. # # Load FAISS on the GPU: # (The library pre-allocates a cache file of around ~1Gb on the device.) res = faiss.StandardGpuResources() deviceId = 0 def KNN_faiss_gpu( K, metric, algorithm="flat", nlist=8192, nprobe=100, m=None, use_float16=False, **kwargs, ): def fit(x_train): D = x_train.shape[1] co = faiss.GpuClonerOptions() co.useFloat16 = use_float16 if metric in ["euclidean", "angular"]: if algorithm == "flat": index = faiss.IndexFlatL2(D) # May be used as quantizer index = faiss.index_cpu_to_gpu(res, deviceId, index, co) elif algorithm == "ivfflat": quantizer = faiss.IndexFlatL2(D) # the other index faiss_metric = ( faiss.METRIC_L2 if metric == "euclidean" else faiss.METRIC_INNER_PRODUCT ) index = faiss.IndexIVFFlat(quantizer, D, nlist, faiss_metric) index = faiss.index_cpu_to_gpu(res, deviceId, index, co) assert not index.is_trained index.train(x_train) # add vectors to the index assert index.is_trained else: raise NotImplementedError(f"The '{metric}' distance is not supported.") # Pre-processing: start = timer(use_torch=False) index.add(x_train) index.nprobe = nprobe elapsed = timer(use_torch=False) - start # Return an operator for actual KNN queries: def f(x_test): start = timer(use_torch=False) distances, indices = index.search(x_test, K) elapsed = timer(use_torch=False) - start return indices, elapsed return f, elapsed return fit ################################################################## # Using the FAISS-Flat bruteforce routines is straightforward: # KNN_faiss_gpu_Flat = partial(KNN_faiss_gpu, algorithm="flat") ####################################### # On the other hand, the FAISS-IVF-Flat method is a bit more complex. # Just as we did for the HNSW algorithm, we rely on the # `ANN-Benchmarks guidelines <https://github.com/erikbern/ann-benchmarks/blob/cb954d1af7124c201aa2c8dfc77681e639fce586/algos.yaml#L50>`_ # and define two routines with **increasing levels of precision**: KNN_faiss_gpu_IVFFlat_fast = partial( KNN_faiss_gpu, algorithm="ivfflat", nlist=400, nprobe=1 ) KNN_faiss_gpu_IVFFlat_slow = partial( KNN_faiss_gpu, algorithm="ivfflat", nlist=4096, nprobe=40 ) ############################################## # Benchmark parameters # -------------------------------------------------------- # # Finally, we compare all our methods through a unified interface. # # .. note:: # Fitting KeOps, JAX, PyTorch and FAISS in a single script is not easy: # all these libraries have different failure modes, # with some of the C++ errors thrown by JAX and FAISS being # very hard to "catch" in a proper Python structure. # To keep things simple, we use environment variables # to make a few "pre-compilation runs" prior to the # final benchmark that is rendered on this website. import os getenv = lambda s: bool(os.getenv(s, "False").lower() in ["true", "1"]) keops_only = getenv("KEOPS_DOC_PRECOMPILE") jax_only = getenv("KEOPS_DOC_PRECOMPILE_JAX") def run_KNN_benchmark(name, loops=[1]): # Load the dataset and some info: dataset = generate_samples(name)(1) N_train, dimension = dataset["train"].shape N_test, _ = dataset["test"].shape metric = dataset["metric"] # Routines to benchmark: if keops_only: routines = [(KNN_KeOps, "KeOps (GPU)", {})] elif jax_only: routines = [(KNN_JAX_batch_loop, "JAX (small batches, GPU)", {})] else: routines = [ (KNN_KeOps, "KeOps (GPU)", {}), (KNN_faiss_gpu_Flat, "FAISS-Flat (GPU)", {}), (KNN_faiss_gpu_IVFFlat_fast, "FAISS-IVF-Flat (GPU, nprobe=1)", {}), (KNN_faiss_gpu_IVFFlat_slow, "FAISS-IVF-Flat (GPU, nprobe=40)", {}), (KNN_torch, "PyTorch (GPU)", {}), (KNN_torch_batch_loop, "PyTorch (small batches, GPU)", {}), (KNN_JAX_batch_loop, "JAX (small batches, GPU)", {}), (KNN_faiss_HNSW_fast, "FAISS-HNSW (CPU, M=4)", {}), (KNN_faiss_HNSW_slow, "FAISS-HNSW (CPU, M=36)", {}), (KNN_sklearn_ball_tree, "sklearn, Ball-tree (CPU)", {}), (KNN_sklearn_kd_tree, "sklearn, KD-tree (CPU)", {}), # (KNN_sklearn_brute, "sklearn, bruteforce (CPU)", {}), ] # Actual run: full_benchmark( f"K-NN search on {name}: {N_test:,} queries on a dataset of {N_train:,} points\nin dimension {dimension:,} with a {metric} metric.", routines, generate_samples(name), min_time=1e-4, max_time=1 if (keops_only or jax_only) else 10, loops=loops, problem_sizes=Ks, xlabel="Number of neighbours K", frequency=True, ylabel="Queries per second (Hz = 1/s)", legend_location="upper right", linestyles=[ "o-", "s-", "^:", "<:", "v-", "x-", "+-", "*--", "p--", "s-.", "^-.", # "<-.", ], ) ############################################## # Random samples in a Euclidean space # -------------------------------------------------------- # # Small dataset of **10k points in dimension 3**, as is typical in # e.g. **shape analysis** and point cloud processing. # In this scenario, bruteforce approaches are most efficient: # **KeOps slightly edges FAISS-Flat**, with both methods out-performing # other routines by **an order of magnitude**. # Note that the HNSW, IVF-Flat and scikit-learn functions # incur a significant "training" pre-processing time, # detailed below the curves. # run_KNN_benchmark("R^D a", loops=[10, 1]) ######################################## # Large dataset of **1M points in dimension 3**, as is typical # in **computer graphics**. # In this setting, taking some time to create a multiscale # index of the input dataset can be worthwhile: # the IVF-Flat and HNSW methods provide **faster queries** at the cost # of significant **pre-processing times**. # Among "on-the-fly" bruteforce methods, KeOps edges # the FAISS-Flat routine and is the most competitive option. run_KNN_benchmark("R^D b") ######################################## # Large dataset of **1M points in dimension 10**, # as can be typical in **low-dimensional machine learning**. # In this setting, approximate strategies such as the IVF-Flat method # are **most competitive** - and we would expect the IVF-PQ routines to perform # even better! # # .. note:: # We don't display CPU-based methods with pre-processing # times longer than 60s, but stress that these routines can # provide excellent performances in "offline" scenarios. run_KNN_benchmark("R^D c") ######################################## # Large dataset of **1M points in dimension 100**, # with **random Gaussian samples**. # Crucially, when the dataset is high-dimensional and has # little to no geometric structure, **bruteforce methods become relevant once again**: # FAISS-Flat and KeOps provide the only two reasonable run times. # As detailed in `our high-dimensional benchmarks <plot_benchmark_high_dimension.html>`_, # the cuBLAS-based routines of FAISS edge our KeOps implementation # when the dimension of the ambient space D exceeds 50-100. # # One of our top priorities for early 2021 is to close this gap # with improved CUDA schemes. Adding support for # some of the new hardware features of Ampere GPUs (Tensor cores, # quantized numerical types, etc.) should also help # to improve performances across the board. run_KNN_benchmark("R^D d") ######################################## # Random samples in other spaces # ------------------------------------------------------- # # **Cosine similarity metric with 1M points in dimension 10**, # as can be typical in low-dimensional machine learning. # This metric is generally well-supported by standard libraries: # using efficient matrix-matrix products, # it is even easier to implement than the squared Euclidean distance. # # Unsurprisingly, run times follow closely the trends # of the previous examples. # In dimension 10, approximate IVF-like strategies provide # the largest amount of queries per second. # KeOps remains competitive among bruteforce methods, # without any pre-processing time. run_KNN_benchmark("S^{D-1}") ######################################## # The picture changes completely # once we start working with less common formulas # such as the **Manhattan-L1 metric**. # In this scenario, neither cuBLAS nor FAISS can be used and # KeOps remain the only competitive library for K-NN search on the GPU. # This is true with **1M points in dimension 10**: # run_KNN_benchmark("R^D f") ######################################## # **1M point in dimension 100**, or any other dataset: run_KNN_benchmark("R^D g") ######################################## # The same lesson holds in e.g. hyperbolic spaces. # In the example below, we perform K-NN queries # for the hyperbolic metric with **1M points in the Poincare half-plane of dimension 10**. # The run times for KeOps remain in line with the "Euclidean" benchmarks # and **orders of magnitude faster** than standard PyTorch and JAX implementations. run_KNN_benchmark("H^D") ######################################## # Standard datasets # -------------------------------------------------------- # # The benchmarks above were all performed on random Gaussian samples. # These results provide an informative baseline... # But in practice, most real-life datasets present a # **geometric structure** that can be leveraged by clever algorithms. # To measure the performances of bruteforce and IVF-like methods in # "realistic" machine learning scenarios, we now benchmark # our routines on several `standard datasets <https://ann-benchmarks.com>`_. # # First of all, on the well-known **MNIST collection of handwritten digits**: # a collection of 60k 28-by-28 images, encoded as vectors # of dimension 784 and endowed with the **Euclidean metric**. # This dataset is relatively **small** (less than 100k training samples) # but **high-dimensional** (D > 50) and highly **clustered** around # a dozen of prototypes (the digits 0, 1, ..., 9 and their variants). # Unsurprisingly, it is handled much more efficiently by the FAISS routines # than by our bruteforce KeOps implementation. # run_KNN_benchmark("MNIST a") ######################################## # Note, however, that KeOps remains the only viable option # to work easily with less common metrics such as the Manhattan-L1 norm: run_KNN_benchmark("MNIST b") ######################################## # To conclude this benchmark, we evaluate our routines # on the `GloVe word embeddings <https://nlp.stanford.edu/projects/glove/>`_ # for natural language processing: # **1.2M words**, represented as vectors of **dimension 25-100** and # compared with each other using the **cosine similarity metric**. # # In dimension 25, KeOps performs on par with the FAISS-Flat bruteforce # routines. Both methods are slower than IVF-like algorithms # in terms of queries per second: run_KNN_benchmark("GloVe25") ######################################## # In dimension 100, the pre-processing times associated # to IVF-like methods increase significantly while # the FAISS-Flat routine edges the KeOps engine # by a sizeable margin: run_KNN_benchmark("GloVe100") plt.show()
keops-main
pykeops/pykeops/benchmarks/benchmark_KNN.py
""" Utility functions for the benchmarks ========================================== """ import importlib import os import time import matplotlib as mpl from matplotlib import pyplot as plt from si_prefix import si_format import numpy as np import torch # import jax use_cuda = torch.cuda.is_available() ################################################## # Utility functions: # def timer(use_torch=True): if use_cuda and use_torch: torch.cuda.synchronize() return time.perf_counter() def flatten(list_of_lists): return [val for sublist in list_of_lists for val in sublist] def clear_gpu_cache(): if use_cuda: torch.cuda.empty_cache() ################################################ # Timeout helper: # from functools import wraps import errno import signal class TimeoutError(Exception): pass def timeout(seconds=10, error_message=os.strerror(errno.ETIME)): def decorator(func): def _handle_timeout(signum, frame): raise TimeoutError(error_message) def wrapper(*args, **kwargs): signal.signal(signal.SIGALRM, _handle_timeout) signal.alarm(seconds) try: result = func(*args, **kwargs) finally: signal.alarm(0) return result return wraps(func)(wrapper) return decorator ################################################## # Conversion routines: # def tensor(*x): if use_cuda: return torch.cuda.FloatTensor(*x) else: return torch.FloatTensor(*x) def int_tensor(*x): if use_cuda: return torch.cuda.LongTensor(*x) else: return torch.LongTensor(*x) def jax_tensor(*x): import jax return jax.device_put(*x) ##################################################### # Random samples: # def random_normal(device="cuda", lang="torch"): def sampler(shape): if lang == "torch": return torch.randn(shape, device=torch.device(device)) else: return np.random.rand(*shape).astype("float32") return sampler def unit_tensor(device="cuda", lang="torch"): def sampler(shape): if lang == "torch": return torch.ones(shape, device=torch.device(device)) else: return np.ones(*shape).astype("float32") return sampler ########################################### # Multiprocessing code # ----------------------------------------- # # # Unfortunately, some FAISS routines throw a C++ "abort" signal instead # of a proper Python exception for out of memory errors on large problems. # Letting them run in a separate process is the only way of handling # the error without aborting the full benchmark. import multiprocess as mp import traceback import queue import sys import uuid def globalize(func): def result(*args, **kwargs): return func(*args, **kwargs) result.__name__ = result.__qualname__ = uuid.uuid4().hex setattr(sys.modules[result.__module__], result.__name__, result) return result class Process(mp.Process): """Exception-friendly process class.""" def __init__(self, *args, **kwargs): mp.Process.__init__(self, *args, **kwargs) self._pconn, self._cconn = mp.Pipe() self._exception = None def run(self): try: mp.Process.run(self) self._cconn.send(None) except Exception as e: tb = traceback.format_exc() self._cconn.send((e, tb)) raise e # You can still rise this exception if you need to @property def exception(self): if self._pconn.poll(): self._exception = self._pconn.recv() return self._exception def with_queue(f, queue, points): o = f(points) queue.put(o) def run_safely(f, x): """Runs f(args) in a separate process.""" # f_global = f # globalize(f) # mp.freeze_support() mp.set_start_method("spawn") q = mp.Queue() p = Process(target=with_queue, args=(f, q, x)) p.start() p.join() if p.exception: error, traceback = p.exception print(traceback) raise error try: out = q.get(False, 2.0) # Non-blocking mode except queue.Empty: print("Empty queue!") print("Exit code: ", p.exitcode) raise MemoryError() return out ############################################## # Benchmarking loops # ----------------------- def simple_loop(N, loops, routine, max_time, args, kwargs): # Warmup run, to compile and load everything: output = routine(*args, **kwargs) t_0 = timer() for i in range(loops): output = routine(*args, **kwargs) elapsed = timer() - t_0 B = kwargs.get("batchsize", 1) perf = elapsed / (B * loops) print( f"{B:3}x{loops:3} loops of size {si_format(N,precision=0):>5}: {B:3}x{loops:3}x {si_format(perf):>7}s" ) return perf def recall(out_indices, true_indices): Ntest, K = out_indices.shape true_indices = true_indices[:Ntest, :K] r = 0.0 for k in range(Ntest): r += np.sum(np.in1d(out_indices[k], true_indices[k], assume_unique=True)) / K r /= Ntest return r def train_test_loop(N, loops, routine, max_time, args, kwargs): x_train = args["train"] x_test = args["test"] ground_truth = args["output"] # Warmup run, to compile and load everything: operator = routine(N, **args, **kwargs) clear_gpu_cache() model, _ = timeout(6 * max_time)(operator)(x_train) clear_gpu_cache() output, _ = timeout(max_time)(model)(x_test) # Time the training step: train_time = 0.0 for i in range(loops): clear_gpu_cache() model, elapsed = operator(x_train) train_time += elapsed # Time the test step: test_time = 0.0 for i in range(loops): clear_gpu_cache() output, elapsed = model(x_test) test_time += elapsed B = kwargs.get("batchsize", 1) train_perf = train_time / (B * loops) test_perf = test_time / (B * loops) perf = recall(output, ground_truth) print(f"{B:3}x{loops:3} loops of size {si_format(N,precision=0):>5}: ", end="") print(f"train = {B:3}x{loops:3}x {si_format(train_perf):>7}s, ", end="") print(f"test = {B:3}x{loops:3}x {si_format(test_perf):>7}s, ", end="") print(f"recall = {100*perf:>3.0f}%") if perf < 0.75: raise ValueError("** Recall lower than 75%!") return test_perf def benchmark( routine, label, N, max_time, loops=10, generate_samples=None, **kwargs, ): importlib.reload(torch) # In case we had a memory overflow just before... args = generate_samples(N, **kwargs) benchmark_loop = train_test_loop if type(args) is dict else simple_loop # Actual benchmark: elapsed = benchmark_loop(N, loops, routine, max_time, args, kwargs) return elapsed def bench_config( routine, label, kwargs, generate_samples=None, problem_sizes=[1], max_time=10, red_time=2, loops=[100, 10, 1], ): """Times a convolution for an increasing number of samples.""" print(f"{label} -------------") times = [] not_recorded_times = [] try: Nloops = loops.copy() nloops = Nloops.pop(0) for n in problem_sizes: elapsed = benchmark( routine, label, n, max_time, loops=nloops, generate_samples=generate_samples, **kwargs, ) times.append(elapsed) if (nloops * elapsed > max_time) or ( nloops * elapsed > red_time and len(Nloops) > 0 ): nloops = Nloops.pop(0) except MemoryError: print("** Memory overflow!") not_recorded_times = (len(problem_sizes) - len(times)) * [np.nan] except (TimeoutError, IndexError): # Thrown by Nloops.pop(0) if Nloops = [] print("** Too slow!") not_recorded_times = (len(problem_sizes) - len(times)) * [np.Infinity] except NotImplementedError: print("** This metric is not supported!") not_recorded_times = (len(problem_sizes) - len(times)) * [np.Infinity] except ValueError as err: print(err) not_recorded_times = (len(problem_sizes) - len(times)) * [np.NINF] except RuntimeError as err: print(err) print("** Runtime error!") not_recorded_times = (len(problem_sizes) - len(times)) * [np.nan] return times + not_recorded_times def identity(x): return x def queries_per_second(N): def qps(x): return N / x return qps def inf_to_nan(x): y = x.copy() y[~np.isfinite(y)] = np.nan return y def full_benchmark( to_plot, routines, generate_samples, problem_sizes, min_time=1e-5, max_time=10, red_time=2, loops=[100, 10, 1], xlabel="Number of samples", ylabel="Time (s)", frequency=False, legend_location="upper left", linestyles=["o-", "s-", "^-", "<-", ">-", "v-", "+-", "*-", "x-", "p-", "d-"], ): if frequency: N = len(generate_samples(1)["test"]) transform = queries_per_second(N) ymin, ymax = transform(max_time), transform(min_time) y_suffix = "Hz" else: transform = identity ymin, ymax = min_time, max_time y_suffix = "s" print("Benchmarking : {} ===============================".format(to_plot)) labels = [label for (_, label, _) in routines] lines = [problem_sizes] + [ bench_config( *routine, generate_samples=generate_samples, problem_sizes=problem_sizes, max_time=max_time, red_time=red_time, loops=loops, ) for routine in routines ] benches = np.array(lines).T # Creates a pyplot figure: plt.figure(figsize=(12, 8)) for i, label in enumerate(labels): plt.plot( benches[:, 0], transform(inf_to_nan(benches[:, i + 1])), linestyles[i % len(linestyles)], linewidth=2, label=label, ) for (j, val) in enumerate(benches[:, i + 1]): if np.isnan(val) and j > 0: x, y = benches[j - 1, 0], transform(benches[j - 1, i + 1]) plt.annotate( "Memory overflow!", xy=(1.05 * x, y), horizontalalignment="left", verticalalignment="center", ) break elif np.isposinf(val) and j > 0: x, y = benches[j - 1, 0], transform(benches[j - 1, i + 1]) plt.annotate( "Too slow!", xy=(1.05 * x, y), horizontalalignment="left", verticalalignment="center", ) break elif np.isneginf(val) and j > 0: x, y = benches[j - 1, 0], transform(benches[j - 1, i + 1]) plt.annotate( "Recall < 75%", xy=(1.05 * x, y), horizontalalignment="left", verticalalignment="center", ) break plt.title(to_plot) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.yscale("log") plt.xscale("log") plt.legend(loc=legend_location) plt.grid(True, which="major", linestyle="-") plt.grid(True, which="minor", linestyle="dotted") plt.axis([problem_sizes[0], problem_sizes[-1], ymin, ymax]) fmt = lambda x, pos: si_format(x, precision=0) plt.gca().xaxis.set_major_formatter(mpl.ticker.FuncFormatter(fmt)) fmt = lambda x, pos: si_format(x, precision=0) + y_suffix plt.gca().yaxis.set_major_formatter(mpl.ticker.FuncFormatter(fmt)) # plt.tight_layout() # Save as a .csv to put a nice Tikz figure in the papers: header = "Npoints, " + ", ".join(labels) os.makedirs("output", exist_ok=True) np.savetxt( f"output/{to_plot}.csv", benches, fmt="%-9.5f", header=header, comments="", delimiter=",", )
keops-main
pykeops/pykeops/benchmarks/benchmark_utils.py
""" Solving positive definite linear systems ========================================= This benchmark compares the performances of KeOps versus Numpy and Pytorch on a inverse matrix operation. It uses the functions :class:`torch.KernelSolve <pykeops.torch.KernelSolve>` (see also :doc:`here <../_auto_examples/pytorch/plot_test_invkernel_torch>`) and :class:`numpy.KernelSolve <pykeops.numpy.KernelSolve>` (see also :doc:`here <../_auto_examples/numpy/plot_test_invkernel_numpy>`). In a nutshell, given :math:`x \in\mathbb R^{N\\times D}` and :math:`b \in \mathbb R^{N\\times D_v}`, we compute :math:`a \in \mathbb R^{N\\times D_v}` so that .. math:: b = (\\alpha\operatorname{Id} + K_{x,x}) a \quad \Leftrightarrow \quad a = (\\alpha\operatorname{Id}+ K_{x,x})^{-1} b where :math:`K_{x,x} = \Big[\exp(-\|x_i -x_j\|^2 / \sigma^2)\Big]_{i,j=1}^N`. The method is based on a conjugate gradient scheme. The benchmark tests various values of :math:`N \in [10, \cdots,10^6]`. .. note:: In this demo, we implement the linear operator :math:`K_xx` using a **bruteforce** implementation and do not leverage any multiscale or low-rank (Nystroem/multipole) decomposition of the Kernel matrix. First support for these approximation schemes is scheduled for May-June 2021. Going further, advanced strategies and solvers are now available through the `GPyTorch <https://docs.gpytorch.ai/en/v1.1.1/examples/02_Scalable_Exact_GPs/KeOps_GP_Regression.html>`_ and `Falkon <https://falkonml.github.io/falkon/>`_ libraries, which rely on a KeOps backend whenever relevant. """ ##################################################################### # Setup # ----- # Standard imports: import numpy as np import torch from matplotlib import pyplot as plt from scipy.sparse import diags from scipy.sparse.linalg import aslinearoperator, cg from scipy.sparse.linalg.interface import IdentityOperator from pykeops.numpy import KernelSolve as KernelSolve_np, LazyTensor from pykeops.torch import KernelSolve from pykeops.torch.utils import squared_distances as sqdist_torch from pykeops.numpy.utils import squared_distances as sqdist_np from benchmark_utils import flatten, random_normal, unit_tensor, full_benchmark use_cuda = torch.cuda.is_available() if torch.__version__ >= "1.8": torchsolve = lambda A, B: torch.linalg.solve(A, B) else: torchsolve = lambda A, B: torch.solve(B, A)[0] ##################################################################### # Benchmark specifications: # D = 3 # Let's do this in 3D Dv = 1 # Dimension of the vectors (= number of linear problems to solve) # Numbers of samples that we'll loop upon: problem_sizes = flatten( [[1 * 10**k, 2 * 10**k, 5 * 10**k] for k in [1, 2, 3, 4, 5]] + [[10**6]] ) D = 3 # We work with 3D points Dv = 1 # and solve one problem at a time. ##################################################################### # Create some random input data: # def generate_samples(N, device="cuda", lang="torch", **kwargs): """Generates a point cloud x, a scalar signal b of size N and two regularization parameters. Args: N (int): number of point. device (str, optional): "cuda", "cpu", etc. Defaults to "cuda". lang (str, optional): "torch", "numpy", etc. Defaults to "torch". Returns: 3-uple of arrays: x, y, b """ randn = random_normal(device=device, lang=lang) ones = unit_tensor(device=device, lang=lang) x = randn((N, D)) b = randn((N, Dv)) gamma = ones((1,)) / (2 * 0.01**2) # kernel bandwidth alpha = ones((1,)) * 0.8 # regularization return x, b, gamma, alpha ###################################################################### # KeOps kernel # --------------- # # Define a Gaussian RBF kernel: # formula = "Exp(- g * SqDist(x,y)) * a" aliases = [ "x = Vi(" + str(D) + ")", # First arg: i-variable of size D "y = Vj(" + str(D) + ")", # Second arg: j-variable of size D "a = Vj(" + str(Dv) + ")", # Third arg: j-variable of size Dv "g = Pm(1)", ] # Fourth arg: scalar parameter ###################################################################### # .. note:: # This operator uses a conjugate gradient solver and assumes # that **formula** defines a **symmetric**, positive and definite # **linear** reduction with respect to the alias ``"a"`` # specified trough the third argument. ###################################################################### # Define the Kernel solver, with a ridge regularization **alpha**: # def Kinv_keops(x, b, gamma, alpha, **kwargs): Kinv = KernelSolve(formula, aliases, "a", axis=1) res = Kinv(x, x, b, gamma, alpha=alpha) return res def Kinv_keops_numpy(x, b, gamma, alpha, **kwargs): Kinv = KernelSolve_np(formula, aliases, "a", axis=1, dtype="float32") res = Kinv(x, x, b, gamma, alpha=alpha) return res def Kinv_scipy(x, b, gamma, alpha, **kwargs): x_i = LazyTensor(np.sqrt(gamma) * x[:, None, :]) y_j = LazyTensor(np.sqrt(gamma) * x[None, :, :]) K_ij = (-((x_i - y_j) ** 2).sum(2)).exp() A = aslinearoperator(diags(alpha * np.ones(x.shape[0]))) + aslinearoperator(K_ij) A.dtype = np.dtype("float32") res = cg(A, b) return res ###################################################################### # Define the same Kernel solver, using a **tensorized** implementation: # def Kinv_pytorch(x, b, gamma, alpha, **kwargs): K_xx = alpha * torch.eye(x.shape[0], device=x.get_device()) + torch.exp( -gamma * sqdist_torch(x, x) ) res = torchsolve(K_xx, b) return res def Kinv_numpy(x, b, gamma, alpha, **kwargs): K_xx = alpha * np.eye(x.shape[0]) + np.exp(-gamma * sqdist_np(x, x)) res = np.linalg.solve(K_xx, b) return res ###################################################################### # Run the benchmark # --------------------- routines = [ (Kinv_numpy, "NumPy", {"lang": "numpy"}), (Kinv_pytorch, "PyTorch", {}), (Kinv_keops_numpy, "NumPy + KeOps", {"lang": "numpy"}), (Kinv_keops, "PyTorch + KeOps", {}), (Kinv_scipy, "Scipy + KeOps", {"lang": "numpy"}), ] full_benchmark( "Inverse radial kernel matrix", routines, generate_samples, problem_sizes=problem_sizes, ) plt.show()
keops-main
pykeops/pykeops/benchmarks/plot_benchmark_invkernel.py
""" Scaling up Gaussian convolutions on 3D point clouds =========================================================== Let's compare the performances of PyTorch and KeOps on simple Gaussian RBF kernel products, as the number of samples grows from 100 to 1,000,000. .. note:: In this demo, we use exact **bruteforce** computations (tensorized for PyTorch and online for KeOps), without leveraging any multiscale or low-rank (Nystroem/multipole) decomposition of the Kernel matrix. First support for these approximation schemes is scheduled for May-June 2021. """ ############################################## # Setup # --------------------- import numpy as np import torch from matplotlib import pyplot as plt from benchmark_utils import flatten, random_normal, full_benchmark use_cuda = torch.cuda.is_available() ############################################## # Benchmark specifications: # # Numbers of samples that we'll loop upon: problem_sizes = flatten( [[1 * 10**k, 2 * 10**k, 5 * 10**k] for k in [2, 3, 4, 5]] + [[10**6]] ) D = 3 # We work with 3D points ############################################## # Synthetic dataset. Feel free to use # a Stanford Bunny, or whatever! def generate_samples(N, device="cuda", lang="torch", batchsize=1, **kwargs): """Generates two point clouds x, y and a scalar signal b of size N. Args: N (int): number of point. device (str, optional): "cuda", "cpu", etc. Defaults to "cuda". lang (str, optional): "torch", "numpy", etc. Defaults to "torch". batchsize (int, optional): number of experiments to run in parallel. Defaults to None. Returns: 3-uple of arrays: x, y, b """ randn = random_normal(device=device, lang=lang) x = randn((batchsize, N, D)) y = randn((batchsize, N, D)) b = randn((batchsize, N, 1)) return x, y, b ############################################## # Define a simple Gaussian RBF product, using a **tensorized** implementation. # Note that expanding the squared norm :math:`\|x-y\|^2` as a sum # :math:`\|x\|^2 - 2 \langle x, y \rangle + \|y\|^2` allows us # to leverage the fast matrix-matrix product of the BLAS/cuBLAS # libraries. # def gaussianconv_numpy(x, y, b, **kwargs): """(1,N,D), (1,N,D), (1,N,1) -> (1,N,1)""" # N.B.: NumPy does not really support batch matrix multiplications: x, y, b = x.squeeze(0), y.squeeze(0), b.squeeze(0) D_xx = np.sum((x**2), axis=-1)[:, None] # (N,1) D_xy = x @ y.T # (N,D) @ (D,M) = (N,M) D_yy = np.sum((y**2), axis=-1)[None, :] # (1,M) D_xy = D_xx - 2 * D_xy + D_yy # (N,M) K_xy = np.exp(-D_xy) # (B,N,M) return K_xy @ b def gaussianconv_pytorch(x, y, b, **kwargs): """(B,N,D), (B,N,D), (B,N,1) -> (B,N,1)""" D_xx = (x * x).sum(-1).unsqueeze(2) # (B,N,1) D_xy = torch.matmul(x, y.permute(0, 2, 1)) # (B,N,D) @ (B,D,M) = (B,N,M) D_yy = (y * y).sum(-1).unsqueeze(1) # (B,1,M) D_xy = D_xx - 2 * D_xy + D_yy # (B,N,M) K_xy = (-D_xy).exp() # (B,N,M) return K_xy @ b # (B,N,1) ############################################## # Define a simple Gaussian RBF product, using an **online** implementation: # from pykeops.torch import generic_sum fun_gaussianconv_keops = generic_sum( "Exp(-SqDist(X,Y)) * B", # Formula "A = Vi(1)", # Output "X = Vi({})".format(D), # 1st argument "Y = Vj({})".format(D), # 2nd argument "B = Vj(1)", # 3rd argument ) def gaussianconv_keops(x, y, b, backend="GPU", **kwargs): """(B,N,D), (B,N,D), (B,N,1) -> (B,N,1)""" x, y, b = x.squeeze(), y.squeeze(), b.squeeze() return fun_gaussianconv_keops(x, y, b, backend=backend) ############################################# # Finally, perform the same operation with our high-level :class:`pykeops.torch.LazyTensor` wrapper: from pykeops.torch import LazyTensor def gaussianconv_lazytensor(x, y, b, backend="GPU", **kwargs): """(B,N,D), (B,N,D), (B,N,1) -> (B,N,1)""" x_i = LazyTensor(x.unsqueeze(-2)) # (B, M, 1, D) y_j = LazyTensor(y.unsqueeze(-3)) # (B, 1, N, D) D_ij = ((x_i - y_j) ** 2).sum(-1) # (B, M, N, 1) K_ij = (-D_ij).exp() # (B, M, N, 1) S_ij = K_ij * b.unsqueeze(-3) # (B, M, N, 1) * (B, 1, N, 1) return S_ij.sum(dim=2, backend=backend) ############################################## # NumPy vs. PyTorch vs. KeOps (Gpu) # -------------------------------------------------------- if use_cuda: routines = [ (gaussianconv_numpy, "Numpy (CPU)", {"lang": "numpy"}), (gaussianconv_pytorch, "PyTorch (GPU)", {}), (gaussianconv_keops, "KeOps (GPU)", {}), ] full_benchmark( "Gaussian Matrix-Vector products (GPU)", routines, generate_samples, problem_sizes=problem_sizes, ) ############################################## # NumPy vs. PyTorch vs. KeOps (Cpu) # -------------------------------------------------------- routines = [ (gaussianconv_numpy, "Numpy (CPU)", {"device": "cpu", "lang": "numpy"}), (gaussianconv_pytorch, "PyTorch (CPU)", {"device": "cpu"}), (gaussianconv_keops, "KeOps (CPU)", {"device": "cpu", "backend": "CPU"}), ] full_benchmark( "Gaussian Matrix-Vector products (CPU)", routines, generate_samples, problem_sizes=problem_sizes, ) ################################################ # Genred vs. LazyTensor vs. batched LazyTensor # ------------------------------------------------ if use_cuda: routines = [ (gaussianconv_keops, "KeOps (Genred)", {}), (gaussianconv_lazytensor, "KeOps (LazyTensor)", {}), ( gaussianconv_lazytensor, "KeOps (LazyTensor, batchsize=10)", {"batchsize": 10}, ), ] full_benchmark( "Gaussian Matrix-Vector products (batch)", routines, generate_samples, problem_sizes=problem_sizes, ) plt.show()
keops-main
pykeops/pykeops/benchmarks/plot_benchmarks_convolutions_3D.py
""" Fitting a Gaussian Mixture Model ===================================== In this tutorial, we show how to use KeOps to fit a Gaussian Mixture Model with a **custom sparsity prior** through **gradient descent** on the empiric log-likelihood. """ #################################################################### # Setup # ----------- # # Standard imports: import matplotlib.cm as cm import numpy as np import torch from matplotlib import pyplot as plt from torch.nn import Module from torch.nn.functional import softmax, log_softmax from pykeops.torch import Vi, Vj, LazyTensor #################################################################### # Define our dataset: a collection of points :math:`(x_i)_{i\in[1,N]}` which describe a # spiral in the unit square. # Choose the storage place for our data : CPU (host) or GPU (device) memory. dtype = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor torch.manual_seed(0) N = 10000 # Number of samples t = torch.linspace(0, 2 * np.pi, N + 1)[:-1] x = torch.stack((0.5 + 0.4 * (t / 7) * t.cos(), 0.5 + 0.3 * t.sin()), 1) x = x + 0.02 * torch.randn(x.shape) x = x.type(dtype) x.requires_grad = True #################################################################### # Display: # Create a uniform grid on the unit square: res = 200 ticks = np.linspace(0, 1, res + 1)[:-1] + 0.5 / res X, Y = np.meshgrid(ticks, ticks) grid = torch.from_numpy(np.vstack((X.ravel(), Y.ravel())).T).contiguous().type(dtype) #################################################################### # Gaussian Mixture Model # ---------------------- # # In this tutorial, we focus on a Gaussian Mixture Model # with varying covariance matrices. For all class indices :math:`j` # in :math:`[1,M]`, we denote by :math:`w_j` the weight score # of the :math:`j`-th class, i.e. the real number such that # # .. math:: # W_j ~=~ \frac{\exp(w_j)}{\sum_k \exp(w_k)} # # is the probability assigned to the :math:`j`-th component of the mixture. # Then, we encode the (inverse) covariance matrix :math:`\Sigma_j^{-1}` of this component # through an arbitrary matrix :math:`A_j`: # # .. math:: # \Sigma_j^{-1} ~=~ A_j A_j^\intercal # # and can evaluate the likelihood of our model at any point :math:`x` through: # # .. math:: # \text{likelihood}_{(w_j),(A_j)}(x)~=~ \sum_{j=1}^M W_j\cdot (2\pi)^{-D/2}\cdot\sqrt{\text{det}(A_j A_j^\intercal) } # \cdot e^{-\tfrac{1}{2} (x - \mu_j)^\intercal \, A_j A_j^\intercal\, (x - \mu_j)}. # # The log-likelihood of a sample :math:`(x_i)` with respect to the parameters # :math:`(A_j)` and :math:`(w_j)` can thus be computed using a straightforward # log-sum-exp reduction, which is most easily implemented through # the :func:`pykeops.torch.LazyTensor` interface. # # **Custom sparsity prior.** Going further, we may allow our model # to select **adaptively** the number of **active components** # by adding a sparsity-inducing penalty on the class weights :math:`W_j`. # For instance, we could minimize the cost: # # .. math:: # \text{Cost}_{(x_i)}((w_j),(A_j)) ~=~ - \frac{1}{N}\sum_{i=1}^N \log \text{likelihood}_{(w_j),(A_j)}(x_i) # ~+~ \frac{s}{M} \sum_{j=1}^M \sqrt{W_j}, # # where the sparsity coefficient :math:`s` controls the amount of non-empty clusters. # Even though this energy cannot be optimized in closed form # through an EM-like algorithm, automatic differentiation allows us # to fit this custom model without hassle: class GaussianMixture(Module): def __init__(self, M, sparsity=0, D=2): super(GaussianMixture, self).__init__() self.params = {} # We initialize our model with random blobs scattered across # the unit square, with a small-ish radius: self.mu = torch.rand(M, D).type(dtype) self.A = 15 * torch.ones(M, 1, 1) * torch.eye(D, D).view(1, D, D) self.A = (self.A).type(dtype).contiguous() self.w = torch.ones(M, 1).type(dtype) self.sparsity = sparsity self.mu.requires_grad, self.A.requires_grad, self.w.requires_grad = ( True, True, True, ) def update_covariances(self): """Computes the full covariance matrices from the model's parameters.""" (M, D, _) = self.A.shape self.params["gamma"] = (torch.matmul(self.A, self.A.transpose(1, 2))).view( M, D * D ) / 2 def covariances_determinants(self): """Computes the determinants of the covariance matrices. N.B.: PyTorch still doesn't support batched determinants, so we have to implement this formula by hand. """ S = self.params["gamma"] if S.shape[1] == 2 * 2: dets = S[:, 0] * S[:, 3] - S[:, 1] * S[:, 2] else: raise NotImplementedError return dets.view(-1, 1) def weights(self): """Scalar factor in front of the exponential, in the density formula.""" return softmax(self.w, 0) * self.covariances_determinants().sqrt() def weights_log(self): """Logarithm of the scalar factor, in front of the exponential.""" return log_softmax(self.w, 0) + 0.5 * self.covariances_determinants().log() def likelihoods(self, sample): """Samples the density on a given point cloud.""" self.update_covariances() return ( -Vi(sample).weightedsqdist(Vj(self.mu), Vj(self.params["gamma"])) ).exp() @ self.weights() def log_likelihoods(self, sample): """Log-density, sampled on a given point cloud.""" self.update_covariances() K_ij = -Vi(sample).weightedsqdist(Vj(self.mu), Vj(self.params["gamma"])) return K_ij.logsumexp(dim=1, weight=Vj(self.weights())) def neglog_likelihood(self, sample): """Returns -log(likelihood(sample)) up to an additive factor.""" ll = self.log_likelihoods(sample) log_likelihood = torch.mean(ll) # N.B.: We add a custom sparsity prior, which promotes empty clusters # through a soft, concave penalization on the class weights. return -log_likelihood + self.sparsity * softmax(self.w, 0).sqrt().mean() def get_sample(self, N): """Generates a sample of N points.""" raise NotImplementedError() def plot(self, sample): """Displays the model.""" plt.clf() # Heatmap: heatmap = self.likelihoods(grid) heatmap = ( heatmap.view(res, res).data.cpu().numpy() ) # reshape as a "background" image scale = np.amax(np.abs(heatmap[:])) plt.imshow( -heatmap, interpolation="bilinear", origin="lower", vmin=-scale, vmax=scale, cmap=cm.RdBu, extent=(0, 1, 0, 1), ) # Log-contours: log_heatmap = self.log_likelihoods(grid) log_heatmap = log_heatmap.view(res, res).data.cpu().numpy() scale = np.amax(np.abs(log_heatmap[:])) levels = np.linspace(-scale, scale, 41) plt.contour( log_heatmap, origin="lower", linewidths=1.0, colors="#C8A1A1", levels=levels, extent=(0, 1, 0, 1), ) # Scatter plot of the dataset: xy = sample.data.cpu().numpy() plt.scatter(xy[:, 0], xy[:, 1], 100 / len(xy), color="k") #################################################################### # Optimization # ------------ # # In typical PyTorch fashion, we fit our Mixture Model # to the data through a stochastic gradient descent on our empiric log-likelihood, # with a sparsity-inducing penalty: model = GaussianMixture(30, sparsity=20) optimizer = torch.optim.Adam([model.A, model.w, model.mu], lr=0.1) loss = np.zeros(501) for it in range(501): optimizer.zero_grad() # Reset the gradients (PyTorch syntax...). cost = model.neglog_likelihood(x) # Cost to minimize. cost.backward() # Backpropagate to compute the gradient. optimizer.step() loss[it] = cost.data.cpu().numpy() # sphinx_gallery_thumbnail_number = 6 if it in [0, 10, 100, 150, 250, 500]: plt.pause(0.01) plt.figure(figsize=(8, 8)) model.plot(x) plt.title("Density, iteration " + str(it), fontsize=20) plt.axis("equal") plt.axis([0, 1, 0, 1]) plt.tight_layout() plt.pause(0.01) #################################################################### # Monitor the optimization process: # plt.figure() plt.plot(loss) plt.tight_layout() plt.show()
keops-main
pykeops/pykeops/tutorials/gaussian_mixture/plot_gaussian_mixture.py
""" ================================= K-NN classification - NumPy API ================================= The :meth:`pykeops.numpy.LazyTensor.argKmin` reduction supported by KeOps :class:`pykeops.numpy.LazyTensor` allows us to perform **bruteforce k-nearest neighbors search** with four lines of code. It can thus be used to implement a **large-scale** `K-NN classifier <https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm>`_, **without memory overflows**. """ ############################# # Setup # ----------------- # Standard imports: import time import numpy as np from matplotlib import pyplot as plt from pykeops.numpy import LazyTensor import pykeops.config dtype = "float32" ############################# # Dataset, in 2D: N, D = ( 10000 if pykeops.config.gpu_available else 1000, 2, ) # Number of samples, dimension x = np.random.rand(N, D).astype(dtype) # Random samples on the unit square # Random-ish class labels: def fth(x): return 3 * x * (x - 0.5) * (x - 1) + x cl = x[:, 1] + 0.1 * np.random.randn(N).astype(dtype) < fth(x[:, 0]) ############################# # Reference sampling grid, on the unit square: M = 1000 if pykeops.config.gpu_available else 100 tmp = np.linspace(0, 1, M).astype(dtype) g1, g2 = np.meshgrid(tmp, tmp) g = np.hstack((g1.reshape(-1, 1), g2.reshape(-1, 1))) ############################# # K-Nearest Neighbors search # ---------------------------- ############################## # Peform the K-NN classification, with a fancy display: # plt.figure(figsize=(12, 8)) plt.subplot(2, 3, 1) plt.scatter(x[:, 0], x[:, 1], c=cl, s=2) plt.imshow(np.ones((2, 2)), extent=(0, 1, 0, 1), alpha=0) plt.axis("off") plt.axis([0, 1, 0, 1]) plt.title("{:,} data points,\n{:,} grid points".format(N, M * M)) for (i, K) in enumerate((1, 3, 10, 20, 50)): start = time.time() # Benchmark: G_i = LazyTensor(g[:, None, :]) # (M**2, 1, 2) X_j = LazyTensor(x[None, :, :]) # (1, N, 2) D_ij = ((G_i - X_j) ** 2).sum(-1) # (M**2, N) symbolic matrix of squared distances indKNN = D_ij.argKmin(K, dim=1) # Grid <-> Samples, (M**2, K) integer tensor clg = np.mean(cl[indKNN], axis=1) > 0.5 # Classify the Grid points end = time.time() plt.subplot(2, 3, i + 2) # Fancy display: clg = np.reshape(clg, (M, M)) plt.imshow(clg, extent=(0, 1, 0, 1), origin="lower") plt.axis("off") plt.axis([0, 1, 0, 1]) plt.tight_layout() plt.title("{}-NN classifier,\n t = {:.2f}s".format(K, end - start)) plt.show()
keops-main
pykeops/pykeops/tutorials/knn/plot_knn_numpy.py
""" ================================= K-NN classification - PyTorch API ================================= The :mod:`.argKmin(K)` reduction supported by KeOps :class:`pykeops.torch.LazyTensor` allows us to perform **bruteforce k-nearest neighbors search** with four lines of code. It can thus be used to implement a **large-scale** `K-NN classifier <https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm>`_, **without memory overflows**. """ ##################################################################### # Setup # ----------------- # Standard imports: import time import numpy as np import torch from matplotlib import pyplot as plt from pykeops.torch import LazyTensor use_cuda = torch.cuda.is_available() dtype = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor ###################################################################### # Dataset, in 2D: N, D = 10000 if use_cuda else 1000, 2 # Number of samples, dimension x = torch.rand(N, D).type(dtype) # Random samples on the unit square # Random-ish class labels: def fth(x): return 3 * x * (x - 0.5) * (x - 1) + x cl = x[:, 1] + 0.1 * torch.randn(N).type(dtype) < fth(x[:, 0]) ####################################################################### # Reference sampling grid, on the unit square: M = 1000 if use_cuda else 100 tmp = torch.linspace(0, 1, M).type(dtype) g2, g1 = torch.meshgrid(tmp, tmp) g = torch.cat((g1.contiguous().view(-1, 1), g2.contiguous().view(-1, 1)), dim=1) ###################################################################### # K-Nearest Neighbors search # ---------------------------- ##################################################################### # Peform the K-NN classification, with a fancy display: # plt.figure(figsize=(12, 8)) plt.subplot(2, 3, 1) plt.scatter(x.cpu()[:, 0], x.cpu()[:, 1], c=cl.cpu(), s=2) plt.imshow(np.ones((2, 2)), extent=(0, 1, 0, 1), alpha=0) plt.axis("off") plt.axis([0, 1, 0, 1]) plt.title("{:,} data points,\n{:,} grid points".format(N, M * M)) for (i, K) in enumerate((1, 3, 10, 20, 50)): start = time.time() # Benchmark: G_i = LazyTensor(g[:, None, :]) # (M**2, 1, 2) X_j = LazyTensor(x[None, :, :]) # (1, N, 2) D_ij = ((G_i - X_j) ** 2).sum(-1) # (M**2, N) symbolic matrix of squared distances indKNN = D_ij.argKmin(K, dim=1) # Grid <-> Samples, (M**2, K) integer tensor clg = cl[indKNN].float().mean(1) > 0.5 # Classify the Grid points end = time.time() plt.subplot(2, 3, i + 2) # Fancy display: clg = clg.view(M, M) plt.imshow(clg.cpu(), extent=(0, 1, 0, 1), origin="lower") plt.axis("off") plt.axis([0, 1, 0, 1]) plt.tight_layout() plt.title("{}-NN classifier,\n t = {:.2f}s".format(K, end - start)) plt.show()
keops-main
pykeops/pykeops/tutorials/knn/plot_knn_torch.py
""" ========================================= K-NN on the MNIST dataset - PyTorch API ========================================= The :mod:`.argKmin(K)` reduction supported by KeOps :class:`pykeops.torch.LazyTensor` allows us to perform **bruteforce k-nearest neighbors search** with four lines of code. It can thus be used to implement a **large-scale** `K-NN classifier <https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm>`_, **without memory overflows** on the full `MNIST <http://yann.lecun.com/exdb/mnist/>`_ dataset. """ ##################################################################### # Setup # ----------------- # Standard imports: import time import torch from matplotlib import pyplot as plt from pykeops.torch import LazyTensor use_cuda = torch.cuda.is_available() tensor = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor ###################################################################### # Load the MNIST dataset: 70,000 images of shape (28,28). try: from sklearn.datasets import fetch_openml except ImportError: raise ImportError("This tutorial requires Scikit Learn version >= 0.20.") mnist = fetch_openml("mnist_784", cache=False, as_frame=False) x = tensor(mnist.data.astype("float32")) y = tensor(mnist.target.astype("int64")) ###################################################################### # Split it into a train and test set: D = x.shape[1] Ntrain, Ntest = (60000, 10000) if use_cuda else (1000, 100) x_train, y_train = x[:Ntrain, :].contiguous(), y[:Ntrain].contiguous() x_test, y_test = ( x[Ntrain : Ntrain + Ntest, :].contiguous(), y[Ntrain : Ntrain + Ntest].contiguous(), ) ###################################################################### # K-Nearest Neighbors search # ---------------------------- # Perform the K-NN classification on 10,000 test images in dimension 784: # K = 3 # N.B.: K has very little impact on the running time start = time.time() # Benchmark: X_i = LazyTensor(x_test[:, None, :]) # (10000, 1, 784) test set X_j = LazyTensor(x_train[None, :, :]) # (1, 60000, 784) train set D_ij = ((X_i - X_j) ** 2).sum( -1 ) # (10000, 60000) symbolic matrix of squared L2 distances ind_knn = D_ij.argKmin(K, dim=1) # Samples <-> Dataset, (N_test, K) lab_knn = y_train[ind_knn] # (N_test, K) array of integers in [0,9] y_knn, _ = lab_knn.mode() # Compute the most likely label if use_cuda: torch.cuda.synchronize() end = time.time() error = (y_knn != y_test).float().mean().item() time = end - start print( "{}-NN on the full MNIST dataset: test error = {:.2f}% in {:.2f}s.".format( K, error * 100, time ) ) ###################################################################### # Fancy display: looks good! plt.figure(figsize=(12, 8)) for i in range(6): ax = plt.subplot(2, 3, i + 1) ax.imshow((255 - x_test[i]).view(28, 28).detach().cpu().numpy(), cmap="gray") ax.set_title("label = {}".format(y_knn[i].int())) plt.axis("off") plt.show()
keops-main
pykeops/pykeops/tutorials/knn/plot_knn_mnist.py
""" ========================================== Linking KeOps with scipy.sparse.linalg ========================================== The `scipy library <https://docs.scipy.org/doc/scipy/reference/sparse.linalg.html>`_ provides a simple abstraction for implicit tensors: the `LinearOperator <https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.LinearOperator.html>`_ class, which represents generic "Matrix-Vector" products and can be plugged seamlessly in a `large collection <https://docs.scipy.org/doc/scipy/reference/sparse.linalg.html>`_ of linear algebra routines. Crucially, KeOps :class:`pykeops.torch.LazyTensor` are now **fully compatible** with this interface. As an example, let's see how to combine KeOps with a `fast eigenproblem solver <https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.eigsh.html>`_ to compute **spectral coordinates** on a large 2D or 3D point cloud. .. note:: Ideally, we'd like to interface KeOps with some methods of the `scikit-learn library <https://scikit-learn.org/stable/>`_... But this seems out of reach, as most of the sklearn codebase relies internally on **explicit numpy arrays**. One day, maybe! """ ##################################################################### # Setup # ----------------- # Standard imports: # import matplotlib.pyplot as plt import numpy as np # noinspection PyUnresolvedReferences from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import from pykeops.numpy import LazyTensor import pykeops.config dtype = "float32" # No need for double precision here! ################################################################### # Create a toy dataset, a spiral in 2D sampled with 10,000 points: N = 10000 if pykeops.config.gpu_available else 1000 t = np.linspace(0, 2 * np.pi, N + 1)[:-1] x = np.stack((0.4 + 0.4 * (t / 7) * np.cos(t), 0.5 + 0.3 * np.sin(t)), 1) x = x + 0.01 * np.random.randn(*x.shape) x = x.astype(dtype) ################################################################### # And display it: # plt.figure(figsize=(8, 8)) plt.scatter(x[:, 0], x[:, 1], s=5000 / len(x)) plt.axis("equal") plt.axis([0, 1, 0, 1]) plt.tight_layout() plt.show() ####################################################################### # Spectral coordinates # ------------------------------- # # To showcase the potential of the KeOps-SciPy interface, # we now perform **spectral analysis** on the point cloud **x**. # As summarized by the `Wikipedia page on spectral clustering <https://en.wikipedia.org/wiki/Spectral_clustering>`_, # spectral coordinates can be defined as the **eigenvectors** associated # to the smallest eigenvalues of a `graph Laplacian <https://en.wikipedia.org/wiki/Laplacian_matrix>`_. # # When no explicit **adjacency matrix** is available, # a simple choice is to use a **soft kernel matrix** such as # the Gaussian RBF matrix: # # .. math:: # K_{i,j} ~=~ \exp\big( - \tfrac{1}{2\sigma^2}\|x_i-x_j\|^2 \big), # # which puts # a smooth link between neighboring points at scale :math:`\sigma`. # sigma = 0.05 x_ = x / sigma x_i, x_j = LazyTensor(x_[:, None, :]), LazyTensor(x_[None, :, :]) K_xx = (-((x_i - x_j) ** 2).sum(2) / 2).exp() # Symbolic (N,N) Gaussian kernel matrix print(K_xx) ######################################################################## # Linear operators # ~~~~~~~~~~~~~~~~~ # # As far as **scipy** is concerned, a KeOps :class:`pykeops.torch.LazyTensor` such # as **K_xx** can be directly understood as a # `LinearOperator <https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.LinearOperator.html>`_: from scipy.sparse.linalg import aslinearoperator K = aslinearoperator(K_xx) ######################################################### # Just like regular numpy :mod:`arrays` or KeOps :class:`pykeops.torch.LazyTensor`, # :mod:`LinearOperators` fully support the "matrix" product operator ``@``. # For instance, to compute the mass coefficients # # .. math:: # D_i = \sum_{j=1}^N K_{i,j}, # # we can simply write: D = K @ np.ones(N, dtype=dtype) # Sum along the lines of the adjacency matrix ####################################################################### # Going further, robust and efficient routines such as # `eigsh <https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.eigsh.html>`_ # can be used to compute the largest (or smallest) eigenvalues of our kernel matrix **K** # at a reasonable computational cost: # from scipy.sparse.linalg import eigsh eigenvalues, eigenvectors = eigsh(K, k=5) # Largest 5 eigenvalues/vectors print("Largest eigenvalues:", eigenvalues) print("Eigenvectors of shape:", eigenvectors.shape) ############################################ # Graph Laplacian # ~~~~~~~~~~~~~~~~~~~ # # Most importantly, :mod:`LinearOperators` can be composed # or added with each other. # To define our implicit **graph Laplacian matrix**: # # .. math:: # L= \text{diag}(D) - K, # # we can simply type: from scipy.sparse import diags L = aslinearoperator(diags(D)) - K L.dtype = np.dtype( dtype ) # Scipy Bugfix: by default, "-" removes the dtype information... ################################################## # Alternatively, we can also use a **symmetric, normalized Laplacian matrix** defined through: # # .. math:: # L_{\text{norm}}= \text{Id} - \text{diag}(D^{-1/2}) K \text{diag}(D^{-1/2}). from scipy.sparse.linalg.interface import IdentityOperator D_2 = aslinearoperator(diags(1 / np.sqrt(D))) L_norm = IdentityOperator((N, N)) - D_2 @ K @ D_2 L_norm.dtype = np.dtype( dtype ) # Scipy Bugfix: by default, "-" removes the dtype information... ################################################## # Then, computing spectral coordinates on **x** is as simple # as typing: # from time import time start = time() # Compute the 7 smallest eigenvalues/vectors of our graph Laplacian eigenvalues, coordinates = eigsh(L, k=7, which="SM") print( "Smallest eigenvalues of the graph Laplacian, computed in {:.3f}s:".format( time() - start ) ) print(eigenvalues) ################################################### # **That's it!** # As expected, our first eigenvalue is equal to 0, # up to the convergence of the `Lanczos-like algorithm <https://en.wikipedia.org/wiki/Lanczos_algorithm>`_ # used internally by **eigsh**. # The spectral coordinates, associated to the **smallest positive eigenvalues** # of our graph Laplacian, can then be displayed as signals on # the raw point cloud **x** and be used to perform # spectral clustering, shape matching or whatever's relevant! _, axarr = plt.subplots(nrows=2, ncols=3, figsize=(12, 8)) for i in range(2): for j in range(3): axarr[i][j].scatter( x[:, 0], x[:, 1], c=coordinates[:, 3 * i + j], cmap=plt.cm.Spectral, s=9 * 500 / len(x), ) axarr[i][j].set_title( "Eigenvalue {} = {:.2f}".format(3 * i + j + 1, eigenvalues[3 * i + j]) ) axarr[i][j].set_aspect("equal") axarr[i][j].set_xlim(0, 1) axarr[i][j].set_ylim(0, 1) plt.tight_layout() plt.show() ############################################################### # Scaling up to large datasets with block-sparse matrices # --------------------------------------------------------------- # # Going further, :class:`pykeops.torch.LazyTensor` support # adaptive **block-sparsity patterns** (specified through an optional **.ranges** attribute) # which allow us to perform large matrix-vector products with **sub-quadratic** complexity. # To illustrate this advanced feature of KeOps, # let's generate a large "noisy Swiss roll" with **1,000,000 points** in the unit cube: # N = 1000000 if pykeops.config.gpu_available else 1000 t = np.linspace(0, 2 * np.pi, N + 1)[:-1] x = np.stack( ( 0.4 + 0.4 * (t / 7) * np.cos(1.5 * t), 0.1 + 0.8 * np.random.rand(N), 0.5 + 0.3 * (t / 7) * np.sin(1.5 * t), ), 1, ) x = x + 0.01 * np.random.randn(*x.shape) x = x.astype(dtype) ################################################################ # To **display** our toy dataset with the (not-so-efficient) PyPlot library, # we pick **10,000 points** at random: N_display = 10000 if pykeops.config.gpu_available else N indices_display = np.random.randint(0, N, N_display) _, ax = plt.subplots(nrows=1, ncols=1, figsize=(8, 8), subplot_kw=dict(projection="3d")) x_ = x[indices_display, :] ax.scatter3D(x_[:, 0], x_[:, 1], x_[:, 2], c=t[indices_display], cmap=plt.cm.Spectral) ax.set_title("{:,} out of {:,} points in our source point cloud".format(N_display, N)) plt.show() #################################################################### # **Can we scale the spectral analysis presented above to this huge dataset?** # # In practice, the radius :math:`\sigma` of our # kernel "adjacency" function is often **much smaller than the diameter of the input point cloud**: # spectral methods rely on *small-range* neighborhoods to build # a *global* coordinate system. # Since :math:`k(x,y) \simeq 0` above a threshold of, say, :math:`4\sigma`, # a simple way of accelerating # the kernel-vector product :math:`v\mapsto K_{xx}v` in the (soft-)graph Laplacian is thus to # **skip computations** between pairs of points that are far away from each other. # # As explained in :doc:`the documentation <../../python/sparsity>`, # fast GPU routines rely heavily on **memory contiguity**: # before going any further, we must # **sort our input dataset** to make sure that neighboring points are stored # next to each other on the device memory. As detailed in the # :doc:`KeOps+NumPy tutorial on block-sparse reductions <../../_auto_examples/numpy/plot_grid_cluster_numpy>`, # a simple way of doing so is to write: # Import the KeOps helper routines for block-sparse reductions: from pykeops.numpy.cluster import ( grid_cluster, cluster_ranges_centroids, sort_clusters, from_matrix, ) # Put our points in cubic bins of size eps, as we compute a vector of class labels: eps = 0.05 x_labels = grid_cluster(x, eps) # Compute the memory footprint and centroid of each of those non-empty "cubic" clusters: x_ranges, x_centroids, _ = cluster_ranges_centroids(x, x_labels) # Sort our dataset according to the vector of labels: x, x_labels = sort_clusters(x, x_labels) ############################################################################# # # .. note:: # In higher-dimensional settings, the simplistic # :func:`grid_cluster <pykeops.numpy.cluster.grid_cluster>` # scheme could be replaced by a more versatile routine such as # our :doc:`KeOps+NumPy K-means implementation <../kmeans/plot_kmeans_numpy>`. # # Points are now roughly sorted # according to their locations, with each cluster corresponding to # a contiguous slice of the (sorted) **x** array: _, ax = plt.subplots(nrows=1, ncols=1, figsize=(8, 8), subplot_kw=dict(projection="3d")) x_ = x[indices_display, :] ax.scatter3D(x_[:, 0], x_[:, 1], x_[:, 2], c=x_labels[indices_display], cmap="prism") ax.set_title("Cluster labels") plt.show() ############################################################################ # We can prune computations out of the :math:`v\mapsto K_{xx} v` # matrix-vector product in a GPU-friendly way by **skipping whole blocks** # of cluster-cluster interactions. # A good rule of thumb is to **only consider pairs of points** belonging # to clusters :math:`X` and :math:`Y` whose centroids :math:`x_c` and # :math:`y_c` are such that: # # .. math:: # \|x_c - y_c\|^2 < \big( 4\sigma + \tfrac{1}{2}\text{diam}(X) + \tfrac{1}{2}\text{diam}(Y) \big)^2. # # Considering that our cubic bins of size :math:`\varepsilon` all have a # diameter that is equal to :math:`\sqrt{3}\,\varepsilon`, this "block-sparsity" # pattern can be encoded in a small boolean matrix **keep** computed through: sigma = ( 0.01 if pykeops.config.gpu_available else 0.1 ) # Standard deviation of our Gaussian kernel # Compute a coarse Boolean mask: D = np.sum((x_centroids[:, None, :] - x_centroids[None, :, :]) ** 2, 2) keep = D < (4 * sigma + np.sqrt(3) * eps) ** 2 ############################################################### # which can then be converted to a GPU-friendly, # `LIL-like sparsity pattern <https://en.wikipedia.org/wiki/Sparse_matrix#List_of_lists_(LIL)>`_ # with the :func:`from_matrix <pykeops.numpy.cluster.from_matrix>` helper: ranges_ij = from_matrix(x_ranges, x_ranges, keep) ############################################################################ # Now, leveraging this information with KeOps is as simple # as typing: x_ = x / sigma # N.B.: x is a **sorted** list of points x_i, x_j = LazyTensor(x_[:, None, :]), LazyTensor(x_[None, :, :]) K_xx = (-((x_i - x_j) ** 2).sum(2) / 2).exp() # Symbolic (N,N) Gaussian kernel matrix K_xx.ranges = ranges_ij # block-sparsity pattern print(K_xx) ############################################################################ # A straightforward computation shows that our new # **block-sparse** operator may be **up to 20 times more efficient** than a # full KeOps :class:`pykeops.torch.LazyTensor`: # Compute the area of each rectangle "cluster-cluster" tile in the full kernel matrix: areas = (x_ranges[:, 1] - x_ranges[:, 0])[:, None] * (x_ranges[:, 1] - x_ranges[:, 0])[ None, : ] total_area = np.sum(areas) # should be equal to N**2 = 1e12 sparse_area = np.sum(areas[keep]) print( "We keep {:.2e}/{:.2e} = {:2d}% of the original kernel matrix.".format( sparse_area, total_area, int(100 * sparse_area / total_area) ) ) ############################################################################ # Good. Once we're done with these pre-processing steps, # block-sparse :class:`pykeops.torch.LazyTensor` are just as easy to interface with **scipy** as # regular NumPy arrays: K = aslinearoperator(K_xx) ########################################################################## # The normalized graph Laplacian can be defined as usual: D = K @ np.ones(N, dtype=dtype) # Sum along the lines of the adjacency matrix D_2 = aslinearoperator(diags(1 / np.sqrt(D))) L_norm = IdentityOperator((N, N)) - D_2 @ K @ D_2 L_norm.dtype = np.dtype( dtype ) # Scipy Bugfix: by default, "-" removes the dtype information... ########################################################################## # And our favourite solver will compute, as expected, # the smallest eigenvalues of this custom operator: from time import time start = time() # Compute the 7 smallest eigenvalues/vectors of our normalized graph Laplacian eigenvalues, coordinates = eigsh(L_norm, k=7, which="SM") print( "Smallest eigenvalues of the normalized graph Laplacian, computed in {:.3f}s ".format( time() - start ) + "on a cloud of {:,} points in dimension {}:".format(x.shape[0], x.shape[1]) ) print(eigenvalues) ########################################################################## # # .. note:: # On very large problems, a custom eigenproblem solver # implemented with the **PyTorch+KeOps** interface should be sensibly **faster** # than this SciPy wrapper: performing all computations on the GPU # would allow us to perform linear operations in parallel # and to **skip hundreds of unnecessary Host-Device memory transfers**. # # Anyway. Displayed on a subsampled point cloud (for the sake of efficiency), # our spectral coordinates look good! x_ = x[indices_display, :] # sphinx_gallery_thumbnail_number = 5 _, axarr = plt.subplots( nrows=2, ncols=3, figsize=(12, 8), subplot_kw=dict(projection="3d") ) for i in range(2): for j in range(3): axarr[i][j].scatter3D( x_[:, 0], x_[:, 1], x_[:, 2], c=coordinates[indices_display, 3 * i + j], cmap=plt.cm.Spectral, ) axarr[i][j].set_title( "Eigenvalue {} = {:.1e}".format(3 * i + j + 1, eigenvalues[3 * i + j]) ) plt.tight_layout() plt.show()
keops-main
pykeops/pykeops/tutorials/backends/plot_scipy.py
""" ================================= Linking KeOps with GPytorch ================================= Out-of-the-box, KeOps only provides :ref:`limited support <interpolation-tutorials>` for `Kriging <https://en.wikipedia.org/wiki/Kriging>`_ or `Gaussian process regression <https://scikit-learn.org/stable/modules/gaussian_process.html>`_: the :class:`KernelSolve <pykeops.torch.KernelSolve>` operator implements a conjugate gradient solver for kernel linear systems... and that's about it. Fortunately though, KeOps can easily be used as a scalable GPU backend for versatile, high-level libraries such as `GPytorch <https://gpytorch.ai/>`_: in this notebook, we show how to plug KeOps' :class:`pykeops.torch.LazyTensor` within the first `regression tutorial <https://docs.gpytorch.ai/en/v1.1.1/examples/01_Exact_GPs/Simple_GP_Regression.html>`_ of GPytorch's documentation. Due to hard-coded constraints within the structure of GPytorch, the syntax presented below is pretty verbose... But **we're working on it**! Needless to say, feel free to `let us know <https://github.com/getkeops/keops/issues>`_ if you encounter any unexpected behavior with this experimental KeOps-GPytorch interface. .. note:: The GPytorch team has now integrated `explicit KeOps kernels <https://github.com/cornellius-gp/gpytorch/tree/main/gpytorch/kernels/keops>`_ within their repository: they are documented `in this tutorial <https://docs.gpytorch.ai/en/v1.1.1/examples/02_Scalable_Exact_GPs/KeOps_GP_Regression.html>`_ and make the handcrafted example below somewhat obsolete. Nevertheless, we keep this page online for the sake of completeness: it may be useful to advanced users who wish to use custom KeOps kernels with GPytorch. """ ##################################################################### # Setup # ----------------- # Standard imports, including `gpytorch <https://gpytorch.ai/>`_: import gpytorch import math import torch from matplotlib import pyplot as plt use_cuda = torch.cuda.is_available() dtype = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor ##################################################################### # We generate a toy dataset: some regularly spaced samples on the unit interval, # and a sinusoid signal corrupted by a small Gaussian noise. N = 1000 if use_cuda else 100 train_x = torch.linspace(0, 1, N).type(dtype) train_y = torch.sin(train_x * (2 * math.pi)) + 0.2 * torch.randn(train_x.size()).type( dtype ) ##################################################################### # Defining a new KeOps RBF kernel # --------------------------------- # # Internally, GPytorch relies on `LazyTensors <https://gpytorch.readthedocs.io/en/latest/lazy.html>`_ # parameterized by explicit **torch Tensors** - and **nothing** else. # To let GPytorch use our KeOps CUDA routines, we should thus create # a new class of :mod:`gpytorch.lazy.LazyTensor`, encoding an implicit # kernel matrix built from raw point clouds **x_i** and **y_j**. # # .. note:: # Ideally, we'd like to be able to **export KeOps LazyTensors** directly as # GPytorch objects, but the reliance of the latter's internal engine on # explicit **torch.Tensor** variables is a hurdle that we could not bypass # easily. Working on this problem with the GPytorch team, # we hope to provide a simpler interface in future releases. from pykeops.torch import LazyTensor class KeOpsRBFLazyTensor(gpytorch.lazy.LazyTensor): def __init__(self, x_i, y_j): """Creates a symbolic Gaussian RBF kernel out of two point clouds `x_i` and `y_j`.""" super().__init__( x_i, y_j ) # GPytorch will remember that self was built from x_i and y_j self.x_i, self.y_j = x_i, y_j # Useful to define a symbolic transpose with torch.autograd.enable_grad(): # N.B.: gpytorch operates in no_grad mode x_i, y_j = ( LazyTensor(self.x_i[:, None, :]), LazyTensor(self.y_j[None, :, :]), ) K_xy = ( -((x_i - y_j) ** 2).sum(-1) / 2 ).exp() # Compute the kernel matrix symbolically... self.K = K_xy # ... and store it for later use def _matmul(self, M): """Kernel-Matrix multiplication.""" return self.K @ M def _size(self): """Shape attribute.""" return torch.Size(self.K.shape) def _transpose_nonbatch(self): """Symbolic transpose operation.""" return KeOpsRBFLazyTensor(self.y_j, self.x_i) def _get_indices(self, row_index, col_index, *batch_indices): """Returns a (small) explicit sub-matrix, used e.g. for Nystroem approximation.""" X_i = self.x_i[row_index] Y_j = self.y_j[col_index] return (-((X_i - Y_j) ** 2).sum(-1) / 2).exp() # Genuine torch.Tensor def _quad_form_derivative(self, *args, **kwargs): """As of gpytorch v0.3.2, the default implementation returns a list instead of a tuple...""" return tuple(super()._quad_form_derivative(*args, **kwargs)) # Bugfix! ##################################################################### # We can now create a new GPytorch **Kernel** object, wrapped around # our KeOps+GPytorch LazyTensor: class KeOpsRBFKernel(gpytorch.kernels.Kernel): """Simple KeOps re-implementation of 'gpytorch.kernels.RBFKernel'.""" has_lengthscale = True def forward(self, x1, x2, diag=False, **params): if diag: # A Gaussian RBF kernel only has "ones" on the diagonal return torch.ones(len(x1)).type_as(x1) else: if x1.dim() == 1: x1 = x1.view(-1, 1) if x2.dim() == 1: x2 = x2.view(-1, 1) # Rescale the input data... x_i, y_j = x1.div(self.lengthscale), x2.div(self.lengthscale) return KeOpsRBFLazyTensor( x_i, y_j ) # ... and return it as a gyptorch.lazy.LazyTensor ##################################################################### # And use it to define a new Gaussian Process model: # We will use the simplest form of GP model, exact inference class KeOpsGPModel(gpytorch.models.ExactGP): def __init__(self, train_x, train_y, likelihood): super().__init__(train_x, train_y, likelihood) self.mean_module = gpytorch.means.ConstantMean() self.covar_module = gpytorch.kernels.ScaleKernel(KeOpsRBFKernel()) def forward(self, x): mean_x = self.mean_module(x) covar_x = self.covar_module(x) return gpytorch.distributions.MultivariateNormal(mean_x, covar_x) ########################################################## # **N.B., for the sake of comparison:** the GPytorch documentation went with # the code below, using the standard :meth:`gpytorch.kernels.RBFKernel()` # instead of our custom :meth:`KeOpsRBFKernel()`: class ExactGPModel(gpytorch.models.ExactGP): def __init__(self, train_x, train_y, likelihood): super(ExactGPModel, self).__init__(train_x, train_y, likelihood) self.mean_module = gpytorch.means.ConstantMean() self.covar_module = gpytorch.kernels.ScaleKernel(gpytorch.kernels.RBFKernel()) def forward(self, x): mean_x = self.mean_module(x) covar_x = self.covar_module(x) return gpytorch.distributions.MultivariateNormal(mean_x, covar_x) ########################################################## # **That's it!** We can now initialize our likelihood and model, as recommended by the documentation: if use_cuda: likelihood = gpytorch.likelihoods.GaussianLikelihood().cuda() model = KeOpsGPModel(train_x, train_y, likelihood).cuda() else: likelihood = gpytorch.likelihoods.GaussianLikelihood() model = KeOpsGPModel(train_x, train_y, likelihood) ##################################################################### # GP training # ----------------- # The code below is now a direct copy-paste from the # `GPytorch 101 tutorial <https://docs.gpytorch.ai/en/v1.1.1/examples/01_Exact_GPs/Simple_GP_Regression.html>`_: # Find optimal model hyperparameters model.train() likelihood.train() # Use the adam optimizer optimizer = torch.optim.Adam( [ {"params": model.parameters()}, ], lr=0.1, # Includes GaussianLikelihood parameters ) # "Loss" for GPs - the marginal log likelihood mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, model) training_iter = 50 for i in range(training_iter): # Zero gradients from previous iteration optimizer.zero_grad() # Output from model output = model(train_x) # Calc loss and backprop gradients loss = -mll(output, train_y) loss.backward() if i % 10 == 0 or i == training_iter - 1: print( "Iter %d/%d - Loss: %.3f lengthscale: %.3f noise: %.3f" % ( i + 1, training_iter, loss.item(), model.covar_module.base_kernel.lengthscale.item(), model.likelihood.noise.item(), ) ) optimizer.step() ##################################################################### # Prediction and display # ------------------------- # Get into evaluation (predictive posterior) mode # model.eval() likelihood.eval() ##################################################################### # Test points are regularly spaced along [0,1]. # We make predictions by feeding our ``model`` through the ``likelihood``: with torch.no_grad(), gpytorch.settings.fast_pred_var(): test_x = torch.linspace(0, 1, 51).type(dtype) observed_pred = likelihood(model(test_x)) ##################################################################### # Display: # with torch.no_grad(): # Initialize plot f, ax = plt.subplots(1, 1, figsize=(12, 9)) # Get upper and lower confidence bounds lower, upper = observed_pred.confidence_region() # Plot training data as black stars ax.plot(train_x.cpu().numpy(), train_y.cpu().numpy(), "k*") # Plot predictive means as blue line ax.plot(test_x.cpu().numpy(), observed_pred.mean.cpu().numpy(), "b") # Shade between the lower and upper confidence bounds ax.fill_between( test_x.cpu().numpy(), lower.cpu().numpy(), upper.cpu().numpy(), alpha=0.5 ) ax.set_ylim([-3, 3]) ax.legend(["Observed Data", "Mean", "Confidence"]) plt.axis([0, 1, -2, 2]) plt.tight_layout() plt.show()
keops-main
pykeops/pykeops/tutorials/backends/plot_gpytorch.py
""" ==================== Surface registration ==================== Example of a diffeomorphic matching of surfaces using varifolds metrics: We perform an LDDMM matching of two meshes using the geodesic shooting algorithm. """ #################################################################### # Define our dataset # ------------------ # # Standard imports import os import time import torch from torch.autograd import grad import plotly.graph_objs as go from pykeops.torch import Vi, Vj # torch type and device use_cuda = torch.cuda.is_available() torchdeviceId = torch.device("cuda:0") if use_cuda else "cpu" torchdtype = torch.float32 # PyKeOps counterpart KeOpsdeviceId = torchdeviceId.index # id of Gpu device (in case Gpu is used) KeOpsdtype = torchdtype.__str__().split(".")[1] # 'float32' #################################################################### # Import data file, one of : # # * "hippos.pt" : original data (6611 vertices), # * "hippos_red.pt" : reduced size (1654 vertices), # * "hippos_reduc.pt" : further reduced (662 vertices), # * "hippos_reduc_reduc.pt" : further reduced (68 vertices) if use_cuda: datafile = "data/hippos.pt" else: datafile = "data/hippos_reduc_reduc.pt" ################################################################## # Define the kernels # ------------------ # # Define Gaussian kernel :math:`(K(x,y)b)_i = \sum_j \exp(-\gamma\|x_i-y_j\|^2)b_j` def GaussKernel(sigma): x, y, b = Vi(0, 3), Vj(1, 3), Vj(2, 3) gamma = 1 / (sigma * sigma) D2 = x.sqdist(y) K = (-D2 * gamma).exp() return (K * b).sum_reduction(axis=1) ################################################################### # Define "Gaussian-CauchyBinet" kernel :math:`(K(x,y,u,v)b)_i = \sum_j \exp(-\gamma\|x_i-y_j\|^2) \langle u_i,v_j\rangle^2 b_j` def GaussLinKernel(sigma): x, y, u, v, b = Vi(0, 3), Vj(1, 3), Vi(2, 3), Vj(3, 3), Vj(4, 1) gamma = 1 / (sigma * sigma) D2 = x.sqdist(y) K = (-D2 * gamma).exp() * (u * v).sum() ** 2 return (K * b).sum_reduction(axis=1) #################################################################### # Custom ODE solver, for ODE systems which are defined on tuples def RalstonIntegrator(): def f(ODESystem, x0, nt, deltat=1.0): x = tuple(map(lambda x: x.clone(), x0)) dt = deltat / nt l = [x] for i in range(nt): xdot = ODESystem(*x) xi = tuple(map(lambda x, xdot: x + (2 * dt / 3) * xdot, x, xdot)) xdoti = ODESystem(*xi) x = tuple( map( lambda x, xdot, xdoti: x + (0.25 * dt) * (xdot + 3 * xdoti), x, xdot, xdoti, ) ) l.append(x) return l return f #################################################################### # LDDMM implementation # -------------------- ##################################################################### # Deformations: diffeomorphism # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ##################################################################### # Hamiltonian system def Hamiltonian(K): def H(p, q): return 0.5 * (p * K(q, q, p)).sum() return H def HamiltonianSystem(K): H = Hamiltonian(K) def HS(p, q): Gp, Gq = grad(H(p, q), (p, q), create_graph=True) return -Gq, Gp return HS ##################################################################### # Shooting approach def Shooting(p0, q0, K, nt=10, Integrator=RalstonIntegrator()): return Integrator(HamiltonianSystem(K), (p0, q0), nt) def Flow(x0, p0, q0, K, deltat=1.0, Integrator=RalstonIntegrator()): HS = HamiltonianSystem(K) def FlowEq(x, p, q): return (K(x, q, p),) + HS(p, q) return Integrator(FlowEq, (x0, p0, q0), deltat)[0] def LDDMMloss(K, dataloss, gamma=0): def loss(p0, q0): p, q = Shooting(p0, q0, K)[-1] return gamma * Hamiltonian(K)(p0, q0) + dataloss(q) return loss #################################################################### # Data attachment term # ^^^^^^^^^^^^^^^^^^^^ ##################################################################### # Varifold data attachment loss for surfaces # VT: vertices coordinates of target surface, # FS,FT : Face connectivity of source and target surfaces # K kernel def lossVarifoldSurf(FS, VT, FT, K): def get_center_length_normal(F, V): V0, V1, V2 = ( V.index_select(0, F[:, 0]), V.index_select(0, F[:, 1]), V.index_select(0, F[:, 2]), ) centers, normals = (V0 + V1 + V2) / 3, 0.5 * torch.cross(V1 - V0, V2 - V0) length = (normals**2).sum(dim=1)[:, None].sqrt() return centers, length, normals / length CT, LT, NTn = get_center_length_normal(FT, VT) cst = (LT * K(CT, CT, NTn, NTn, LT)).sum() def loss(VS): CS, LS, NSn = get_center_length_normal(FS, VS) return ( cst + (LS * K(CS, CS, NSn, NSn, LS)).sum() - 2 * (LS * K(CS, CT, NSn, NTn, LT)).sum() ) return loss #################################################################### # Registration # ------------ #################################################################### # Load the dataset and plot it VS, FS, VT, FT = torch.load(datafile) q0 = VS.clone().detach().to(dtype=torchdtype, device=torchdeviceId).requires_grad_(True) VT = VT.clone().detach().to(dtype=torchdtype, device=torchdeviceId) FS = FS.clone().detach().to(dtype=torch.long, device=torchdeviceId) FT = FT.clone().detach().to(dtype=torch.long, device=torchdeviceId) sigma = torch.tensor([20], dtype=torchdtype, device=torchdeviceId) x, y, z = ( q0[:, 0].detach().cpu().numpy(), q0[:, 1].detach().cpu().numpy(), q0[:, 2].detach().cpu().numpy(), ) i, j, k = ( FS[:, 0].detach().cpu().numpy(), FS[:, 1].detach().cpu().numpy(), FS[:, 2].detach().cpu().numpy(), ) xt, yt, zt = ( VT[:, 0].detach().cpu().numpy(), VT[:, 1].detach().cpu().numpy(), VT[:, 2].detach().cpu().numpy(), ) it, jt, kt = ( FT[:, 0].detach().cpu().numpy(), FT[:, 1].detach().cpu().numpy(), FT[:, 2].detach().cpu().numpy(), ) save_folder = "../../../doc/_build/html/_images/" os.makedirs(save_folder, exist_ok=True) fig = go.Figure( data=[ go.Mesh3d(x=xt, y=yt, z=zt, i=it, j=jt, k=kt, color="blue", opacity=0.50), go.Mesh3d(x=x, y=y, z=z, i=i, j=j, k=k, color="red", opacity=0.50), ] ) fig.write_html(save_folder + "data.html", auto_open=False) # sphinx_gallery_thumbnail_path = '_static/plot_LDDMM_Surface_thumb.png' ############################################################################ # .. raw:: html # # <iframe src="../../_images/data.html" height="700px" width="100%"></iframe> # ##################################################################### # Define data attachment and LDDMM functional dataloss = lossVarifoldSurf(FS, VT, FT, GaussLinKernel(sigma=sigma)) Kv = GaussKernel(sigma=sigma) loss = LDDMMloss(Kv, dataloss) ###################################################################### # Perform optimization # initialize momentum vectors p0 = torch.zeros(q0.shape, dtype=torchdtype, device=torchdeviceId, requires_grad=True) optimizer = torch.optim.LBFGS([p0], max_eval=10, max_iter=10) print("performing optimization...") start = time.time() def closure(): optimizer.zero_grad() L = loss(p0, q0) print("loss", L.detach().cpu().numpy()) L.backward() return L for i in range(10): print("it ", i, ": ", end="") optimizer.step(closure) print("Optimization (L-BFGS) time: ", round(time.time() - start, 2), " seconds") #################################################################### # Display output # -------------- # The animated version of the deformation: nt = 15 listpq = Shooting(p0, q0, Kv, nt=nt) ############################################################################ # .. raw:: html # # <iframe src="../../_images/results.html" height="700px" width="100%"></iframe> # #################################################################### # The code to generate the figure: VTnp, FTnp = VT.detach().cpu().numpy(), FT.detach().cpu().numpy() q0np, FSnp = q0.detach().cpu().numpy(), FS.detach().cpu().numpy() # Create figure fig = go.Figure() fig.add_trace( go.Mesh3d( visible=True, x=VTnp[:, 0], y=VTnp[:, 1], z=VTnp[:, 2], i=FTnp[:, 0], j=FTnp[:, 1], k=FTnp[:, 2], ) ) # Add traces, one for each slider step for t in range(nt): qnp = listpq[t][1].detach().cpu().numpy() fig.add_trace( go.Mesh3d( visible=False, x=qnp[:, 0], y=qnp[:, 1], z=qnp[:, 2], i=FSnp[:, 0], j=FSnp[:, 1], k=FSnp[:, 2], ) ) # Make 10th trace visible fig.data[1].visible = True # Create and add slider steps = [] for i in range(len(fig.data) - 1): step = dict( method="restyle", args=["visible", [False] * len(fig.data)], ) step["args"][1][0] = True step["args"][1][i + 1] = True # Toggle i'th trace to "visible" steps.append(step) sliders = [ dict(active=0, currentvalue={"prefix": "time: "}, pad={"t": 20}, steps=steps) ] fig.update_layout(sliders=sliders) fig.write_html(save_folder + "results.html", auto_open=False)
keops-main
pykeops/pykeops/tutorials/surface_registration/plot_LDDMM_Surface.py
""" ========================================================= Advanced usage: Vi, Vj, Pm helpers and symbolic variables ========================================================= This tutorial shows some advanced features of the LazyTensor class. """ import time import torch from pykeops.torch import LazyTensor use_cuda = torch.cuda.is_available() tensor = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor ########################################################################### # The Vi, Vj, Pm decorators # ------------------------- # This part presents an alternative style for using the KeOps LazyTensor wrapper, that # some users may find more convenient. The idea is to always input 2D tensors, # and use the :func:`Vi <pykeops.torch.Vi>`, :func:`Vj <pykeops.torch.Vj>` helpers described below to specify wether the tensor is to be # understood as indexed by i (i.e. with an equivalent shape of the form (M,1,D)) # or by j (shape of the form (1,N,D)). Note that it is currently not possible to use # additional batch dimensions with this specific syntax. # # Here is how it works, if we # want to perform a simple gaussian convolution. # # We first create the dataset using 2D tensors: M, N = (100000, 200000) if use_cuda else (1000, 2000) D = 3 x = torch.randn(M, D).type(tensor) y = torch.randn(N, D).type(tensor) ############################################################################ # Then we use :func:`Vi <pykeops.torch.Vi>` and :func:`Vj <pykeops.torch.Vj>` to convert to KeOps LazyTensor objects from pykeops.torch import Vi, Vj x_i = Vi(x) # (M, 1, D) LazyTensor, equivalent to LazyTensor( x[:,None,:] ) y_j = Vj(y) # (1, N, D) LazyTensor, equivalent to LazyTensor( y[None,:,:] ) ############################################################################ # and perform our operations: D2xy = ((x_i - y_j) ** 2).sum() gamma = D2xy.sum_reduction(dim=1) ######################################################################### # Note that in the first line we used ``sum`` without any axis or dim parameter. # This is equivalent to ``sum(-1)`` or ``sum(dim=2)``, because # the axis parameter is set to ``2`` by default. But speaking about ``dim=2`` # here with the :func:`Vi <pykeops.torch.Vi>`, :func:`Vj <pykeops.torch.Vj>` helpers could be misleading. # Similarly we used ``sum_reduction`` instead of ``sum`` to make it clear # that we perform a reduction, but sum and sum_reduction with ``dim=0`` or ``1`` # are equivalent (however ``sum_reduction`` with ``dim=2`` is forbidden) ############################################################################ # We have not spoken about :func:`Pm <pykeops.torch.Pm>` yet. In fact :func:`Pm <pykeops.torch.Pm>` is used to introduce # scalars or 1D vectors of parameters into formulas, but it is useless # in such examples because scalars, lists of scalars, 0D or 1D NumPy vectors # are automatically converted into parameters when combined with # KeOps formulas. We will have to use :func:`Pm <pykeops.torch.Pm>` in other parts below. ######################################################################## # Other examples # -------------- # All KeOps operations and reductions # are available, either via operators or methods. Here are one line # examples # # Getting indices of closest point between x and y: indmin = ((x_i - y_j) ** 2).sum().argmin(axis=0) ############################################################################### # Scalar product, absolute value, power operator, and a SoftMax type reduction: res = (abs(x_i | y_j) ** 1.5).sumsoftmaxweight(x_i, axis=1) ######################################################################## # The ``[]`` operator can be used to do element selection or slicing # (Elem or Extract operation in KeOps). res = (x_i[:2] * y_j[2:] - x_i[2:] * y_j[:2]).sqnorm2().sum(axis=1) ######################################################################## # Kernel inversion : let's do a gaussian kernel inversion. Note that # we have to use both :func:`Vi <pykeops.torch.Vi>` and :func:`Vj <pykeops.torch.Vj>` helpers on the same tensor ``x`` here. # e_i = Vi(torch.rand(M, D).type(tensor)) x_j = Vj(x) D2xx = LazyTensor.sum((x_i - x_j) ** 2) sigma = 0.25 Kxx = (-D2xx / sigma**2).exp() res = LazyTensor.solve(Kxx, e_i, alpha=0.1) ######################################################################### # Use of loops or vector operations for sums of kernels # ----------------------------------------------------- ############################################################################# # Let us now perform again a kernel convolution, but replacing the gaussian # kernel by a sum of 4 gaussian kernels with different sigma widths. # This can be done as follows with a for loop: sigmas = tensor([0.5, 1.0, 2.0, 4.0]) b_j = Vj(torch.rand(N, D).type(tensor)) Kxy = 0 for sigma in sigmas: Kxy += LazyTensor.exp(-D2xy / sigma**2) gamma = (Kxy * b_j).sum_reduction(axis=1) ############################################################################### # Note again that after the for loop, no actual computation has been performed. # So we can actually build formulas with much more flexibility than with the # use of Genred. # # Ok, this was just to showcase the use of a for loop, # however in this case there is no need for a for loop, we can do simply: Kxy = LazyTensor.exp(-D2xy / sigmas**2).sum() gamma = (Kxy * b_j).sum_reduction(axis=1) ############################################################################### # This is because all operations are broadcasted, so the ``/`` operation above # works and corresponds to a ``./`` (scalar-vector element-wise division) ################################################################################### # The "no call" mode # ----------------------------------------------------- # When using a reduction operation, the user has the choice to actually not perform # the computation directly and instead output a KeOps object which is # direclty callable. This can be done using the "call=False" option M, N = (100000, 200000) if use_cuda else (1000, 2000) D, Dv = 3, 4 x = torch.randn(M, D).type(tensor) y = torch.randn(N, D).type(tensor) b = torch.randn(N, Dv).type(tensor) sigmas = tensor([0.5, 1.0, 2.0, 4.0]) from pykeops.torch import Vi, Vj, Pm x_i = Vi(x) # (M, 1, D) LazyTensor, equivalent to LazyTensor( x[:,None,:] ) y_j = Vj(y) # (1, N, D) LazyTensor, equivalent to LazyTensor( y[None,:,:] ) b_j = Vj(b) # (1, N, D) LazyTensor, equivalent to LazyTensor( b[None,:,:] ) D2xy = ((x_i - y_j) ** 2).sum(-1) Kxy = LazyTensor.exp(-D2xy / sigmas**2).sum() gammafun = (Kxy * b_j).sum_reduction(axis=1, call=False) ########################################################################### # Here gammafun is a function and can be evaluated later gamma = gammafun() ########################################################################### # This is usefull in order to avoid the small overhead # caused by using the container syntax inside loops if one wants to perform # a large number of times the same reduction. # Here is an example where we compare the two approaches on small size data # to see the effect of the overhead M, N = 50, 30 x = torch.rand(M, D).type(tensor) y = torch.rand(N, D).type(tensor) beta = torch.rand(N, Dv).type(tensor) xi, yj, bj = Vi(x), Vj(y), Vj(beta) dxy2 = LazyTensor.sum((xi - yj) ** 2) Niter = 1000 start = time.time() for k in range(Niter): Kxyb = LazyTensor.exp(-dxy2 / sigmas**2).sum() * bj gamma = Kxyb.sum_reduction(axis=1) end = time.time() print( "Timing for {} iterations: {:.5f}s = {} x {:.5f}s".format( Niter, end - start, Niter, (end - start) / Niter ) ) start = time.time() Kxyb = LazyTensor.exp(-dxy2 / sigmas**2).sum() * bj gammafun = Kxyb.sum_reduction(axis=1, call=False) for k in range(Niter): gamma = gammafun() end = time.time() print( "Timing for {} iterations: {:.5f}s = {} x {:.5f}s".format( Niter, end - start, Niter, (end - start) / Niter ) ) ########################################################################### # Of course this means the user has to perform in-place operations # over tensors ``x``, ``y,`` ``beta`` inside the loop, otherwise the result of the # call to ``gammafun`` will always be the same. This is not very convenient, # so we provide also a "symbolic variables" syntax. ########################################################################### # Using "symbolic" variables in formulas # ----------------------------------------------------- # # Instead of inputing tensors to the :func:`Vi <pykeops.torch.Vi>`, :func:`Vj <pykeops.torch.Vj>`, :func:`Pm <pykeops.torch.Pm>` helpers, one may specify # the variables as symbolic, providing an index and a dimension: xi = Vi(0, D) yj = Vj(1, D) bj = Vj(2, Dv) Sigmas = Pm(3, 4) ########################################################################### # Now we build the formula as before dxy2 = LazyTensor.sum((xi - yj) ** 2) Kxyb = LazyTensor.exp(-dxy2 / Sigmas**2).sum() * bj gammafun = Kxyb.sum_reduction(axis=1) ############################################################################### # Note that we did not have to specify ``call=False`` because since the # variables are symbolic, no computation can be done of course. So the # ouput is automatically a function. We can evaluate it by providing the # arguments in the order specified by the index argument given to :func:`Vi <pykeops.torch.Vi>`, :func:`Vj <pykeops.torch.Vj>`, :func:`Pm <pykeops.torch.Pm>`: gamma = gammafun(x, y, beta, sigmas) ########################################################################### # Symbolic and non symbolic variables can be mixed. For example if we want # to fix ``x``, ``beta`` and ``sigmas`` in the previous example and make the reduction # a function of ``y`` only we can write: xi = Vi(x) yj = Vj(0, D) bj = Vj(beta) dxy2 = LazyTensor.sum((xi - yj) ** 2) Kxyb = LazyTensor.exp(-dxy2 / sigmas**2).sum() * bj gammafun = Kxyb.sum_reduction(axis=1) print(gammafun) gamma = gammafun(y)
keops-main
pykeops/pykeops/tutorials/a_LazyTensors/plot_lazytensors_c.py
""" ========================================== Fancy reductions, solving linear systems ========================================== """ ############################################################# # As discussed in the previous notebook, # KeOps :class:`LazyTensors <pykeops.torch.LazyTensor>` # support a wide range of **mathematical formulas**. # Let us now discuss the different operators that can be used # to **reduce** our large M-by-N symbolic tensors into # vanilla NumPy arrays or PyTorch tensors. # # .. note:: # In this tutorial, we stick to the **PyTorch** interface; # but note that apart from a few lines on backpropagation, # everything here can be seamlessly translated to vanilla **NumPy+KeOps** code. # # LogSumExp, KMin and advanced reductions # --------------------------------------------------- # # First, let's build some large :class:`LazyTensors <pykeops.torch.LazyTensor>` # ``S_ij`` and ``V_ij`` which respectively handle **scalar** and **vector** # formulas: import torch from pykeops.torch import LazyTensor use_cuda = torch.cuda.is_available() tensor = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor M, N = (100000, 200000) if use_cuda else (1000, 2000) D = 3 x = torch.randn(M, D).type(tensor) y = torch.randn(N, D).type(tensor) x_i = LazyTensor(x[:, None, :]) # (M, 1, D) LazyTensor y_j = LazyTensor(y[None, :, :]) # (1, N, D) LazyTensor V_ij = x_i - y_j # (M, N, D) symbolic tensor of differences S_ij = (V_ij**2).sum(-1) # (M, N, 1) = (M, N) symbolic matrix of squared distances print(S_ij) print(V_ij) ############################################################################ # As we've seen earlier, the :meth:`pykeops.torch.LazyTensor.sum()` reduction can be used # on both ``S_ij`` and ``V_ij`` to produce genuine PyTorch 2D tensors: print("Sum reduction of S_ij wrt. the 'N' dimension:", S_ij.sum(dim=1).shape) ############################################### # Note that :class:`LazyTensors<pykeops.torch.LazyTensor>` # support reductions over both indexing dimensions ``M`` and ``N``, # which can be specified using the PyTorch ``dim`` # or the NumPy ``axis`` optional arguments: print("Sum reduction of V_ij wrt. the 'M' dimension:", V_ij.sum(axis=0).shape) ################################################################## # Just like PyTorch tensors, # :mod:`pykeops.torch.LazyTensor` # support a **stabilized** `log-sum-exp reduction <https://en.wikipedia.org/wiki/LogSumExp>`_, # computed efficiently with a **running maximum** in the CUDA loop. For example, the # following line computes :math:`\log(\sum_ie^{S_{ij}})` print( "LogSumExp reduction of S_ij wrt. the 'M' dimension:", S_ij.logsumexp(dim=0).shape ) ################################################################## # This reduction supports a weight parameter that can be scalar or vector-valued. # For example, the following line computes :math:`\log(\sum_je^{S_{ij}}V_{ij})` print( "LogSumExp reduction of S_ij, with 'weight' V_ij, wrt. the 'N' dimension:", S_ij.logsumexp(dim=1, weight=V_ij).shape, ) ############################################################### # Going further, the :meth:`pykeops.torch.LazyTensor.min`, :meth:`pykeops.torch.LazyTensor.max()`, :meth:`pykeops.torch.LazyTensor.argmin` or :meth:`pykeops.torch.LazyTensor.argmax` # reductions work as expected, following the sensible NumPy convention: print("Min reduction of S_ij wrt. the 'M' dimension:", S_ij.min(dim=0).shape) print("ArgMin reduction of S_ij wrt. the 'N' dimension:", S_ij.argmin(dim=1).shape) print("Max reduction of V_ij wrt. the 'M' dimension:", V_ij.max(dim=0).shape) print("ArgMax reduction of V_ij wrt. the 'N' dimension:", V_ij.argmax(dim=1).shape) ################################################################## # To compute both quantities in a single pass, feel free to use # the :meth:`pykeops.torch.LazyTensor.min_argmin` and :meth:`pykeops.torch.LazyTensor.max_argmax` reductions: m_i, s_i = S_ij.min_argmin(dim=0) print("Min-ArgMin reduction on S_ij wrt. the 'M' dimension:", m_i.shape, s_i.shape) m_i, s_i = V_ij.max_argmax(dim=1) print("Max-ArgMax reduction on V_ij wrt. the 'N' dimension:", m_i.shape, s_i.shape) ################################################################## # More interestingly, KeOps also provides support for # the :meth:`pykeops.torch.LazyTensor.Kmin`, :meth:`pykeops.torch.LazyTensor.argKmin` and :meth:`pykeops.torch.LazyTensor.Kmin_argKmin` # reductions that can be used to implement an efficient # :doc:`K-nearest neighbor algorithm <../knn/plot_knn_torch>` : # K = 5 print("KMin reduction of S_ij wrt. the 'M' dimension:", S_ij.Kmin(K=K, dim=0).shape) print( "ArgKMin reduction of S_ij wrt. the 'N' dimension:", S_ij.argKmin(K=K, dim=1).shape ) ################################################################## # It even works on vector formulas! K = 7 print("KMin reduction of V_ij wrt. the 'M' dimension:", V_ij.Kmin(K=K, dim=0).shape) print( "ArgKMin reduction of V_ij wrt. the 'N' dimension:", V_ij.argKmin(K=K, dim=1).shape ) ################################################################# # Finally, the :meth:`pykeops.torch.LazyTensor.sumsoftmaxweight` reduction # can be used to computed weighted SoftMax combinations # # .. math:: # a_i = \frac{\sum_j \exp(s_{i,j})\,v_{i,j} }{\sum_j \exp(s_{i,j})}, # # with scalar coefficients :math:`s_{i,j}` and arbitrary vector weights :math:`v_{i,j}`: a_i = S_ij.sumsoftmaxweight(V_ij, dim=1) print( "SumSoftMaxWeight reduction of S_ij, with weights V_ij, wrt. the 'N' dimension:", a_i.shape, ) ################################################################# # Solving linear systems # ------------------------------------- # # Inverting large M-by-M linear systems is a fundamental problem in applied mathematics. # To help you solve problems of the form # # .. math:: # & & a^{\star} & =\operatorname*{argmin}_a \| (\alpha\operatorname{Id}+K_{xx})a -b\|^2_2, \\\\ # &\text{i.e.}\quad & a^{\star} & = (\alpha \operatorname{Id} + K_{xx})^{-1} b, # # KeOps :mod:`pykeops.torch.LazyTensor` support # a simple :meth:`LazyTensor.solve(b, alpha=1e-10)<pykeops.torch.LazyTensor.solve>` operation that we use as follows: x = torch.randn(M, D, requires_grad=True).type(tensor) # Random point cloud x_i = LazyTensor(x[:, None, :]) # (M, 1, D) LazyTensor x_j = LazyTensor(x[None, :, :]) # (1, M, D) LazyTensor K_xx = (-((x_i - x_j) ** 2).sum(-1)).exp() # Symbolic (M, M) Gaussian kernel matrix alpha = 0.1 # "Ridge" regularization parameter b_i = torch.randn(M, 4).type(tensor) # Target signal, supported by the x_i's a_i = K_xx.solve(b_i, alpha=alpha) # Source signal, supported by the x_i's print("a_i is now a {} of shape {}.".format(type(a_i), a_i.shape)) ################################################################## # As expected, we can now check that: # # .. math:: # (\alpha \operatorname{Id} + K_{xx}) \,a \simeq b. # c_i = alpha * a_i + K_xx @ a_i # Reconstructed target signal print("Mean squared reconstruction error: {:.2e}".format(((c_i - b_i) ** 2).mean())) ################################################################# # Please note that just like (nearly) all the other :class:`LazyTensor <pykeops.torch.LazyTensor>` methods, # :meth:`pykeops.torch.LazyTensor.solve` fully supports the :mod:`torch.autograd` module: [g_i] = torch.autograd.grad((a_i**2).sum(), [x]) print("g_i is now a {} of shape {}.".format(type(g_i), g_i.shape)) ################################################################# # .. warning:: # As of today, the :meth:`pykeops.torch.LazyTensor.solve` operator only implements # a `conjugate gradient descent <https://en.wikipedia.org/wiki/Conjugate_gradient_method>`_ # under the assumption that **K_xx is a symmetric, positive-definite matrix**. # To solve generic systems, you could either # :doc:`interface KeOps with the routines of the SciPy package <../backends/plot_scipy>` # or implement your own solver, mimicking our # `reference implementation. <https://github.com/getkeops/keops/blob/main/pykeops/common/operations.py>`_
keops-main
pykeops/pykeops/tutorials/a_LazyTensors/plot_lazytensors_b.py
r""" ================================================ A wrapper for NumPy and PyTorch arrays ================================================ KeOps brings **semi-symbolic** calculus to modern computing libraries: it alleviates the need for **huge intermediate variables** such as *kernel* or *distance* matrices in machine learning and computational geometry. """ ######################################################################### # First steps # ----------- # # A simple interface to the KeOps inner routines is provided by # the :class:`pykeops.numpy.LazyTensor` or :class:`pykeops.torch.LazyTensor` # **symbolic wrapper**, to be used with **NumPy arrays** or **PyTorch # tensors** respectively. # # To illustrate its main features on a **simple example**, let's generate two point # clouds :math:`(x_i)_{i\in[1,M]}` and :math:`(y_j)_{j\in[1,N]}` in the unit square: import numpy as np M, N = 1000, 2000 x = np.random.rand(M, 2) y = np.random.rand(N, 2) ########################################################################## # With NumPy, an efficient way of computing the index of the **nearest y-neighbor** # # .. math:: # \sigma(i) = \arg \min_{j\in [1,N]} \| x_i - y_j\|^2 # # for all points :math:`x_i` is to perform a :func:`numpy.argmin()` # reduction on the **M-by-N matrix** of squared distances # # .. math:: # D_{i,j} = \|x_i-y_j\|^2, # # computed using **tensorized**, broadcasted operators: # x_i = x[:, None, :] # (M, 1, 2) numpy array y_j = y[None, :, :] # (1, N, 2) numpy array D_ij = ((x_i - y_j) ** 2).sum(-1) # (M, N) array of squared distances |x_i-y_j|^2 s_i = np.argmin(D_ij, axis=1) # (M,) array of integer indices print(s_i[:10]) ########################################################################### # That's good! Going further, we can speed-up these computations # using the **CUDA routines** of the PyTorch library: import torch use_cuda = torch.cuda.is_available() tensor = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor x_i = tensor(x[:, None, :]) # (M, 1, 2) torch tensor y_j = tensor(y[None, :, :]) # (1, N, 2) torch tensor D_ij = ((x_i - y_j) ** 2).sum(-1) # (M, N) tensor of squared distances |x_i-y_j|^2 s_i = D_ij.argmin(dim=1) # (M,) tensor of integer indices print(s_i[:10]) ########################################################################### # But **can we scale to larger point clouds?** # Unfortunately, tensorized codes will throw an exception # as soon as the **M-by-N matrix** :math:`(D_{i,j})` stops fitting # contiguously on the device memory. This generally happens # when :math:`\sqrt{MN}` goes past a hardware-dependent threshold # in the [5,000; 50,000] range: M, N = (100000, 200000) if use_cuda else (1000, 2000) x = np.random.rand(M, 2) y = np.random.rand(N, 2) x_i = tensor(x[:, None, :]) # (M, 1, 2) torch tensor y_j = tensor(y[None, :, :]) # (1, N, 2) torch tensor try: D_ij = ((x_i - y_j) ** 2).sum(-1) # (M, N) tensor of squared distances |x_i-y_j|^2 except RuntimeError as err: print(err) ########################################################################### # **That's unfortunate...** And unexpected! # After all, modern GPUs routinely handle # `the real-time rendering of scenes with millions of triangles moving around <https://www.youtube.com/watch?v=RaLQuJtQ-gc>`_. # So how do `graphics <https://www.siggraph.org/>`_ programmers achieve such # a level of performance? # # The key to efficient numerical schemes is to remark that # even though the distance matrix :math:`(D_{i,j})` is not **sparse** in the # traditional sense, it definitely is **compact from a computational perspective**. # Since its coefficients are fully described by two lists of points # and a **symbolic formula**, sensible implementations should # compute required values on-the-fly... # and bypass, **lazily**, the cumbersome pre-computation and storage # of all pairwise distances :math:`\|x_i-y_j\|^2`. # # from pykeops.numpy import LazyTensor as LazyTensor_np x_i = LazyTensor_np( x[:, None, :] ) # (M, 1, 2) KeOps LazyTensor, wrapped around the numpy array x y_j = LazyTensor_np( y[None, :, :] ) # (1, N, 2) KeOps LazyTensor, wrapped around the numpy array y D_ij = ((x_i - y_j) ** 2).sum(-1) # **Symbolic** (M, N) matrix of squared distances print(D_ij) ########################################################## # With KeOps, implementing **lazy** numerical schemes really # is **that simple**! # Our :class:`LazyTensor<pykeops.torch.LazyTensor>` variables # are encoded as a list of data arrays plus an arbitrary # symbolic formula, written with a :doc:`custom mathematical syntax <../../api/math-operations>` # that is modified after each "pythonic" operation such as ``-``, ``**2`` or ``.exp()``. # # We can then perform a :meth:`pykeops.torch.LazyTensor.argmin` reduction with # an efficient Map-Reduce scheme, implemented # as a `templated CUDA kernel <https://github.com/getkeops/keops/blob/main/keops/core/GpuConv1D.cu>`_ around # our custom formula. # As evidenced by our :doc:`benchmarks <../../_auto_benchmarks/index>`, # the KeOps routines have a **linear memory footprint** # and generally **outperform tensorized GPU implementations by two orders of magnitude**. s_i = D_ij.argmin(dim=1).ravel() # genuine (M,) array of integer indices print("s_i is now a {} of shape {}.".format(type(s_i), s_i.shape)) print(s_i[:10]) ########################################################## # Going further, we can combine :class:`LazyTensors <pykeops.torch.LazyTensor>` # using a **wide range of mathematical operations**. # For instance, with data arrays stored directly on the GPU, # an exponential kernel dot product # # .. math:: # a_i = \sum_{j=1}^N \exp(-\|x_i-y_j\|)\cdot b_j # # in dimension D=10 can be performed with: from pykeops.torch import LazyTensor D = 10 x = torch.randn(M, D).type(tensor) # M target points in dimension D, stored on the GPU y = torch.randn(N, D).type(tensor) # N source points in dimension D, stored on the GPU b = torch.randn(N, 4).type( tensor ) # N values of the 4D source signal, stored on the GPU x.requires_grad = True # In the next section, we'll compute gradients wrt. x! x_i = LazyTensor(x[:, None, :]) # (M, 1, D) LazyTensor y_j = LazyTensor(y[None, :, :]) # (1, N, D) LazyTensor D_ij = ((x_i - y_j) ** 2).sum(-1).sqrt() # Symbolic (M, N) matrix of distances K_ij = (-D_ij).exp() # Symbolic (M, N) Laplacian (aka. exponential) kernel matrix a_i = K_ij @ b # The matrix-vector product "@" can be used on "raw" PyTorch tensors! print("a_i is now a {} of shape {}.".format(type(a_i), a_i.shape)) ############################################################################# # # .. note:: # KeOps LazyTensors have two symbolic or # "virtual" axes at positions -3 and -2. # Operations on the last "vector" dimension (-1) # or on optional "batch" dimensions (-4 and beyond) # are evaluated **lazily**. # On the other hand, a reduction on one of the two symbolic axes # (-2 or -3) triggers an **explicit computation**: # we return a standard dense array with no symbolic axes. # # # # Automatic differentiation # ----------------------------------------------- # # KeOps # **fully support** the :mod:`torch.autograd` engine: # we can backprop through KeOps reductions as easily as through # vanilla PyTorch operations. # For instance, coming back to the kernel dot product above, # we can compute the gradient # # .. math:: # g_i ~=~ \frac{\partial \sum_i \|a_i\|^2}{\partial x_i} # # with: [g_i] = torch.autograd.grad((a_i**2).sum(), [x], create_graph=True) print("g_i is now a {} of shape {}.".format(type(g_i), g_i.shape)) ############################################################################# # As usual with PyTorch, having set the ``create_graph=True`` option # allows us to compute higher-order derivatives as needed: [h_i] = torch.autograd.grad(g_i.exp().sum(), [x], create_graph=True) print("h_i is now a {} of shape {}.".format(type(h_i), h_i.shape)) ############################################################################ # .. warning:: # As of today, backpropagation is **not supported** through # the :meth:`pykeops.torch.LazyTensor.min`, :meth:`pykeops.torch.LazyTensor.max` or :meth:`pykeops.torch.LazyTensor.Kmin` reductions: # we're working on it, but are not there just yet. # Until then, a simple workaround is to use # the indices computed by the # :meth:`pykeops.torch.LazyTensor.argmin`, :meth:`pykeops.torch.LazyTensor.argmax` or :meth:`pykeops.torch.LazyTensor.argKmin` # reductions to define a fully differentiable PyTorch tensor as we now explain. # # Coming back to our example about nearest neighbors in the unit cube: x = torch.randn(M, 3).type(tensor) y = torch.randn(N, 3).type(tensor) x.requires_grad = True x_i = LazyTensor(x[:, None, :]) # (M, 1, 3) LazyTensor y_j = LazyTensor(y[None, :, :]) # (1, N, 3) LazyTensor D_ij = ((x_i - y_j) ** 2).sum(-1) # Symbolic (M, N) matrix of squared distances ##################################################################### # We could compute the ``(M,)`` vector of squared distances to the **nearest y-neighbor** with: to_nn = D_ij.min(dim=1).view(-1) ################################################################ # But instead, using: s_i = D_ij.argmin(dim=1).view(-1) # (M,) integer Torch tensor to_nn_alt = ((x - y[s_i, :]) ** 2).sum(-1) ########################################################## # outputs the same result, while also allowing us to **compute arbitrary gradients**: print( "Difference between the two vectors: {:.2e}".format((to_nn - to_nn_alt).abs().max()) ) [g_i] = torch.autograd.grad(to_nn_alt.sum(), [x]) print("g_i is now a {} of shape {}.".format(type(g_i), g_i.shape)) ########################################################### # The only real downside here is that we had to write **twice** the # "squared distance" formula that specifies our computation. # We hope to fix this (minor) inconvenience sooner rather than later! # ############################################################################# # Batch processing # ----------------------------------------------- # # As should be expected, :class:`LazyTensors<pykeops.torch.LazyTensor>` # also provide full support of **batch processing**, # with broadcasting over dummy (=1) batch dimensions: A, B = 7, 3 # Batch dimensions x_i = LazyTensor(torch.randn(A, B, M, 1, D)) l_i = LazyTensor(torch.randn(1, 1, M, 1, D)) y_j = LazyTensor(torch.randn(1, B, 1, N, D)) s = LazyTensor(torch.rand(A, 1, 1, 1, 1)) D_ij = ((l_i * x_i - y_j) ** 2).sum(-1) # Symbolic (A, B, M, N, 1) LazyTensor K_ij = -1.6 * D_ij / (1 + s**2) # Some arbitrary (A, B, M, N, 1) Kernel matrix a_i = K_ij.sum(dim=3) print("a_i is now a {} of shape {}.".format(type(a_i), a_i.shape)) ################################################################## # Everything works just fine, with two major caveats: # # - The structure of KeOps computations is still a little bit **rigid**: # :class:`LazyTensors<pykeops.torch.LazyTensor>` should only # be used in situations where the **large** dimensions M and N # over which the main reduction # is performed are in positions # -3 and -2 (respectively), with **vector** variables in position # -1 and an arbitrary number of batch dimensions beforehand. # We're working towards a full support of **tensor** variables, # but this will probably take some time to implement and test properly... # # - KeOps :class:`LazyTensors<pykeops.torch.LazyTensor>` never collapse # their last "dimension", even after a ``.sum(-1)`` reduction # whose **keepdim** argument is implicitely set to **True**. print("Convenient, numpy-friendly shape: ", K_ij.shape) print("Actual shape, used internally by KeOps: ", K_ij._shape) ################################################################## # This is the reason why in the example above, # **a_i** is a 4D Tensor of shape ``(7, 3, 1000, 1)`` and **not** # a 3D Tensor of shape ``(7, 3, 1000)``. # ############################################################################# # Supported formulas # ------------------------------------ # # The full range of mathematical operations supported by # :class:`LazyTensors<pykeops.torch.LazyTensor>` is described # in our API documentation. # Let's just mention that the lines below define valid computations: # x_i = LazyTensor(torch.randn(A, B, M, 1, D)) l_i = LazyTensor(torch.randn(1, 1, M, 1, D)) y_j = LazyTensor(torch.randn(1, B, 1, N, D)) s = LazyTensor(torch.rand(A, 1, 1, 1, 1)) F_ij = ( (x_i**1.5 + y_j / l_i).cos() - (x_i | y_j) + (x_i[:, :, :, :, 2] * s.relu() * y_j) ) print(F_ij) a_j = F_ij.sum(dim=2) print("a_j is now a {} of shape {}.".format(type(a_j), a_j.shape)) ############################################################################# # Enjoy! And feel free to check the next tutorial for a discussion # of the varied reduction operations that can be applied to # KeOps :class:`LazyTensors<pykeops.torch.LazyTensor>`.
keops-main
pykeops/pykeops/tutorials/a_LazyTensors/plot_lazytensors_a.py
""" ========= TensorDot ========= This is a test script to showcase the tensordot syntax. """ import numpy as np import torch from pykeops.torch import LazyTensor M, N = 2, 10 ####################################################################################################################### # Matrix multiplication as a special case of Tensordot # ---------------------------------------------------- # a = torch.randn(4 * 7, requires_grad=True, dtype=torch.float64) b = torch.randn(7, requires_grad=True, dtype=torch.float64) c = a.reshape(4, 7) @ b ####################################################################################################################### # A single matrix multiplication # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ # # In this case no need to use KeOps: this is a sanity check. A = LazyTensor(a[None, None, :]) B = LazyTensor(b[None, None, :]) C = A.keops_tensordot(B, (4, 7), (7,), (1,), (0,)).sum_reduction(dim=1) # print(C, c) print( "Compare the two MatVecMul implementations. All good?", torch.allclose(c.flatten(), C.flatten()), ) xi = torch.randn(4, dtype=torch.float64) dC = torch.autograd.grad(C, a, xi.reshape(1, 4), retain_graph=True)[0].view(-1) dc = torch.autograd.grad(c, a, xi, retain_graph=True)[0].view(-1) # print(dC, dc) print( "Compare the two MatVecMul gradient wrt a implementations. All good?", torch.allclose(dc.flatten(), dC.flatten()), ) dC = torch.autograd.grad(C, b, xi.reshape(1, 4))[0].view(-1) dc = torch.autograd.grad(c, b, xi)[0].view(-1) # print(dC, dc) print( "Compare the two MatVecMul gradient wrt b implementations. All good?", torch.allclose(dc.flatten(), dC.flatten()), ) print("-------------------------------") ####################################################################################################################### # Matrix multiplication with a sum reduction # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ # # That is where KeOps come into play. a = torch.randn(M, 4 * 7, requires_grad=True, dtype=torch.float64) b = torch.randn(N, 7, requires_grad=True, dtype=torch.float64) c = torch.tensordot(a.reshape(M, 4, 7), b.reshape(N, 7), dims=([2], [1])).sum(2) A = LazyTensor(a[:, None, :]) B = LazyTensor(b[None, :, :]) C = A.keops_tensordot(B, (4, 7), (7,), (1,), (0,)).sum_reduction(dim=1) # print(C, c) print( "Compare the two MatVecMul with sum implementations. All good ?", torch.allclose(c.flatten(), C.flatten()), ) xi = torch.randn(M, 4, dtype=torch.float64) dCa = torch.autograd.grad(C, a, xi, retain_graph=True)[0].view(-1) dca = torch.autograd.grad(c, a, xi, retain_graph=True)[0].view(-1) # print(dC, dc) print( "Compare the two MatVecMul with sum gradient wrt a implementations. All good ?", torch.allclose(dca.flatten(), dCa.flatten()), ) dCb = torch.autograd.grad(C, b, xi)[0].view(-1) dcb = torch.autograd.grad(c, b, xi)[0].view(-1) # print(dC, dc) print( "Compare the two MatVecMul with sum gradient wrt b implementations. All good ?", torch.allclose(dcb.flatten(), dCb.flatten()), ) print("-------------------------------") ####################################################################################################################### # Matrix-Matrix multiplication as a special case of Tensordot # ----------------------------------------------------------- # a = torch.randn(4 * 7, requires_grad=True, dtype=torch.float64) b = torch.randn(7 * 2, requires_grad=True, dtype=torch.float64) c = a.reshape(4, 7) @ b.reshape(7, 2) A = LazyTensor(a[None, None, :]) B = LazyTensor(b[None, None, :]) C = A.keops_tensordot(B, (4, 7), (7, 2), (1,), (0,)).sum_reduction(dim=1) # print(C, c) print( "Compare the two MatMul implementations. All good?", torch.allclose(c.flatten(), C.flatten()), ) xi = torch.randn(4 * 2, dtype=torch.float64) dC = torch.autograd.grad(C, a, xi.reshape(1, 4 * 2), retain_graph=True)[0].view(-1) dc = torch.autograd.grad(c, a, xi.reshape(4, 2), retain_graph=True)[0].view(-1) # print(dC, dc) print( "Compare the two MatMul gradient wrt a implementations. All good?", torch.allclose(dc.flatten(), dC.flatten()), ) dCb = torch.autograd.grad(C, b, xi.reshape(1, 4 * 2))[0].view(-1) dcb = torch.autograd.grad(c, b, xi.reshape(4, 2))[0].view(-1) # print(dCb, dcb) print( "Compare the two MatMul gradient wrt b implementations. All good?", torch.allclose(dcb.flatten(), dCb.flatten()), ) print("-------------------------------") ####################################################################################################################### # Tensordot in keopscore (generic case) # --------------------------------- # # A fisrt example # ^^^^^^^^^^^^^^^ # # First, let us start with a standard torch implementation. We contract two tensor along a common axis of size 7. # Then, a reduction is performed alog the dimension of size N. x = torch.randn(M, 4, 7, 3, requires_grad=True, dtype=torch.float64) y = torch.randn(N, 7, 2, requires_grad=True, dtype=torch.float64) f_torch = torch.tensordot(x, y, dims=([2], [1])) # now is shape (M, 4, 3, N, 2) sum_f_torch2 = f_torch.sum(3) # ... yielding a result of dimension (M,4*3*2) # In KeOps, we forgot the first reduction axis (size M and N respectively). We then need to tell the compiler not only # the contration axis (1 and 0 respectively both of dimension 7) but the shapes (4,7,3) and (7,2) as well, # keeping in mind that the 2 actual first axis of x and y (reduction axis) are ignored so the result has # shape (M,4*3*2) or (N, 4*3*2) depending on the chosen reduction axis. f_keops = LazyTensor(x.reshape(M, 1, 4 * 7 * 3)).keops_tensordot( LazyTensor(y.reshape(1, N, 7 * 2)), (4, 7, 3), (7, 2), (1,), (0,) ) sum_f_keops = f_keops.sum_reduction(dim=1) # reduction is perform along second axis # print(sum_f_keops.flatten()) # ... yielding a result of dimension (M,4*3*2) print( "Compare the two tensordot implementation. All good ?", torch.allclose(sum_f_keops.flatten(), sum_f_torch2.flatten(), rtol=1e-4), ) ######################################################################################################################## # As before, let us check the gradients e = torch.randn(M, 4 * 3 * 2, dtype=torch.float64) Ee = e.reshape(M, 4, 3, 2) grad_keops = ( torch.autograd.grad(sum_f_keops, x, e, retain_graph=True)[0].squeeze().numpy() ) grad_torch = ( torch.autograd.grad(sum_f_torch2, x, Ee, retain_graph=True)[0].squeeze().numpy() ) # print(grad_keops[0,:,:,:]) # print(grad_torch[0,:,:,:]) print( "Check gradient wrt x. All good ?", np.allclose(grad_keops.flatten(), grad_torch.flatten()), ) # tmp = torch.tensordot(Ee,y, dims=([3], [2])).sum(3).detach().numpy() # print("grad_keops and tmp are the same? ", np.allclose(tmp.flatten(), grad_keops.flatten())) # print("grad_torch and tmp are the same? ", np.allclose(grad_torch , np.moveaxis(tmp, [0,1,2,3], [0,1,3,2]))) grad_keops = torch.autograd.grad(sum_f_keops, y, e)[0].numpy() grad_torch = torch.autograd.grad(sum_f_torch2, y, Ee)[0].numpy() # print(grad_keops[:1]) # print(grad_torch[:1]) print( "Check gradient wrt y. All good ?", np.allclose(grad_keops.flatten(), grad_torch.flatten()), ) print("-------------------------------") ####################################################################################################################### # A Second example # ^^^^^^^^^^^^^^^^ # # Torch version x = torch.randn(M, 4, 3, 7, requires_grad=True, dtype=torch.float64) y = torch.randn(N, 7, 2, requires_grad=True, dtype=torch.float64) f_torch = torch.tensordot(x, y, dims=([3], [1])) # now is shape (M, 4, 3, N, 2) sum_f_torch2 = f_torch.sum(3) # ... yielding a result of dimension (M,4,3,2) ####################################################################################################################### # And corresponding KeOps version f_keops = LazyTensor(x.reshape(M, 1, 4 * 3 * 7)).keops_tensordot( LazyTensor(y.reshape(1, N, 7 * 2)), (4, 3, 7), (7, 2), (2,), (0,) ) sum_f_keops = f_keops.sum_reduction(dim=1) # reduction is perform along second axis # print(sum_f_keops.shape) # ... yielding a result of dimension (M,4*3*2) print( "Compare the two tensordot implementation. All good ?", torch.allclose(sum_f_keops.flatten(), sum_f_torch2.flatten(), rtol=1e-4), ) # checking gradients e = torch.randn(M, 4 * 3 * 2, dtype=torch.float64) Ee = e.reshape(M, 4, 3, 2) grad_keops = ( torch.autograd.grad(sum_f_keops, x, e, retain_graph=True)[0].squeeze().numpy() ) grad_torch = ( torch.autograd.grad(sum_f_torch2, x, Ee, retain_graph=True)[0].squeeze().numpy() ) # print(grad_keops[0,:,:,:]) # print(grad_torch[0,:,:,:]) print( "Compare the two gradient x tensordot implementation. All good ?", np.allclose(grad_keops.flatten(), grad_torch.flatten(), rtol=1e-4), ) grad_keops = ( torch.autograd.grad(sum_f_keops, y, e, retain_graph=True)[0].squeeze().numpy() ) grad_torch = ( torch.autograd.grad(sum_f_torch2, y, Ee, retain_graph=True)[0].squeeze().numpy() ) # print(grad_keops[0,:,:,:]) # print(grad_torch[0,:,:,:]) print( "Compare the two gradient y tensordot implementation. All good ?", np.allclose(grad_keops.flatten(), grad_torch.flatten(), rtol=1e-4), ) print("------------------------------------------") ####################################################################################################################### # A Third example # ^^^^^^^^^^^^^^^^ x = torch.randn(M, 4, 3, 2, requires_grad=True, dtype=torch.float64) y = torch.randn(N, 4, 2, requires_grad=True, dtype=torch.float64) xshape, yshape = x.shape[1:], y.shape[1:] f_keops = LazyTensor(x.reshape(M, 1, int(np.array((xshape)).prod()))).keops_tensordot( LazyTensor(y.reshape(1, N, int(np.array(yshape).prod()))), xshape, yshape, (0, 2), (0, 1), ) sum_f_keops = f_keops.sum_reduction(dim=1) sum_f_torch2 = torch.tensordot(x, y, dims=([1, 3], [1, 2])).sum(2) # sum_f_torch2 = torch.tensordot(x, y, dims=([3], [1])).sum(3) print( "Compare the two tensordot implementation. All good ????", torch.allclose(sum_f_keops.flatten(), sum_f_torch2.flatten()), ) # checking gradients e = torch.randn_like(sum_f_torch2) grad_keops = torch.autograd.grad(sum_f_keops, x, e.reshape(M, -1), retain_graph=True)[ 0 ].numpy() grad_torch = torch.autograd.grad(sum_f_torch2, x, e, retain_graph=True)[0].numpy() print( "Compare the two gradient x tensordot implementation. is All good ????", np.allclose(grad_keops.flatten(), grad_torch.flatten(), rtol=1e-4), ) grad_keops = torch.autograd.grad(sum_f_keops, y, e.reshape(M, -1), retain_graph=True)[ 0 ].numpy() grad_torch = torch.autograd.grad(sum_f_torch2, y, e, retain_graph=True)[0].numpy() print( "Compare the two gradient y tensordot implementation. is All good ????", np.allclose(grad_keops.flatten(), grad_torch.flatten(), rtol=1e-4), ) print("------------------------------------------") ####################################################################################################################### # A Fourth example # ^^^^^^^^^^^^^^^^ x = torch.randn(M, 2, 3, 4, 2, 2, requires_grad=True, dtype=torch.float64) y = torch.randn(N, 2, 4, 5, 3, 2, requires_grad=True, dtype=torch.float64) xshape, yshape = x.shape[1:], y.shape[1:] f_keops = LazyTensor(x.reshape(M, 1, int(np.array((xshape)).prod()))).keops_tensordot( LazyTensor(y.reshape(1, N, int(np.array(yshape).prod()))), xshape, yshape, (0, 1, 4), (0, 3, 4), ) sum_f_keops = f_keops.sum_reduction(dim=1) sum_f_torch2 = torch.tensordot(x, y, dims=([1, 2, 5], [1, 4, 5])).sum(3) # sum_f_torch2 = torch.tensordot(x, y, dims=([3], [1])).sum(3) print( "Compare the two tensordot implementation. All good ????!", torch.allclose(sum_f_keops.flatten(), sum_f_torch2.flatten()), ) # checking gradients e = torch.randn_like(sum_f_torch2) grad_keops = torch.autograd.grad(sum_f_keops, x, e.reshape(M, -1), retain_graph=True)[ 0 ].numpy() grad_torch = torch.autograd.grad(sum_f_torch2, x, e, retain_graph=True)[0].numpy() print( "Compare the two gradient x tensordot implementation. All good ????!", np.allclose(grad_keops.flatten(), grad_torch.flatten(), rtol=1e-4), ) grad_keops = torch.autograd.grad(sum_f_keops, y, e.reshape(M, -1), retain_graph=True)[ 0 ].numpy() grad_torch = torch.autograd.grad(sum_f_torch2, y, e, retain_graph=True)[0].numpy() print( "Compare the two gradient y tensordot implementation. All good ????!", np.allclose(grad_keops.flatten(), grad_torch.flatten(), rtol=1e-4), ) print("------------------------------------------") ####################################################################################################################### # A Fifth example # ^^^^^^^^^^^^^^^^ x = torch.randn(M, 2, 3, 4, requires_grad=True, dtype=torch.float64) y = torch.randn(N, 2, 4, 5, requires_grad=True, dtype=torch.float64) xshape, yshape = x.shape[1:], y.shape[1:] f_keops = LazyTensor(x.reshape(M, 1, int(np.array((xshape)).prod()))).keops_tensordot( LazyTensor(y.reshape(1, N, int(np.array(yshape).prod()))), xshape, yshape, (2, 0), (1, 0), ) sum_f_keops = f_keops.sum_reduction(dim=1) sum_f_torch2 = torch.tensordot(x, y, dims=([3, 1], [2, 1])).sum(2) # sum_f_torch2 = torch.tensordot(x, y, dims=([3], [1])).sum(3) print( "Compare the two tensordot implementation. All good ????!", torch.allclose(sum_f_keops.flatten(), sum_f_torch2.flatten()), ) # checking gradients e = torch.randn_like(sum_f_torch2) grad_keops = torch.autograd.grad(sum_f_keops, x, e.reshape(M, -1), retain_graph=True)[ 0 ].numpy() grad_torch = torch.autograd.grad(sum_f_torch2, x, e, retain_graph=True)[0].numpy() print( "Compare the two gradient x tensordot implementation. All good ????!", np.allclose(grad_keops.flatten(), grad_torch.flatten(), rtol=1e-4), ) grad_keops = torch.autograd.grad(sum_f_keops, y, e.reshape(M, -1), retain_graph=True)[ 0 ].numpy() grad_torch = torch.autograd.grad(sum_f_torch2, y, e, retain_graph=True)[0].numpy() print( "Compare the two gradient y tensordot implementation. All good ????!", np.allclose(grad_keops.flatten(), grad_torch.flatten(), rtol=1e-4), ) print("------------------------------------------") ####################################################################################################################### # A Sixth example # ^^^^^^^^^^^^^^^^ x = torch.randn(M, 2, 3, 4, requires_grad=True, dtype=torch.float64) y = torch.randn(N, 4, 2, requires_grad=True, dtype=torch.float64) xshape, yshape = x.shape[1:], y.shape[1:] f_keops = LazyTensor(x.reshape(M, 1, int(np.array((xshape)).prod()))).keops_tensordot( LazyTensor(y.reshape(1, N, int(np.array(yshape).prod()))), xshape, yshape, (2, 0), (0, 1), ) sum_f_keops = f_keops.sum_reduction(dim=1) sum_f_torch2 = torch.tensordot(x, y, dims=([3, 1], [1, 2])).sum(2) # sum_f_torch2 = torch.tensordot(x, y, dims=([3], [1])).sum(3) print( "Compare the two tensordot implementation. All good ????", torch.allclose(sum_f_keops.flatten(), sum_f_torch2.flatten()), ) # checking gradients e = torch.randn_like(sum_f_torch2) grad_keops = torch.autograd.grad(sum_f_keops, x, e.reshape(M, -1), retain_graph=True)[ 0 ].numpy() grad_torch = torch.autograd.grad(sum_f_torch2, x, e, retain_graph=True)[0].numpy() print( "Compare the two gradient x tensordot implementation. All good ????", np.allclose(grad_keops.flatten(), grad_torch.flatten(), rtol=1e-4), ) grad_keops = torch.autograd.grad(sum_f_keops, y, e.reshape(M, -1))[0].numpy() grad_torch = torch.autograd.grad(sum_f_torch2, y, e)[0].numpy() # print(grad_keops) # print(grad_torch) print( "Compare the two gradient y tensordot implementation. All good ????", np.allclose(grad_keops.flatten(), grad_torch.flatten(), rtol=1e-4), ) print("------------------------------------------") ####################################################################################################################### # A Seventh example # ^^^^^^^^^^^^^^^^^ x = torch.randn(M, 2, 3, 2, 2, 4, requires_grad=True, dtype=torch.float64) y = torch.randn(N, 2, 4, 2, 3, 2, 3, requires_grad=True, dtype=torch.float64) xshape, yshape = x.shape[1:], y.shape[1:] f_keops = LazyTensor(x.reshape(M, 1, int(np.array((xshape)).prod()))).keops_tensordot( LazyTensor(y.reshape(1, N, int(np.array(yshape).prod()))), xshape, yshape, (4, 0, 2), (1, 4, 2), ) sum_f_keops = f_keops.sum_reduction(dim=1) sum_f_torch2 = torch.tensordot(x, y, dims=([5, 1, 3], [2, 5, 3])).sum(3) # sum_f_torch2 = torch.tensordot(x, y, dims=([3], [1])).sum(3) print( "Compare the two tensordot implementation. All good ????!", torch.allclose(sum_f_keops.flatten(), sum_f_torch2.flatten()), ) # checking gradients e = torch.randn_like(sum_f_torch2) grad_keops = torch.autograd.grad(sum_f_keops, x, e.reshape(M, -1), retain_graph=True)[ 0 ].numpy() grad_torch = torch.autograd.grad(sum_f_torch2, x, e, retain_graph=True)[0].numpy() print( "Compare the two gradient x tensordot implementation. All good ????!", np.allclose(grad_keops.flatten(), grad_torch.flatten(), rtol=1e-4), ) grad_keops = torch.autograd.grad(sum_f_keops, y, e.reshape(M, -1), retain_graph=True)[ 0 ].numpy() grad_torch = torch.autograd.grad(sum_f_torch2, y, e, retain_graph=True)[0].numpy() print( "Compare the two gradient y tensordot implementation. All good ????!", np.allclose(grad_keops.flatten(), grad_torch.flatten(), rtol=1e-4), ) print("------------------------------------------") ####################################################################################################################### # # # def my_tensordort_perm(a, b, dims=None, perm=None): # print(torch.tensordot(a, b, dims=dims).sum(3).shape) return torch.tensordot(a, b, dims=dims).sum(3).permute(perm) def invert_permutation_numpy(permutation): return np.arange(len(permutation))[np.argsort(permutation)] x = torch.randn(M, 2, 3, 4, requires_grad=True, dtype=torch.float64) y = torch.randn(N, 2, 4, requires_grad=True, dtype=torch.float64) dimfa, dimfb = x.shape[1:], y.shape[1:] contfa, contfb = [3], [2] keepfa, keepfb = ( [item - 1 for item in [1, 2, 3] if item not in contfa], [item for item in [1, 2] if item not in contfb], ) # contfa, contfb = [2, 3], [1, 2] n = len(dimfa) + len(dimfb) - 2 * len(contfa) # perm = [int(i) for i in torch.randperm(n)] perm = [2, 0, 1] # perm = [2, 1, 3, 0] # perm = [1, 0] perm_torch = (0,) + tuple([(i + 1) for i in invert_permutation_numpy(perm)]) sum_f_torch2 = my_tensordort_perm( x, y, dims=(contfa, contfb), perm=perm_torch ) # 1, 2,3,5,4 -> 1, 5,3,4,2 f_keops = LazyTensor(x.reshape(M, 1, int(np.array((dimfa)).prod()))).keops_tensordot( LazyTensor(y.reshape(1, N, int(np.array(dimfb).prod()))), dimfa, dimfb, tuple(np.array(contfa) - 1), tuple(np.array(contfb) - 1), tuple(perm), ) sum_f_keops = f_keops.sum_reduction(dim=1) print( "Compare the two tensordot implementation. All good ????!!", torch.allclose(sum_f_keops.flatten(), sum_f_torch2.flatten()), ) # checking gradients e = torch.randn_like(sum_f_torch2) grad_keops = torch.autograd.grad(sum_f_keops, x, e.reshape(M, -1), retain_graph=True)[ 0 ].numpy() # grad_torch2 = my_tensordort_perm(e, y, dims=([4,2], keepfb), perm=[0,1,2]) grad_torch = torch.autograd.grad(sum_f_torch2, x, e, retain_graph=True)[0].numpy() print( "Compare the two gradient x tensordot implementation. All good ????!", np.allclose(grad_keops.flatten(), grad_torch.flatten(), rtol=1e-4), ) # print("Compare the two gradient x tensordot implementation. All good ????!", # np.allclose(grad_torch2.detach().numpy(), grad_torch, rtol=1e-4)) grad_keops = torch.autograd.grad(sum_f_keops, y, e.reshape(M, -1), retain_graph=True)[ 0 ].numpy() grad_torch = torch.autograd.grad(sum_f_torch2, y, e, retain_graph=True)[0].numpy() # grad_torch2 = my_tensordort_perm(e, x, dims=([1,3], [1,2]), perm=[0,1,2,3]).permute(perm) # grad_torch2 = my_tensordort_perm(e, x, dims=([1,3], [1,2]), perm=perm) print( "Compare the two gradient y tensordot implementation. All good ????!", np.allclose(grad_keops.flatten(), grad_torch.flatten(), rtol=1e-4), ) # print("Compare the two gradient y tensordot implementation. All good ????!", # np.allclose(grad_torch2.detach().numpy(), grad_torch, rtol=1e-4)) print("------------------------------------------") x = torch.randn(M, 2, 3, 4, requires_grad=True, dtype=torch.float64) y = torch.randn(N, 2, 4, 5, requires_grad=True, dtype=torch.float64) dimfa, dimfb = x.shape[1:], y.shape[1:] contfa, contfb = [3], [2] keepfa, keepfb = ( [item - 1 for item in [1, 2, 3] if item not in contfa], [item for item in [1, 2, 3] if item not in contfb], ) # contfa, contfb = [2, 3], [1, 2] n = len(dimfa) + len(dimfb) - 2 * len(contfa) # perm = [int(i) for i in torch.randperm(n)] perm = [0, 2, 3, 1] # perm = [2, 1, 3, 0] # perm = [1, 0] perm_torch = (0,) + tuple([(i + 1) for i in invert_permutation_numpy(perm)]) sum_f_torch2 = my_tensordort_perm( x, y, dims=(contfa, contfb), perm=perm_torch ) # 1, 2,3,5,4 -> 1, 5,3,4,2 f_keops = LazyTensor(x.reshape(M, 1, int(np.array((dimfa)).prod()))).keops_tensordot( LazyTensor(y.reshape(1, N, int(np.array(dimfb).prod()))), dimfa, dimfb, tuple(np.array(contfa) - 1), tuple(np.array(contfb) - 1), tuple(perm), ) sum_f_keops = f_keops.sum_reduction(dim=1) print( "Compare the two tensordot implementation. All good ????!!", torch.allclose(sum_f_keops.flatten(), sum_f_torch2.flatten()), ) # checking gradients e = torch.randn_like(sum_f_torch2) grad_keops = torch.autograd.grad(sum_f_keops, x, e.reshape(M, -1), retain_graph=True)[ 0 ].numpy() # grad_torch2 = my_tensordort_perm(e, y, dims=([4,2], keepfb), perm=[0,1,2,3]) grad_torch = torch.autograd.grad(sum_f_torch2, x, e, retain_graph=True)[0].numpy() print( "Compare the two gradient x tensordot implementation. All good ????!", np.allclose(grad_keops.flatten(), grad_torch.flatten(), rtol=1e-4), ) # print("Compare the two gradient x tensordot implementation. All good ????!", # np.allclose(grad_torch2.detach().numpy(), grad_torch, rtol=1e-4)) grad_keops = torch.autograd.grad(sum_f_keops, y, e.reshape(M, -1), retain_graph=True)[0] grad_torch = torch.autograd.grad(sum_f_torch2, y, e, retain_graph=True)[0] # grad_torch2 = my_tensordort_perm(e, x, dims=([1,3], [1,2]), perm=perm) print( "Compare the two gradient y tensordot implementation. All good ????!", np.allclose(grad_keops.numpy().flatten(), grad_torch.numpy().flatten(), rtol=1e-4), ) # print("Compare the two gradient y tensordot implementation. All good ????!", # np.allclose(grad_torch2.detach().numpy(), grad_torch, rtol=1e-4)) print("------------------------------------------") x = torch.randn(M, 2, 3, 2, 2, 4, requires_grad=True, dtype=torch.float64) y = torch.randn(N, 2, 4, 2, 3, 2, 3, requires_grad=True, dtype=torch.float64) dimfa, dimfb = x.shape[1:], y.shape[1:] contfa, contfb = [5, 1, 3], [2, 5, 3] n = len(dimfa) + len(dimfb) - 2 * len(contfa) # perm_id = [int(i) for i in range(n+1)] # perm = [int(i) for i in torch.randperm(n)] # perm = [0,2,1,4,3] perm = [4, 3, 2, 0, 1] perm_torch = (0,) + tuple([(i + 1) for i in invert_permutation_numpy(perm)]) sum_f_torch2 = my_tensordort_perm(x, y, dims=(contfa, contfb), perm=perm_torch) # print(sum_f_torch2.shape) f_keops = LazyTensor(x.reshape(M, 1, int(np.array((dimfa)).prod()))).keops_tensordot( LazyTensor(y.reshape(1, N, int(np.array(dimfb).prod()))), dimfa, dimfb, tuple(np.array(contfa) - 1), tuple(np.array(contfb) - 1), tuple(perm), ) sum_f_keops = f_keops.sum_reduction(dim=1) print( "Compare the two tensordot implementation. All good ????!!", torch.allclose(sum_f_keops.flatten(), sum_f_torch2.flatten()), ) # checking gradients e = torch.randn_like(sum_f_torch2) grad_keops = torch.autograd.grad(sum_f_keops, x, e.reshape(M, -1), retain_graph=True)[ 0 ].numpy() grad_torch = torch.autograd.grad(sum_f_torch2, x, e, retain_graph=True)[0].numpy() # grad_torch2 = my_tensordort_perm(e, y, dims=([1,2,3], [1,4,6]), perm=[0,1,2,3,4,5]).permute(3) print( "Compare the two gradient x tensordot implementation. All good ????!", np.allclose(grad_keops.flatten(), grad_torch.flatten(), rtol=1e-4), ) grad_keops = torch.autograd.grad(sum_f_keops, y, e.reshape(M, -1), retain_graph=True)[ 0 ].numpy() grad_torch = torch.autograd.grad(sum_f_torch2, y, e, retain_graph=True)[0].numpy() print( "Compare the two gradient y tensordot implementation. All good ????!", np.allclose(grad_keops.flatten(), grad_torch.flatten(), rtol=1e-4), ) print("------------------------------------------") ####################################################################################################################### # Using gradcheck # --------------- # # def my_tensordot(x,y): # f_keops = LazyTensor(x.reshape(M, 1, 4 * 3 * 7)).keops_tensordot(LazyTensor(y.reshape(1, N, 7 * 2)), (4, 3, 7), # (7, 2), (2,), (0,)) # return f_keops.sum_reduction(dim=1) # print(torch.autograd.gradcheck(my_tensordot, [x,y])) def my_tensordot2(x, y): xshape, yshape = x.shape[1:], y.shape[1:] f_keops = LazyTensor( x.reshape(M, 1, int(np.array((xshape)).prod())) ).keops_tensordot( LazyTensor(y.reshape(1, N, int(np.array(yshape).prod()))), xshape, yshape, (2, 0), # (2,0,1), (0, 1), # (0,3,2) ) return f_keops.sum_reduction(dim=1) x = torch.randn(M, 2, 2, 2, requires_grad=True, dtype=torch.float64) y = torch.randn(N, 2, 2, requires_grad=True, dtype=torch.float64) print(torch.autograd.gradcheck(my_tensordot2, [x, y], atol=1e-5, rtol=1e-5)) print(torch.autograd.gradgradcheck(my_tensordot2, [x, y], atol=1e-5, rtol=1e-5))
keops-main
pykeops/pykeops/tutorials/a_LazyTensors/plot_test_tensordot.py
r""" ================================== Kernel interpolation - PyTorch API ================================== The :meth:`pykeops.torch.LazyTensor.solve(b, alpha=1e-10)<pykeops.torch.LazyTensor.solve>` method of KeOps :class:`pykeops.torch.LazyTensor` allows you to solve optimization problems of the form .. math:: a^{\star}=\operatorname*{argmin}_a \| (\alpha\operatorname{Id}+K_{xx})a -b\|^2_2, where :math:`K_{xx}` is a symmetric, positive definite linear operator defined through the :ref:`KeOps generic syntax <part.generic_formulas>` and :math:`\alpha` is a nonnegative regularization parameter. In the following script, we use it to solve large-scale `Kriging <https://en.wikipedia.org/wiki/Kriging>`_ (aka. `Gaussian process regression <https://scikit-learn.org/stable/modules/gaussian_process.html>`_ or `generalized spline interpolation <https://en.wikipedia.org/wiki/Spline_interpolation>`_) problems with a **linear memory footprint**. """ ############################################################################################### # Setup # ----- # # Standard imports: import time import torch from matplotlib import pyplot as plt from pykeops.torch import LazyTensor ############################################################################################### # Generate some data: use_cuda = torch.cuda.is_available() dtype = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor N = 10000 if use_cuda else 1000 # Number of samples # Sampling locations: x = torch.rand(N, 1).type(dtype) # Some random-ish 1D signal: b = ( x + 0.5 * (6 * x).sin() + 0.1 * (20 * x).sin() + 0.05 * torch.randn(N, 1).type(dtype) ) ###################################################################### # Interpolation in 1D # ------------------- # # Specify our **regression model** - a simple **Gaussian** variogram or **kernel matrix** # of deviation **sigma**: def gaussian_kernel(x, y, sigma=0.1): x_i = LazyTensor(x[:, None, :]) # (M, 1, 1) y_j = LazyTensor(y[None, :, :]) # (1, N, 1) D_ij = ((x_i - y_j) ** 2).sum(-1) # (M, N) symbolic matrix of squared distances return (-D_ij / (2 * sigma**2)).exp() # (M, N) symbolic Gaussian kernel matrix ####################################################################### # Perform the **Kernel interpolation**, without forgetting to specify # the ridge regularization parameter **alpha** which controls the trade-off # between a perfect fit (**alpha** = 0) and a # smooth interpolation (**alpha** = :math:`+\infty`): alpha = 1.0 # Ridge regularization start = time.time() K_xx = gaussian_kernel(x, x) a = K_xx.solve(b, alpha=alpha) end = time.time() print( "Time to perform an RBF interpolation with {:,} samples in 1D: {:.5f}s".format( N, end - start ) ) ############################################################################################### # Display the (fitted) model on the unit interval: # # Extrapolate on a uniform sample: t = torch.linspace(0, 1, 1001).type(dtype)[:, None] K_tx = gaussian_kernel(t, x) mean_t = K_tx @ a # 1D plot: plt.figure(figsize=(8, 6)) plt.scatter(x.cpu()[:, 0], b.cpu()[:, 0], s=100 / len(x)) # Noisy samples plt.plot(t.cpu().numpy(), mean_t.cpu().numpy(), "r") plt.axis([0, 1, 0, 1]) plt.tight_layout() ############################################################################################### # Interpolation in 2D # ------------------- # # Generate some data: # Sampling locations: x = torch.rand(N, 2).type(dtype) # Some random-ish 2D signal: b = ((x - 0.5) ** 2).sum(1, keepdim=True) b[b > 0.4**2] = 0 b[b < 0.3**2] = 0 b[b >= 0.3**2] = 1 b = b + 0.05 * torch.randn(N, 1).type(dtype) # Add 25% of outliers: Nout = N // 4 b[-Nout:] = torch.rand(Nout, 1).type(dtype) ######################################################################## # Specify our **regression model** - a simple **Exponential** variogram # or **Laplacian** kernel matrix of deviation **sigma**: def laplacian_kernel(x, y, sigma=0.1): x_i = LazyTensor(x[:, None, :]) # (M, 1, 1) y_j = LazyTensor(y[None, :, :]) # (1, N, 1) D_ij = ((x_i - y_j) ** 2).sum(-1) # (M, N) symbolic matrix of squared distances return (-D_ij.sqrt() / sigma).exp() # (M, N) symbolic Laplacian kernel matrix ####################################################################### # Perform the **Kernel interpolation**, without forgetting to specify # the ridge regularization parameter **alpha** which controls the trade-off # between a perfect fit (**alpha** = 0) and a # smooth interpolation (**alpha** = :math:`+\infty`): alpha = 10 # Ridge regularization start = time.time() K_xx = laplacian_kernel(x, x) a = K_xx.solve(b, alpha=alpha) end = time.time() print( "Time to perform an RBF interpolation with {:,} samples in 2D: {:.5f}s".format( N, end - start ) ) ############################################################################################### # Display the (fitted) model on the unit square: # # Extrapolate on a uniform sample: X = Y = torch.linspace(0, 1, 101).type(dtype) X, Y = torch.meshgrid(X, Y) t = torch.stack((X.contiguous().view(-1), Y.contiguous().view(-1)), dim=1) K_tx = laplacian_kernel(t, x) mean_t = K_tx @ a mean_t = mean_t.view(101, 101) # 2D plot: noisy samples and interpolation in the background plt.figure(figsize=(8, 8)) plt.scatter( x.cpu()[:, 0], x.cpu()[:, 1], c=b.cpu().view(-1), s=25000 / len(x), cmap="bwr" ) plt.imshow( mean_t.cpu().numpy()[::-1, :], interpolation="bilinear", extent=[0, 1, 0, 1], cmap="coolwarm", ) # sphinx_gallery_thumbnail_number = 2 plt.axis([0, 1, 0, 1]) plt.tight_layout() plt.show()
keops-main
pykeops/pykeops/tutorials/interpolation/plot_RBF_interpolation_torch.py
r""" ================================== Kernel interpolation - NumPy API ================================== The :meth:`pykeops.numpy.LazyTensor.solve(b, alpha=1e-10)<pykeops.numpy.LazyTensor.solve>` method of KeOps :class:`pykeops.numpy.LazyTensor` allows you to solve optimization problems of the form .. math:: & & a^{\star} & =\operatorname*{argmin}_a \tfrac 1 2 \langle a,( \alpha \operatorname{Id}+K_{xx}) a\rangle - \langle a,b \rangle, \\\\ &\text{i.e.}\quad & a^{\star} & = (\alpha \operatorname{Id} + K_{xx})^{-1} b, where :math:`K_{xx}` is a symmetric, positive definite linear operator defined through the :ref:`KeOps generic syntax <part.generic_formulas>` and :math:`\alpha` is a nonnegative regularization parameter. In the following script, we use it to solve large-scale `Kriging <https://en.wikipedia.org/wiki/Kriging>`_ (aka. `Gaussian process regression <https://scikit-learn.org/stable/modules/gaussian_process.html>`_ or `generalized spline interpolation <https://en.wikipedia.org/wiki/Spline_interpolation>`_) problems with a **linear memory footprint**. """ ######################################################################## # Setup # ---------------------- # # Standard imports: import time import numpy as np from matplotlib import pyplot as plt from pykeops.numpy import LazyTensor import pykeops.config ####################################################################### # Generate some data: dtype = "float64" N = 10000 if pykeops.config.gpu_available else 1000 # Number of samples # Sampling locations: x = np.random.rand(N, 1).astype(dtype) # Some random-ish 1D signal: b = ( x + 0.5 * np.sin(6 * x) + 0.1 * np.sin(20 * x) + 0.05 * np.random.randn(N, 1).astype(dtype) ) ###################################################################### # Interpolation in 1D # ------------------- # # Specify our **regression model** - a simple **Gaussian** variogram or **kernel matrix** # of deviation **sigma**: def gaussian_kernel(x, y, sigma=0.1): x_i = LazyTensor(x[:, None, :]) # (M, 1, 1) y_j = LazyTensor(y[None, :, :]) # (1, N, 1) D_ij = ((x_i - y_j) ** 2).sum(-1) # (M, N) symbolic matrix of squared distances return (-D_ij / (2 * sigma**2)).exp() # (M, N) symbolic Gaussian kernel matrix ####################################################################### # Perform the **Kernel interpolation**, without forgetting to specify # the ridge regularization parameter **alpha** which controls the trade-off # between a perfect fit (**alpha** = 0) and a # smooth interpolation (**alpha** = :math:`+\infty`): alpha = 1.0 # Ridge regularization start = time.time() K_xx = gaussian_kernel(x, x) a = K_xx.solve(b, alpha=alpha) end = time.time() print( "Time to perform an RBF interpolation with {:,} samples in 1D: {:.5f}s".format( N, end - start ) ) ####################################################################### # Display the (fitted) model on the unit interval: # # Extrapolate on a uniform sample: t = np.reshape(np.linspace(0, 1, 1001), [1001, 1]).astype(dtype) K_tx = gaussian_kernel(t, x) mean_t = K_tx @ a # 1D plot: plt.figure(figsize=(8, 6)) plt.scatter(x[:, 0], b[:, 0], s=100 / len(x)) # Noisy samples plt.plot(t, mean_t, "r") plt.axis([0, 1, 0, 1]) plt.tight_layout() ######################################################################### # Interpolation in 2D # ------------------- # # Generate some data: # Sampling locations: x = np.random.rand(N, 2).astype(dtype) # Some random-ish 2D signal: b = np.sum((x - 0.5) ** 2, axis=1)[:, None] b[b > 0.4**2] = 0 b[b < 0.3**2] = 0 b[b >= 0.3**2] = 1 b = b + 0.05 * np.random.randn(N, 1).astype(dtype) # Add 25% of outliers: Nout = N // 4 b[-Nout:] = np.random.rand(Nout, 1).astype(dtype) ######################################################################## # Specify our **regression model** - a simple **Exponential** variogram # or **Laplacian** kernel matrix of deviation **sigma**: def laplacian_kernel(x, y, sigma=0.1): x_i = LazyTensor(x[:, None, :]) # (M, 1, 1) y_j = LazyTensor(y[None, :, :]) # (1, N, 1) D_ij = ((x_i - y_j) ** 2).sum(-1) # (M, N) symbolic matrix of squared distances return (-D_ij.sqrt() / sigma).exp() # (M, N) symbolic Laplacian kernel matrix ####################################################################### # Perform the **Kernel interpolation**, without forgetting to specify # the ridge regularization parameter **alpha** which controls the trade-off # between a perfect fit (**alpha** = 0) and a # smooth interpolation (**alpha** = :math:`+\infty`): alpha = 10 # Ridge regularization start = time.time() K_xx = laplacian_kernel(x, x) a = K_xx.solve(b, alpha=alpha) end = time.time() print( "Time to perform an RBF interpolation with {:,} samples in 2D: {:.5f}s".format( N, end - start ) ) ######################################################################## # Display the (fitted) model on the unit square: # # Extrapolate on a uniform sample: X = Y = np.linspace(0, 1, 101) X, Y = np.meshgrid(X, Y) t = np.stack((X.ravel(), Y.ravel()), axis=1) K_tx = laplacian_kernel(t, x) mean_t = K_tx @ a mean_t = mean_t.reshape(101, 101)[::-1, :] # 2D plot: noisy samples and interpolation in the background plt.figure(figsize=(8, 8)) plt.scatter(x[:, 0], x[:, 1], c=b.ravel(), s=25000 / len(x), cmap="bwr") plt.imshow(mean_t, interpolation="bilinear", extent=[0, 1, 0, 1], cmap="coolwarm") plt.axis([0, 1, 0, 1]) plt.tight_layout() plt.show()
keops-main
pykeops/pykeops/tutorials/interpolation/plot_RBF_interpolation_numpy.py
""" ================================ K-means clustering - PyTorch API ================================ The :meth:`pykeops.torch.LazyTensor.argmin` reduction supported by KeOps :class:`pykeops.torch.LazyTensor` allows us to perform **bruteforce nearest neighbor search** with four lines of code. It can thus be used to implement a **large-scale** `K-means clustering <https://en.wikipedia.org/wiki/K-means_clustering>`_, **without memory overflows**. .. note:: For large and high dimensional datasets, this script **outperforms its NumPy counterpart** as it avoids transfers between CPU (host) and GPU (device) memories. """ ######################################################################## # Setup # ----------------- # Standard imports: import time import torch from matplotlib import pyplot as plt from pykeops.torch import LazyTensor use_cuda = torch.cuda.is_available() dtype = torch.float32 if use_cuda else torch.float64 device_id = "cuda:0" if use_cuda else "cpu" ######################################################################## # Simple implementation of the K-means algorithm: def KMeans(x, K=10, Niter=10, verbose=True): """Implements Lloyd's algorithm for the Euclidean metric.""" start = time.time() N, D = x.shape # Number of samples, dimension of the ambient space c = x[:K, :].clone() # Simplistic initialization for the centroids x_i = LazyTensor(x.view(N, 1, D)) # (N, 1, D) samples c_j = LazyTensor(c.view(1, K, D)) # (1, K, D) centroids # K-means loop: # - x is the (N, D) point cloud, # - cl is the (N,) vector of class labels # - c is the (K, D) cloud of cluster centroids for i in range(Niter): # E step: assign points to the closest cluster ------------------------- D_ij = ((x_i - c_j) ** 2).sum(-1) # (N, K) symbolic squared distances cl = D_ij.argmin(dim=1).long().view(-1) # Points -> Nearest cluster # M step: update the centroids to the normalized cluster average: ------ # Compute the sum of points per cluster: c.zero_() c.scatter_add_(0, cl[:, None].repeat(1, D), x) # Divide by the number of points per cluster: Ncl = torch.bincount(cl, minlength=K).type_as(c).view(K, 1) c /= Ncl # in-place division to compute the average if verbose: # Fancy display ----------------------------------------------- if use_cuda: torch.cuda.synchronize() end = time.time() print( f"K-means for the Euclidean metric with {N:,} points in dimension {D:,}, K = {K:,}:" ) print( "Timing for {} iterations: {:.5f}s = {} x {:.5f}s\n".format( Niter, end - start, Niter, (end - start) / Niter ) ) return cl, c ############################################################### # K-means in 2D # ---------------------- # First experiment with N=10,000 points in dimension D=2, with K=50 classes: # N, D, K = 10000, 2, 50 ############################################################### # Define our dataset: x = 0.7 * torch.randn(N, D, dtype=dtype, device=device_id) + 0.3 ############################################################### # Perform the computation: cl, c = KMeans(x, K) ############################################################### # Fancy display: plt.figure(figsize=(8, 8)) plt.scatter(x[:, 0].cpu(), x[:, 1].cpu(), c=cl.cpu(), s=30000 / len(x), cmap="tab10") plt.scatter(c[:, 0].cpu(), c[:, 1].cpu(), c="black", s=50, alpha=0.8) plt.axis([-2, 2, -2, 2]) plt.tight_layout() plt.show() ################################################################ # KeOps is a versatile library: we can add support for the cosine # similarity with a few lines of code. def KMeans_cosine(x, K=10, Niter=10, verbose=True): """Implements Lloyd's algorithm for the Cosine similarity metric.""" start = time.time() N, D = x.shape # Number of samples, dimension of the ambient space c = x[:K, :].clone() # Simplistic initialization for the centroids # Normalize the centroids for the cosine similarity: c = torch.nn.functional.normalize(c, dim=1, p=2) x_i = LazyTensor(x.view(N, 1, D)) # (N, 1, D) samples c_j = LazyTensor(c.view(1, K, D)) # (1, K, D) centroids # K-means loop: # - x is the (N, D) point cloud, # - cl is the (N,) vector of class labels # - c is the (K, D) cloud of cluster centroids for i in range(Niter): # E step: assign points to the closest cluster ------------------------- S_ij = x_i | c_j # (N, K) symbolic Gram matrix of dot products cl = S_ij.argmax(dim=1).long().view(-1) # Points -> Nearest cluster # M step: update the centroids to the normalized cluster average: ------ # Compute the sum of points per cluster: c.zero_() c.scatter_add_(0, cl[:, None].repeat(1, D), x) # Normalize the centroids, in place: c[:] = torch.nn.functional.normalize(c, dim=1, p=2) if verbose: # Fancy display ----------------------------------------------- if use_cuda: torch.cuda.synchronize() end = time.time() print( f"K-means for the cosine similarity with {N:,} points in dimension {D:,}, K = {K:,}:" ) print( "Timing for {} iterations: {:.5f}s = {} x {:.5f}s\n".format( Niter, end - start, Niter, (end - start) / Niter ) ) return cl, c ################################################################ # Timings are similar to the Euclidean case: cl, c = KMeans_cosine(x, K) ############################################################### # Clusters behave as slices around the origin: plt.figure(figsize=(8, 8)) plt.scatter(x[:, 0].cpu(), x[:, 1].cpu(), c=cl.cpu(), s=30000 / len(x), cmap="tab10") plt.scatter(c[:, 0].cpu(), c[:, 1].cpu(), c="black", s=50, alpha=0.8) plt.axis([-2, 2, -2, 2]) plt.tight_layout() plt.show() #################################################################### # K-means in dimension 100 # ------------------------- # Second experiment with N=1,000,000 points in dimension D=100, with K=1,000 classes: if use_cuda: N, D, K = 1000000, 100, 1000 x = torch.randn(N, D, dtype=dtype, device=device_id) cl, c = KMeans(x, K) cl, c = KMeans_cosine(x, K)
keops-main
pykeops/pykeops/tutorials/kmeans/plot_kmeans_torch.py
""" =============================== K-means clustering - NumPy API =============================== The :meth:`pykeops.numpy.LazyTensor.argmin` reduction supported by KeOps :class:`pykeops.numpy.LazyTensor` allows us to perform **bruteforce nearest neighbor search** with four lines of code. It can thus be used to implement a **large-scale** `K-means clustering <https://en.wikipedia.org/wiki/K-means_clustering>`_, **without memory overflows**. .. note:: For large and high dimensional datasets, this script **is outperformed by its PyTorch counterpart** which avoids transfers between CPU (host) and GPU (device) memories. """ ######################################################################### # Setup # ----------------- # Standard imports: import time import numpy as np from matplotlib import pyplot as plt from pykeops.numpy import LazyTensor import pykeops.config dtype = "float32" # May be 'float32' or 'float64' ########################################################################## # Simple implementation of the K-means algorithm: def KMeans(x, K=10, Niter=10, verbose=True): N, D = x.shape # Number of samples, dimension of the ambient space # K-means loop: # - x is the point cloud, # - cl is the vector of class labels # - c is the cloud of cluster centroids start = time.time() c = np.copy(x[:K, :]) # Simplistic random initialization x_i = LazyTensor(x[:, None, :]) # (Npoints, 1, D) for i in range(Niter): c_j = LazyTensor(c[None, :, :]) # (1, Nclusters, D) D_ij = ((x_i - c_j) ** 2).sum( -1 ) # (Npoints, Nclusters) symbolic matrix of squared distances cl = D_ij.argmin(axis=1).astype(int).reshape(N) # Points -> Nearest cluster Ncl = np.bincount(cl).astype(dtype) # Class weights for d in range(D): # Compute the cluster centroids with np.bincount: c[:, d] = np.bincount(cl, weights=x[:, d]) / Ncl end = time.time() if verbose: print( "K-means example with {:,} points in dimension {:,}, K = {:,}:".format( N, D, K ) ) print( "Timing for {} iterations: {:.5f}s = {} x {:.5f}s\n".format( Niter, end - start, Niter, (end - start) / Niter ) ) return cl, c ############################################################### # K-means in 2D # ---------------------- # First experiment with N=10,000 points in dimension D=2, with K=50 classes: # N, D, K = 10000, 2, 50 ############################################################### # Define our dataset: x = np.random.randn(N, D).astype(dtype) / 6 + 0.5 ############################################################## # Perform the computation: cl, c = KMeans(x, K) ############################################################## # Fancy display: plt.figure(figsize=(8, 8)) plt.scatter(x[:, 0], x[:, 1], c=cl, s=30000 / len(x), cmap="tab10") plt.scatter(c[:, 0], c[:, 1], c="black", s=50, alpha=0.8) plt.axis([0, 1, 0, 1]) plt.tight_layout() plt.show() #################################################################### # K-means in dimension 100 # ------------------------- # Second experiment with N=1,000,000 points in dimension D=100, with K=1,000 classes: if pykeops.config.gpu_available: N, D, K = 1000000, 100, 1000 x = np.random.randn(N, D).astype(dtype) cl, c = KMeans(x, K)
keops-main
pykeops/pykeops/tutorials/kmeans/plot_kmeans_numpy.py
# Always prefer setuptools over distutils # To use a consistent encoding from codecs import open import os from os import path from setuptools import setup here = path.abspath(path.dirname(__file__)) with open(os.path.join(here, "keopscore", "keops_version"), encoding="utf-8") as v: current_version = v.read().rstrip() # Get the long description from the README file with open(path.join(here, "keopscore", "readme.md"), encoding="utf-8") as f: long_description = f.read() setup( name="keopscore", version=current_version, description="keopscore is the KeOps meta programming engine. This python module should be used through a binder (e.g. pykeops or rkeops)", # Required long_description=long_description, long_description_content_type="text/markdown", url="http://www.kernel-operations.io/", project_urls={ "Bug Reports": "https://github.com/getkeops/keops/issues", "Source": "https://github.com/getkeops/keops", }, author="B. Charlier, J. Feydy, J. Glaunes", author_email="[email protected], [email protected], [email protected]", python_requires=">=3", classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Topic :: Scientific/Engineering", "License :: OSI Approved :: MIT License", "Operating System :: POSIX :: Linux", "Operating System :: MacOS :: MacOS X", "Programming Language :: C++", "Programming Language :: Python :: 3 :: Only", ], keywords="kernels gpu autodiff", packages=[ "keopscore", "keopscore.binders", "keopscore.binders.cpp", "keopscore.binders.nvrtc", "keopscore.config", "keopscore.formulas", "keopscore.formulas.autodiff", "keopscore.formulas.complex", "keopscore.formulas.maths", "keopscore.formulas.reductions", "keopscore.formulas.variables", "keopscore.include", "keopscore.mapreduce", "keopscore.mapreduce.cpu", "keopscore.mapreduce.gpu", "keopscore.tests", "keopscore.utils", ], package_data={ "keopscore": [ "readme.md", "licence.txt", "keops_version", "config/libiomp5.dylib", "binders/nvrtc/keops_nvrtc.cpp", "binders/nvrtc/nvrtc_jit.cpp", "include/CudaSizes.h", "include/ranges_utils.h", "include/Ranges.h", "include/Sizes.h", "include/utils_pe.h", ], }, install_requires=[], extras_require={}, )
keops-main
keopscore/setup.py
""" This is the main entry point for all binders. It takes as inputs : - map_reduce_id : string naming the type of map-reduce scheme to be used : either "CpuReduc", "GpuReduc1D_FromDevice", ... - red_formula_string : string expressing the formula, such as "Sum_Reduction((Exp(Minus(Sum(Square((Var(0,3,0) / Var(1,3,1)))))) * Var(2,1,1)),0)", - enable_chunks : -1, 0 or 1, for Gpu mode only, enable special routines for high dimensions (-1 means automatic setting) - enable_finalchunks : -1, 0 or 1, for Gpu mode only, enable special routines for final operation in high dimensions (-1 means automatic setting) - mul_var_highdim : -1, 0 or 1, for Gpu mode only, another option for special routines of final operation in high dimensions (-1 means automatic setting) - aliases : list of strings expressing the aliases list, which may be empty, - nargs : integer specifying the number of arguments for the call to the routine, - dtype : string specifying the float type of the arguments "float", "double" or "half") - dtypeacc : string specifying the float type of the accumulator of the reduction ("float", "double" or "half") - sum_scheme_string : string specifying the type of accumulation for summation reductions : either "direct_sum", "block_sum" or "kahan_scheme". - tagHostDevice : 0 or 1, for Gpu mode only, use indicates whether data is stored on Host (0) or Gpu Device (1) - tagCPUGPU : 0 or 1, indicates whether we use Cpu (0) or Gpu (1) mode, i.e. reduction is performed on Cpu or Gpu - tag1D2D : 0 or 1, for Gpu mode only, use 1D (0) or 2D (1) computation map-reduce scheme - use_half : 0 or 1, for Gpu mode only, enable special routines for half-precision data type - device_id : integer, for Gpu mode only, id of Gpu device to build the code for It returns - tag : string, hash code used as id for the input formula and parameters - source_file : string, either : - in CPU mode : name of the source file to be compiled - in GPU mode : name of the main dll to be called - low_level_code_file : string, either : - in CPU mode : the empty string "" - in GPU mode : name of the low level code (ptx) or binary file (cubin) to be passed to the main dll. - tagI : integer, 0 or 1, specifying if reduction must be performed over i or j indices, - tagZero : integer, 0 or 1, specifying if reduction just consists in filling output with zeros, - use_half : 0 or 1, enable special routines for half-precision data type, - cuda_block_size : integer, prefered block size for Gpu kernel - use_chunk_mode : 0, 1 or 2, if 1 or 2, enables special routines for high dimensions, - tag1D2D : same as input - dimred : integer, dimension of the inner reduction operation. - dim : integer, dimension of the output tensor. - dimy : integer, total dimension of the j indexed variables. - indsi : list of integers, indices of i indexed variables. - indsj : list of integers, indices of j indexed variables. - indsp : list of integers, indices of parameter variables. - dimsx : list of integers, dimensions of i indexed variables. - dimsy : list of integers, dimensions of j indexed variables. - indsp : list of integers, dimensions of parameter variables. It can be used as a Python function or as a standalone Python script (in which case it prints the outputs): - example (as Python function) : get_keops_dll("CpuReduc", "Sum_Reduction((Exp(Minus(Sum(Square((Var(0,3,0) / Var(1,3,1)))))) * Var(2,1,1)),0)", 0, 0, 0, [], 3, "float", "float", "block_sum", 0, 0, 0, 0, 0) - example (as Python script) : python get_keops_dll.py CpuReduc "Sum_Reduction((Exp(Minus(Sum(Square((Var(0,3,0) / Var(1,3,1)))))) * Var(2,1,1)),0)" 0 0 0 "[]" 3 float float block_sum 0 0 0 0 0 """ import inspect import sys import keopscore.config.config from keopscore.config.config import get_build_folder import keopscore.mapreduce from keopscore import cuda_block_size from keopscore.config.chunks import ( get_enable_chunk, set_enable_chunk, dimchunk, set_enable_finalchunk, use_final_chunks, set_mult_var_highdim, ) from keopscore.formulas import Zero_Reduction, Sum_Reduction from keopscore.formulas.GetReduction import GetReduction from keopscore.formulas.variables.Zero import Zero from keopscore.utils.Cache import Cache from keopscore.utils.code_gen_utils import KeOps_Error # Get every classes in mapreduce map_reduce = dict(inspect.getmembers(keopscore.mapreduce, inspect.isclass)) def get_keops_dll_impl( map_reduce_id, red_formula_string, enable_chunks, enable_finalchunks, mul_var_highdim, aliases, *args, ): # detecting the need for special chunked computation modes : use_chunk_mode = 0 if "Gpu" in map_reduce_id: if not keopscore.config.config.use_cuda: KeOps_Error( "You selected a Gpu reduce scheme but KeOps is in Cpu only mode." ) set_enable_chunk(enable_chunks) set_enable_finalchunk(enable_finalchunks) set_mult_var_highdim(mul_var_highdim) red_formula = GetReduction(red_formula_string, aliases) if use_final_chunks(red_formula) and map_reduce_id != "GpuReduc2D": use_chunk_mode = 2 map_reduce_id += "_finalchunks" elif get_enable_chunk() and map_reduce_id != "GpuReduc2D": if len(red_formula.formula.chunked_formulas(dimchunk)) == 1: from keopscore.mapreduce.Chunk_Mode_Constants import ( Chunk_Mode_Constants, ) chk = Chunk_Mode_Constants(red_formula) if not chk.chunk_postchunk_mix: use_chunk_mode = 1 map_reduce_id += "_chunks" # Instantiation of map_reduce_class = map_reduce[map_reduce_id] map_reduce_obj = map_reduce_class(red_formula_string, aliases, *args) # detecting the case of formula being equal to zero, to bypass reduction. rf = map_reduce_obj.red_formula if isinstance(rf, Zero_Reduction) or ( isinstance(rf.formula, Zero) and isinstance(rf, Sum_Reduction) ): if "Gpu" in map_reduce_id: map_reduce_class = map_reduce["GpuReduc1D"] map_reduce_obj = map_reduce_class.AssignZero(red_formula_string, aliases, *args) tagZero = 1 else: tagZero = 0 res = map_reduce_obj.get_dll_and_params() tag1D2D = 0 if tagZero == 1 else res["tag1D2D"] return ( res["tag"], res["source_file"], res["low_level_code_file"], res["tagI"], tagZero, res["use_half"], cuda_block_size, use_chunk_mode, tag1D2D, res["dimred"], res["dim"], res["dimy"], res["indsi"], res["indsj"], res["indsp"], res["dimsx"], res["dimsy"], res["dimsp"], ) get_keops_dll = Cache( get_keops_dll_impl, use_cache_file=True, save_folder=get_build_folder(), ) if __name__ == "__main__": argv = sys.argv[1:] argdict = { "map_reduce_id": str, "red_formula_string": str, "enable_chunks": int, "enable_finalchunks": int, "mul_var_highdim": int, "aliases": list, "nargs": int, "dtype": str, "dtypeacc": str, "sum_scheme_string": str, "tagHostDevice": int, "tagCPUGPU": int, "tag1D2D": int, "use_half": int, "device_id": int, } if len(argv) != len(argdict): KeOps_Error( f"Invalid call to Python script {sys.argv[0]}. There should be {len(argdict)} arguments corresponding to:\n{list(argdict.keys())}" ) for k, key in enumerate(argdict): argtype = argdict[key] argval = argv[k] if argtype == str else eval(argv[k]) if not isinstance(argval, argtype): KeOps_Error( f"Invalid call to Python script {sys.argv[0]}. Argument number {k + 1} ({key}) should be of type {argtype} but is of type {type(argval)}" ) argdict[key] = argval res = get_keops_dll(argdict["map_reduce_id"], *list(argdict.values())[1:]) for item in res: print(item)
keops-main
keopscore/keopscore/get_keops_dll.py
import sys, os from os import path ########################################################### # Verbosity level verbose = True if os.getenv("KEOPS_VERBOSE") == "0": verbose = False here = path.abspath(path.dirname(__file__)) with open(os.path.join(here, "keops_version"), encoding="utf-8") as v: __version__ = v.read().rstrip() from .config.config import set_build_folder, get_build_folder from .utils.code_gen_utils import clean_keops # flags for debugging : # prints information about atomic operations during code building debug_ops = False # adds C++ code for printing all input and output values # for all atomic operations during computations debug_ops_at_exec = False cuda_block_size = 192 from . import config as keopscoreconfig if keopscoreconfig.config.use_cuda: keopscoreconfig.config.init_cudalibs() from .binders.nvrtc.Gpu_link_compile import Gpu_link_compile from .binders.nvrtc.Gpu_link_compile import jit_compile_dll if not os.path.exists(jit_compile_dll()): Gpu_link_compile.compile_jit_compile_dll()
keops-main
keopscore/keopscore/__init__.py
import os from os.path import join import shutil from ctypes import CDLL, RTLD_GLOBAL import keopscore from ctypes.util import find_library from keopscore.utils.misc_utils import KeOps_Warning, KeOps_Error import platform, sys # global parameters can be set here : use_cuda = True # use cuda if possible use_OpenMP = True # use OpenMP if possible (see function set_OpenMP below) # System Path base_dir_path = os.path.abspath(join(os.path.dirname(os.path.realpath(__file__)), "..")) template_path = join(base_dir_path, "templates") bindings_source_dir = join(base_dir_path) keops_cache_folder = join( os.path.expanduser("~"), ".cache", f"keops{keopscore.__version__}" ) default_build_folder_name = "build" # In case user has specified CUDA_VISIBLE_DEVICES environment variable, # it is better to set the build folder name accordingly. specific_gpus = os.getenv("CUDA_VISIBLE_DEVICES") if specific_gpus: specific_gpus = specific_gpus.replace(",", "_") default_build_folder_name += "_CUDA_VISIBLE_DEVICES_" + specific_gpus default_build_path = join(keops_cache_folder, default_build_folder_name) # init cache folder os.makedirs(keops_cache_folder, exist_ok=True) # build path setter/getter _build_path = None def set_build_folder( path=None, read_save_file=False, write_save_file=True, reset_all=True ): # if path is not given, we either read the save file or use the default build path save_file = join(keops_cache_folder, "build_folder_location.txt") if not path: if read_save_file and os.path.isfile(save_file): f = open(save_file, "r") path = f.read() f.close() else: path = default_build_path # create the folder if not yet done os.makedirs(path, exist_ok=True) # _build_path contains the current build folder path (or None if not yet set). We need # to remove this _build_path from the sys.path, replace the value of _build_path # and update the sys.path global _build_path if _build_path in sys.path: sys.path.remove(_build_path) _build_path = path sys.path.append(path) # saving the location of the build path in a file if write_save_file: f = open(save_file, "w") f.write(path) f.close() # reset all cached formulas if needed if reset_all: keopscore.get_keops_dll.get_keops_dll.reset(new_save_folder=_build_path) if keopscore.config.config.use_cuda: from keopscore.binders.nvrtc.Gpu_link_compile import ( Gpu_link_compile, jit_compile_dll, ) if not os.path.exists(jit_compile_dll()): Gpu_link_compile.compile_jit_compile_dll() set_build_folder(read_save_file=True, write_save_file=False, reset_all=False) def get_build_folder(): return _build_path jit_binary = join(_build_path, "keops_nvrtc.so") # Compiler cxx_compiler = os.getenv("CXX") if cxx_compiler is None: cxx_compiler = "g++" if shutil.which(cxx_compiler) is None: KeOps_Warning( """ The default C++ compiler could not be found on your system. You need to either define the CXX environment variable or a symlink to the g++ command. For example if g++-8 is the command you can do import os os.environ['CXX'] = 'g++-8' """ ) compile_options = " -shared -fPIC -O3 -std=c++11" # cpp options cpp_flags = compile_options + " -flto" disable_pragma_unrolls = True # OpenMP setting # adds compile flags for OpenMP support. if use_OpenMP: if platform.system() == "Darwin": import subprocess, importlib res = subprocess.run( 'echo "#include <omp.h>" | g++ -E - -o /dev/null', stdout=subprocess.PIPE, shell=True, ) if res.returncode != 0: KeOps_Warning("omp.h header is not in the path, disabling OpenMP.") use_OpenMP = False else: # we try to import either mkl or numpy, because it will load # the shared libraries for OpenMP. import importlib.util if importlib.util.find_spec("mkl"): import mkl elif importlib.util.find_spec("numpy"): import numpy # Now we can look if one of libmkl_rt, libomp and/or libiomp is loaded. pid = os.getpid() loaded_libs = {} for lib in ["libomp", "libiomp", "libmkl_rt"]: res = subprocess.run( f"lsof -p {pid} | grep {lib}", stdout=subprocess.PIPE, shell=True ) loaded_libs[lib] = ( os.path.dirname(res.stdout.split(b" ")[-1]).decode("utf-8") if res.returncode == 0 else None ) if loaded_libs["libmkl_rt"]: cpp_flags += f' -Xclang -fopenmp -lmkl_rt -L{loaded_libs["libmkl_rt"]}' elif loaded_libs["libiomp"]: cpp_flags += f' -Xclang -fopenmp -liomp5 -L{loaded_libs["libiomp"]}' elif loaded_libs["libomp"]: cpp_flags += f' -Xclang -fopenmp -lomp -L{loaded_libs["libomp"]}' else: KeOps_Warning("OpenMP shared libraries not loaded, disabling OpenMP.") use_OpenMP = False else: cpp_flags += " -fopenmp -fno-fat-lto-objects" if platform.system() == "Darwin": cpp_flags += " -undefined dynamic_lookup" cpp_flags += " -I" + bindings_source_dir from keopscore.utils.gpu_utils import get_gpu_props cuda_dependencies = ["cuda", "nvrtc"] if all([find_library(lib) for lib in cuda_dependencies]): # N.B. calling get_gpu_props issues a warning if cuda is not available, so we do not add another warning here cuda_available = get_gpu_props()[0] > 0 else: cuda_available = False KeOps_Warning( "Cuda libraries were not detected on the system ; using cpu only mode" ) if not use_cuda and cuda_available: KeOps_Warning( "Cuda appears to be available on your system, but use_cuda is set to False in config.py. Using cpu only mode" ) if use_cuda and not cuda_available: use_cuda = False if use_cuda: from keopscore.utils.gpu_utils import ( libcuda_folder, libnvrtc_folder, get_cuda_include_path, get_cuda_version, ) cuda_version = get_cuda_version() nvrtc_flags = ( compile_options + f" -fpermissive -L{libcuda_folder} -L{libnvrtc_folder} -lcuda -lnvrtc" ) nvrtc_include = " -I" + bindings_source_dir cuda_include_path = get_cuda_include_path() if cuda_include_path: nvrtc_include += " -I" + cuda_include_path jit_source_file = join(base_dir_path, "binders", "nvrtc", "keops_nvrtc.cpp") jit_source_header = join(base_dir_path, "binders", "nvrtc", "keops_nvrtc.h") else: cuda_version = None libcuda_folder = None libnvrtc_folder = None nvrtc_flags = None nvrtc_include = None cuda_include_path = None jit_source_file = None jit_source_header = None jit_binary = None init_cudalibs_flag = False def init_cudalibs(): if not keopscore.config.config.init_cudalibs_flag: # we load some libraries that need to be linked with KeOps code # This is to avoid "undefined symbols" errors. CDLL(find_library("nvrtc"), mode=RTLD_GLOBAL) CDLL(find_library("cuda"), mode=RTLD_GLOBAL) CDLL(find_library("cudart"), mode=RTLD_GLOBAL) keopscore.config.config.init_cudalibs_flag = True
keops-main
keopscore/keopscore/config/config.py
keops-main
keopscore/keopscore/config/__init__.py
# special computation scheme for dim>100 enable_chunk = True def get_enable_chunk(): global enable_chunk return enable_chunk def set_enable_chunk(val): global enable_chunk if val == 1: enable_chunk = True elif val == 0: enable_chunk = False dimchunk = 64 dim_treshold_chunk = 146 specdims_use_chunk = [99, 100, 102, 120, 133, 138, 139, 140, 141, 142] # special mode for formula of the type sum_j k(x_i,y_j)*b_j with high dimensional b_j enable_final_chunk = True def set_enable_finalchunk(val): global enable_final_chunk if val == 1: enable_final_chunk = True elif val == 0: enable_final_chunk = False dimfinalchunk = 64 def get_dimfinalchunk(): global dimfinalchunk return dimfinalchunk def set_dimfinalchunk(val): global dimfinalchunk dimfinalchunk = val def use_final_chunks(red_formula): global enable_final_chunk global mult_var_highdim global dim_treshold_chunk return ( enable_final_chunk and mult_var_highdim and red_formula.dim > dim_treshold_chunk ) mult_var_highdim = False def set_mult_var_highdim(val): global mult_var_highdim if val == 1: mult_var_highdim = True elif val == 0: mult_var_highdim = False
keops-main
keopscore/keopscore/config/chunks.py
keops-main
keopscore/keopscore/include/__init__.py
keops-main
keopscore/keopscore/tests/__init__.py
import os.path import sys import types import numpy as np import torch from torch.autograd import grad import keopscore from pykeops.torch import Genred sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")) import unittest from keopscore.formulas.maths import * def perform_test(op_str, tol=1e-4, dtype="float32"): # N.B. dtype can be 'float32', 'float64' or 'float16' print("") keops_op = eval(op_str) if isinstance(keops_op, types.FunctionType): op_class_str = f"{op_str}_Impl" exec(f"from {keops_op.__module__} import {op_class_str}") keops_op_class = eval(op_class_str) else: keops_op_class = keops_op if keops_op_class.enable_test: if hasattr(keops_op_class, "test_argdims"): dims = keops_op_class.test_argdims nargs = len(dims) else: if hasattr(keops_op_class, "nargs"): nargs = keops_op_class.nargs elif hasattr(keops_op_class, "test_ranges"): nargs = len(keops_op_class.test_ranges) elif hasattr(keops_op_class, "Derivative"): from inspect import signature nargs = len(signature(keops_op_class.Derivative).parameters) if hasattr(keops_op_class, "test_params"): nargs -= len(keops_op_class.test_params) else: print("no test available for " + op_str) return None dims = [3] * nargs else: print("no test available for " + op_str) return None ##################################################################### # Declare random inputs: M = 3000 N = 5000 # Choose the storage place for our data : CPU (host) or GPU (device) memory. device = torch.device("cuda" if torch.cuda.is_available() else "cpu") if dtype == "float32": torchtype = torch.float32 elif dtype == "float64": torchtype = torch.float64 elif dtype == "float16": torchtype = torch.float16 else: raise ValueError("invalid dtype") argcats = np.random.choice(["i", "j"], nargs) if hasattr(keops_op_class, "test_ranges"): rng = keops_op_class.test_ranges rand = torch.rand else: rng = [(0, 1)] * nargs rand = torch.randn args = [None] * nargs for k in range(nargs): MorN = M if argcats[k] == "i" else N args[k] = rand( MorN, dims[k], dtype=torchtype, device=device, requires_grad=True ) args[k] = args[k] * (rng[k][1] - rng[k][0]) + rng[k][0] #################################################################### # Define a custom formula # ----------------------- if hasattr(keops_op_class, "test_params"): params = keops_op_class.test_params else: params = () formula = ( op_str + "(" + ",".join(f"v{k}" for k in range(nargs)) + "," + ",".join(str(p) for p in params) + ")" ) variables = list(f"v{k} = V{argcats[k]}({dims[k]})" for k in range(nargs)) # print("Testing operation " + op_str) my_routine = Genred(formula, variables, reduction_op="Sum", axis=1, dtype=dtype) c = my_routine(*args) # print("ok, no error") # print("5 first values :", *c.flatten()[:5].tolist()) #################################################################### # Compute the gradient # ----------------------- e = torch.rand_like(c) # print("Testing gradient of operation " + op_str) g = grad(c, args, e) # print("ok, no error") # for k in range(nargs): # app_str = f"number {k}" if len(args) > 1 else "" # print(f"5 first values for gradient {app_str}:", *g[k].flatten()[:5].tolist()) if not hasattr(keops_op_class, "torch_op"): torch_op_str = keops_op_class.string_id.lower() if not torch_op_str in dir(torch): return None torch_op = "torch." + torch_op_str else: if keops_op_class.torch_op is None: return None torch_op = keops_op_class.torch_op print("Comparing with PyTorch implementation ") torch_args = [None] * nargs for k in range(nargs): torch_args[k] = ( args[k][:, None, :] if argcats[k] == "i" else args[k][None, :, :] ) #################################################################### # The equivalent code with a "vanilla" pytorch implementation if isinstance(torch_op, str): torch_op = eval(torch_op) c_torch = torch_op(*torch_args, *params).sum(dim=1) # err_op = torch.norm(c - c_torch).item() / torch.norm(c_torch).item() err_op = torch.allclose(c, c_torch, atol=tol, rtol=tol) print("relative error for operation :", err_op) if not hasattr(keops_op_class, "no_torch_grad") or not keops_op_class.no_torch_grad: g_torch = grad(c_torch, args, e) err_gr = [None] * nargs for k in range(nargs): app_str = f"number {k}" if len(args) > 1 else "" print(g_torch[k][:10], g[k][:10]) # err_gr[k] = (torch.norm(g[k] - g_torch[k]) / torch.norm(g_torch[k])).item() err_gr[k] = torch.allclose(g[k], g_torch[k], atol=tol, rtol=tol) print(f"relative error for gradient {app_str}:", err_gr[k]) else: print("no gradient for torch") return [err_op] return [err_op] + err_gr class OperationUnitTestCase(unittest.TestCase): def test_formula_maths(self): for b in keopscore.formulas.maths.__all__: with self.subTest(b=b): # Call cuda kernel res = perform_test(b) print("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee") print(b, res) print("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee") if res is not None: self.assertTrue(all(res)) else: pass if __name__ == "__main__": """ run tests """ unittest.main()
keops-main
keopscore/keopscore/tests/test_op.py
import time import torch import numpy as np from torch.autograd import grad from pykeops.torch import Genred from keopscore.formulas import * import types def TestOperation(op_str, tol=1e-4, dtype="float32", test_grad=True): # N.B. dtype can be 'float32', 'float64' or 'float16' print("") keops_op = eval(op_str) if isinstance(keops_op, types.FunctionType): op_class_str = f"{op_str}_Impl" exec(f"from {keops_op.__module__} import {op_class_str}") keops_op_class = eval(op_class_str) else: keops_op_class = keops_op if keops_op_class.enable_test: if hasattr(keops_op_class, "test_argdims"): dims = keops_op_class.test_argdims nargs = len(dims) else: if hasattr(keops_op_class, "nargs"): nargs = keops_op_class.nargs elif hasattr(keops_op_class, "test_ranges"): nargs = len(keops_op_class.test_ranges) elif hasattr(keops_op_class, "Derivative"): from inspect import signature nargs = len(signature(keops_op_class.Derivative).parameters) if hasattr(keops_op_class, "test_params"): nargs -= len(keops_op_class.test_params) else: print("no test available for " + op_str) return None dims = [3] * nargs else: print("no test available for " + op_str) return None ##################################################################### # Declare random inputs: M = 3000 N = 5000 # Choose the storage place for our data : CPU (host) or GPU (device) memory. device = torch.device("cuda" if torch.cuda.is_available() else "cpu") if dtype == "float32": torchtype = torch.float32 elif dtype == "float64": torchtype = torch.float64 elif dtype == "float16": torchtype = torch.float16 else: raise ValueError("invalid dtype") argcats = np.random.choice(["i", "j"], nargs) if hasattr(keops_op_class, "test_ranges"): rng = keops_op_class.test_ranges rand = torch.rand else: rng = [(0, 1)] * nargs rand = torch.randn args = [None] * nargs for k in range(nargs): MorN = M if argcats[k] == "i" else N args[k] = rand( MorN, dims[k], dtype=torchtype, device=device, requires_grad=True ) args[k] = args[k] * (rng[k][1] - rng[k][0]) + rng[k][0] #################################################################### # Define a custom formula # ----------------------- if hasattr(keops_op_class, "test_params"): params = keops_op_class.test_params else: params = () formula = ( op_str + "(" + ",".join(f"v{k}" for k in range(nargs)) + "," + ",".join(str(p) for p in params) + ")" ) variables = list(f"v{k} = V{argcats[k]}({dims[k]})" for k in range(nargs)) print("Testing operation " + op_str) my_routine = Genred(formula, variables, reduction_op="Sum", axis=1) c = my_routine(*args) print("ok, no error") print("5 first values :", *c.flatten()[:5].tolist()) #################################################################### # Compute the gradient # ----------------------- if test_grad: e = torch.rand_like(c) print("Testing gradient of operation " + op_str) g = grad(c, args, e) print("ok, no error") for k in range(nargs): app_str = f"number {k}" if len(args) > 1 else "" print( f"5 first values for gradient {app_str}:", *g[k].flatten()[:5].tolist() ) if not hasattr(keops_op_class, "torch_op"): torch_op_str = keops_op_class.string_id.lower() if not torch_op_str in dir(torch): return "no_torch" torch_op = "torch." + torch_op_str else: if keops_op_class.torch_op is None: return "no_torch" torch_op = keops_op_class.torch_op print("Comparing with PyTorch implementation ") torch_args = [None] * nargs for k in range(nargs): torch_args[k] = ( args[k][:, None, :] if argcats[k] == "i" else args[k][None, :, :] ) #################################################################### # The equivalent code with a "vanilla" pytorch implementation if isinstance(torch_op, str): torch_op = eval(torch_op) c_torch = torch_op(*torch_args, *params).sum(dim=1) err_op = torch.norm(c - c_torch).item() / torch.norm(c_torch).item() print("relative error for operation :", err_op) if test_grad: if ( not hasattr(keops_op_class, "no_torch_grad") or not keops_op_class.no_torch_grad ): g_torch = grad(c_torch, args, e) err_gr = [None] * nargs for k in range(nargs): app_str = f"number {k}" if len(args) > 1 else "" err_gr[k] = ( torch.norm(g[k] - g_torch[k]) / torch.norm(g_torch[k]) ).item() print(f"relative error for gradient {app_str}:", err_gr[k]) else: print("no gradient for torch") return abs(err_op) > tol return abs(err_op) > tol, list(abs(err) > tol for err in err_gr) else: return abs(err_op) > tol
keops-main
keopscore/keopscore/utils/TestOperation.py
class Tree: """a custom class for handling a tree structure. Currently we use it only to recursively print a formula or reduction""" def recursive_str(self): if hasattr(self, "print_spec"): idstr, mode, level = self.print_spec if mode == "pre": pre_string = idstr middle_string = "," post_string = "" elif mode == "mid": pre_string = "" middle_string = idstr post_string = "" elif mode == "post": pre_string = "" middle_string = "," post_string = idstr else: pre_string = self.string_id + "(" middle_string = "," post_string = ")" string = pre_string for k, child in enumerate(self.children): test = ( hasattr(child, "print_spec") and hasattr(self, "print_spec") and child.print_spec[2] >= level ) string += "(" if test else "" string += child.recursive_str() string += ")" if test else "" string += middle_string if k < len(self.children) - 1 else "" for k, param in enumerate(self.params): if k > 0 or len(self.children) > 0: string += "," string += str(param) string += post_string return string def print_expand(self, depth=0): depth += 1 string = self.string_id for child in self.children: string += ( "\n" + depth * 4 * " " + "{}".format(child.recursive_str(depth=depth)) ) for param in self.params: string += "\n" + depth * 4 * " " + str(param) return string def __str__(self): return self.recursive_str() def __repr__(self): return self.recursive_str() # custom __eq__ method def __eq__(self, other): return ( type(self) == type(other) and len(self.children) == len(other.children) and all([x == y for x, y in zip(self.children, other.children)]) )
keops-main
keopscore/keopscore/utils/Tree.py
import os from hashlib import sha256 from keopscore.config.config import disable_pragma_unrolls from keopscore.utils.misc_utils import KeOps_Error, KeOps_Message def get_hash_name(*args): return sha256("".join(list(str(arg) for arg in args)).encode("utf-8")).hexdigest()[ :10 ] ####################################################################### # . Python to C++ meta programming toolbox ####################################################################### def sizeof(dtype): if dtype == "float": return 4 elif dtype == "double": return 8 elif dtype == "half": return 2 else: KeOps_Error("not implemented") class new_c_varname: # class to generate unique names for variables in C++ code, to avoid conflicts dict_instances = {} def __new__(self, template_string_id, num=1, as_list=False): # - template_string_id is a string, the base name for c_variable # - if num>1 returns a list of num new names with same base names # For example the first call to new_c_variable("x") # will return "x_1", the second call will return "x_2", etc. if num > 1 or as_list: return list(new_c_varname(template_string_id) for k in range(num)) if template_string_id in new_c_varname.dict_instances: cnt = new_c_varname.dict_instances[template_string_id] + 1 else: cnt = 0 new_c_varname.dict_instances[template_string_id] = cnt string_id = template_string_id + "_" + str(cnt) return string_id class c_variable: # class to represent a C++ variable, storing its c++ name and its C++ type. def __new__(self, dtype, list_string_id=None): if isinstance(list_string_id, list): return list(c_variable(dtype, string_id) for string_id in list_string_id) else: return super(c_variable, self).__new__(self) def __init__(self, dtype, string_id=None): if string_id is None: string_id = new_c_varname("var") self.dtype = dtype # dtype is C++ type of variable self.id = string_id # string_id is C++ name of variable def __repr__(self): # method for printing the c_variable inside Python code return self.id def declare(self): return f"{self.dtype} {self.id};\n" def declare_assign(self, value): return f"{self.dtype} " + self.assign(value) def assign(self, value): if type(value) in (int, float): dtype = "int" if type(value) == int else "float" return self.assign(c_variable(dtype, str(value))) elif type(value) == str: return f"{self.id} = ({self.dtype})({value});\n" elif value.dtype != self.dtype: if self.dtype == "float2" and value.dtype == "float": return f""" {self.id}.x = {value.id}; {self.id}.y = {value.id}; """ else: return f"{self.id} = {cast_to(self.dtype, value)};\n" else: return f"{self.id} = ({value.id});\n" def add_assign(self, value): if type(value) in (int, float): dtype = "int" if type(value) == int else "float" return self.add_assign(c_variable(dtype, str(value))) if type(value) == str: return f"{self.id} += ({self.dtype})({value});\n" elif value.dtype != self.dtype: if self.dtype == "float2" and value.dtype == "half2": return f""" {self.id}.x += (float){value.id}.x; {self.id}.y += (float){value.id}.y; """ else: return f"{self.id} += {cast_to(self.dtype, value)};\n" else: return f"{self.id} += ({value.id});\n" def __add__(self, other): if type(other) in (int, float): dtype = "int" if type(other) == int else "float" return self + c_variable(dtype, str(other)) elif type(other) == c_variable: if self.dtype != other.dtype: KeOps_Error("addition of two c_variable only possible with same dtype") return c_variable(self.dtype, f"({self.id}+{other.id})") else: KeOps_Error("not implemented") def __mul__(self, other): if type(other) in (int, float): dtype = "int" if type(other) == int else "float" return self * c_variable(dtype, str(other)) elif type(other) == c_variable: if self.dtype != other.dtype: KeOps_Error( "multiplication of two c_variable only possible with same dtype" ) return c_variable(self.dtype, f"({self.id}*{other.id})") else: KeOps_Error("not implemented") def __sub__(self, other): if type(other) in (int, float): dtype = "int" if type(other) == int else "float" return self - c_variable(dtype, str(other)) elif type(other) == c_variable: if self.dtype != other.dtype: KeOps_Error( "subtraction of two c_variable only possible with same dtype" ) return c_variable(self.dtype, f"({self.id}-{other.id})") else: KeOps_Error("not implemented") def __truediv__(self, other): if type(other) in (int, float): dtype = "int" if type(other) == int else "float" return self / c_variable(dtype, str(other)) elif type(other) == c_variable: if self.dtype != other.dtype: KeOps_Error("division of two c_variable only possible with same dtype") return c_variable(self.dtype, f"({self.id}/{other.id})") else: KeOps_Error("not implemented") def __lt__(self, other): if type(other) in (int, float): dtype = "int" if type(other) == int else "float" return self < c_variable(dtype, str(other)) elif type(other) == c_variable: if self.dtype != other.dtype: KeOps_Error( "comparison of two c_variable only possible with same dtype" ) return c_variable("bool", f"({self.id}<{other.id})") else: KeOps_Error("not implemented") def __gt__(self, other): if type(other) in (int, float): dtype = "int" if type(other) == int else "float" return self > c_variable(dtype, str(other)) elif type(other) == c_variable: if self.dtype != other.dtype: KeOps_Error( "comparison of two c_variable only possible with same dtype" ) return c_variable("bool", f"({self.id}>{other.id})") else: KeOps_Error("not implemented") def __neg__(self): return c_variable(self.dtype, f"(-{self.id})") def __getitem__(self, other): if type(other) == int: return self[c_variable("int", str(other))] elif type(other) == c_variable: if other.dtype != "int": KeOps_Error("v[i] with i and v c_variable requires i.dtype='int' ") return c_variable(value(self.dtype), f"{self.id}[{other.id}]") else: KeOps_Error("not implemented") def use_pragma_unroll(n=64): if disable_pragma_unrolls: return "\n" else: if n is None: return f"\n#pragma unroll\n" else: return f"\n#pragma unroll({n})\n" def c_for_loop(start, end, incr, pragma_unroll=False): def to_string(x): if type(x) == c_variable: if x.dtype != "int": KeOps_Error("only simple int type for loops implemented") return x.id elif type(x) == int: return str(x) else: KeOps_Error("only simple int type for loops implemented") start, end, incr = map(to_string, (start, end, incr)) k = c_variable("int", new_c_varname("k")) def printfun(body_code): string = "" if pragma_unroll: string += use_pragma_unroll() string += f""" for(int {k.id}={start}; {k.id}<{end}; {k.id}+=({incr})) {{ {body_code} }} """ return string return printfun, k c_zero_int = c_variable("int", "0") c_zero_float = c_variable("float", "0.0f") def neg_infinity(dtype): return c_variable(dtype, f"-({infinity(dtype).id})") def infinity(dtype): if dtype == "float": code = "( 1.0f/0.0f )" elif dtype == "double": code = "( 1.0/0.0 )" else: KeOps_Error( "only float and double dtypes are implemented in new python engine for now" ) return c_variable(dtype, code) def cast_to(dtype, var): # returns C++ code string to do a cast ; e.g. "(float)" if dtype is "float" for example simple_dtypes = ["float", "double", "int"] if (dtype in simple_dtypes) and (var.dtype in simple_dtypes): return f"({dtype})({var.id})" elif dtype == "half2" and var.dtype == "float": return f"__float2half2_rn({var.id})" elif dtype == "float2" and var.dtype == "half2": return f"__half22float2({var.id})" elif dtype == "half2" and var.dtype == "float2": return f"__float22half2_rn({var.id})" else: KeOps_Error(f"not implemented: casting from {var.dtype} to {dtype}") def value(x): # either convert c_array or c_variable representing a pointer to its value c_variable (dereference) # or converts string "dtype*" to "dtype" if isinstance(x, c_array): return c_variable(x.dtype, f"(*{x.id})") if isinstance(x, c_variable): return c_variable(value(x.dtype), f"(*{x.id})") elif isinstance(x, str): if x[-1] == "*": return x[:-1] else: KeOps_Error( "Incorrect input string in value function; it should represent a pointer C++ type." ) else: KeOps_Error("input should be either c_variable instance or string.") def pointer(x): # either convert c_variable to its address c_variable (reference) # or converts string "dtype" to "dtype*" if isinstance(x, c_variable): return c_variable(pointer(x.dtype), f"(&{x.id})") elif isinstance(x, str): return x + "*" else: KeOps_Error("input should be either c_variable instance or string.") class c_array: def __init__(self, dtype, dim, string_id=new_c_varname("array")): if dim < 0: KeOps_Error("negative dimension for array") self.c_var = c_variable(pointer(dtype), string_id) self.dtype = dtype self.dim = dim self.id = string_id def __repr__(self): # method for printing the c_variable inside Python code return self.c_var.__repr__() def declare(self): # returns C++ code to declare a fixed-size arry of size dim, # skipping declaration if dim=0 if self.dim > 0: return f"{self.dtype} {self.c_var.id}[{self.dim}];" else: return "" def split(self, *dims): # split c_array in n sub arrays with dimensions dims[0], dims[1], ..., dims[n-1] if sum(dims) != self.dim: KeOps_Error("incompatible dimensions for split") listarr, cumdim = [], 0 for dim in dims: listarr.append(c_array(self.dtype, dim, f"({self.id}+{cumdim})")) cumdim += dim return listarr def assign(self, val): # returns C++ code string to fill all elements of a fixed size array with a single value # val is a c_variable representing the value. loop, k = c_for_loop(0, self.dim, 1) return loop(self[k].assign(val)) def __getitem__(self, other): if type(other) == int: return self[c_variable("int", str(other))] elif type(other) == c_variable: if other.dtype != "int": KeOps_Error("v[i] with i and v c_array requires i.dtype='int' ") return c_variable(self.dtype, f"{self.id}[{other.id}]") else: KeOps_Error("not implemented") @property def c_print(self): if self.dtype in ["float", "double"]: tag = "%f, " * self.dim elif self.dtype in ["int", "float*", "double*"]: tag = "%d, " * self.dim else: KeOps_Error(f"c_print not implemented for dtype={self.dtype}") string = f'printf("{self.id} = {tag}\\n"' for i in range(self.dim): string += f", {self[i].id}" string += ");\n" return string def VectApply(fun, out, *args): # returns C++ code string to apply a scalar operation to fixed-size arrays, following broadcasting rules. # - fun is the scalar unary function to be applied, it must accept two c_variable or c_array inputs and output a string # - out must be a c_array instance # - args may be c_array or c_variable instances # # Example : if out.dim = 3, arg0.dim = 1, arg1.dim = 3, # it will generate the following (in pseudo-code for clarity) : # #pragma unroll # for(int k=0; k<out.dim; k++) # fun(out[k], arg0[0], arg1[k]); # # Equivalently, if out.dim = 3, arg0 is c_variable, arg1.dim = 3, # it will generate the following (in pseudo-code for clarity) : # #pragma unroll # for(int k=0; k<out.dim; k++) # fun(out[k], arg0, arg1[k]); dims = [out.dim] for arg in args: if isinstance(arg, c_variable): dims.append(1) elif isinstance(arg, c_array): dims.append(arg.dim) else: KeOps_Error("args must be c_variable or c_array instances") dimloop = max(dims) if not set(dims) in ({dimloop}, {1, dimloop}): KeOps_Error("incompatible dimensions in VectApply") incr_out = 1 if out.dim == dimloop else 0 incr_args = list((1 if dim == dimloop else 0) for dim in dims[1:]) forloop, k = c_for_loop(0, dimloop, 1, pragma_unroll=True) argsk = [] for (arg, incr) in zip(args, incr_args): if isinstance(arg, c_variable): argsk.append(arg) elif isinstance(arg, c_array): argsk.append(arg[k * incr]) return forloop(fun(out[k * incr_out], *argsk)) def ComplexVectApply(fun, out, *args): # similar to VectApply but for complex operations dims = [out.dim] for arg in args: if isinstance(arg, c_array): dims.append(arg.dim) else: KeOps_Error("args must be c_array instances") dimloop = max(dims) if not set(dims) in ({dimloop}, {2, dimloop}): KeOps_Error("incompatible dimensions in ComplexVectApply") incr_out = 1 if out.dim == dimloop else 0 incr_args = list((1 if dim == dimloop else 0) for dim in dims[1:]) forloop, k = c_for_loop(0, dimloop, 2, pragma_unroll=True) argsk = [] for (arg, incr) in zip(args, incr_args): argk = c_array(arg.dtype, 2, f"({arg.id}+{k.id}*{incr})") argsk.append(argk) outk = c_array(out.dtype, 2, f"({out.id}+{k.id}*{incr_out})") return forloop(fun(outk, *argsk)) def VectCopy(out, arg, dim=None): # returns a C++ code string representing a vector copy between fixed-size arrays # - dim is dimension of arrays # - out is c_variable representing the output array # - arg is c_variable representing the input array if dim is None: dim = out.dim forloop, k = c_for_loop(0, dim, 1, pragma_unroll=True) return forloop(out[k].assign(arg[k])) def call_list(args): return ", ".join(list(arg.id for arg in args)) def signature_list(args): return ", ".join(list(f"{arg.dtype} {arg.id}" for arg in args)) def c_include(*headers): return "".join(f"#include <{header}>\n" for header in headers) def c_if(condition, command, else_command=None): string = f""" if ({condition.id}) {{ {command} }} """ if else_command: string += f""" else {{ {else_command} }} """ return string def c_block(*commands): block_string = "".join(commands) return f""" {{ {block_string} }} """ def c_function(name, dtypeout, args, commands, qualifier=None): # first write the signature of the function : string = "" if qualifier is not None: string += f"{qualifier} " string += f"{dtypeout} {name}({signature_list(args)}) " # then the body string += "\n{\n" string += "\n".join(list(c for c in commands)) string += "\n}\n" return string ####################################################################### # . KeOps related helpers ####################################################################### def GetDims(Vars): # returns the list of dim fields (dimensions) of a list of Var instances return tuple(v.dim for v in Vars) def GetInds(Vars): # returns the list of ind fields (indices) of a list of Var instances return tuple(v.ind for v in Vars) class Var_loader: def __init__(self, red_formula): formula = red_formula.formula tagI, tagJ = red_formula.tagI, red_formula.tagJ mymin = lambda x: min(x) if len(x) > 0 else -1 self.Varsi = formula.Vars( cat=tagI ) # list all "i"-indexed variables in the formula self.nvarsi = len(self.Varsi) # number of "i"-indexed variables self.indsi = GetInds(self.Varsi) # list indices of "i"-indexed variables self.pos_first_argI = mymin(self.indsi) # first index of "i"-indexed variables self.dimsx = GetDims(self.Varsi) # list dimensions of "i"-indexed variables self.dimx = sum(self.dimsx) # total dimension of "i"-indexed variables self.Varsj = formula.Vars( cat=tagJ ) # list all "j"-indexed variables in the formula self.nvarsj = len(self.Varsj) # number of "j"-indexed variables self.indsj = GetInds(self.Varsj) # list indices of "j"-indexed variables self.pos_first_argJ = mymin(self.indsj) # first index of "j"-indexed variables self.dimsy = GetDims(self.Varsj) # list dimensions of "j"-indexed variables self.dimy = sum(self.dimsy) # total dimension of "j"-indexed variables self.Varsp = formula.Vars(cat=2) # list all parameter variables in the formula self.nvarsp = len(self.Varsp) # number of parameter variables self.indsp = GetInds(self.Varsp) # list indices of parameter variables self.pos_first_argP = mymin(self.indsp) # first index of parameter variables self.dimsp = GetDims(self.Varsp) # list indices of parameter variables self.dimp = sum(self.dimsp) # total dimension of parameter variables self.inds = GetInds(formula.Vars_) self.nminargs = max(self.inds) + 1 if len(self.inds) > 0 else 0 def table(self, xi, yj, pp): return table( self.nminargs, self.dimsx, self.dimsy, self.dimsp, self.indsi, self.indsj, self.indsp, xi, yj, pp, ) def direct_table(self, args, i, j): return direct_table( self.nminargs, self.dimsx, self.dimsy, self.dimsp, self.indsi, self.indsj, self.indsp, args, i, j, ) def load_vars(self, cat, *args, **kwargs): if cat == "i": dims, inds = self.dimsx, self.indsi elif cat == "j": dims, inds = self.dimsy, self.indsj elif cat == "p": dims, inds = self.dimsp, self.indsp return load_vars(dims, inds, *args, **kwargs) def table(nminargs, dimsx, dimsy, dimsp, indsi, indsj, indsp, xi, yj, pp): res = [None] * nminargs for (dims, inds, xloc) in ( (dimsx, indsi, xi), (dimsy, indsj, yj), (dimsp, indsp, pp), ): k = 0 for u in range(len(dims)): res[inds[u]] = c_array(xloc.dtype, dims[u], f"({xloc.id}+{k})") k += dims[u] return res def direct_table(nminargs, dimsx, dimsy, dimsp, indsi, indsj, indsp, args, i, j): res = [None] * nminargs for (dims, inds, row_index) in ( (dimsx, indsi, i), (dimsy, indsj, j), (dimsp, indsp, c_zero_int), ): for u in range(len(dims)): arg = args[inds[u]] res[inds[u]] = c_array( value(arg.dtype), dims[u], f"({arg.id}+{row_index.id}*{dims[u]})" ) return res def table4( nminargs, dimsx, dimsy, dimsp, dims_new, indsi, indsj, indsp, inds_new, xi, yj, pp, arg_new, ): res = [None] * nminargs for (dims, inds, xloc) in ( (dimsx, indsi, xi), (dimsy, indsj, yj), (dimsp, indsp, pp), (dims_new, inds_new, arg_new), ): k = 0 for u in range(len(dims)): res[inds[u]] = c_array(xloc.dtype, dims[u], f"({xloc.id}+{k})") k += dims[u] return res def load_vars(dims, inds, xloc, args, row_index=c_zero_int, offsets=None, indsref=None): # returns a c++ code used to create a local copy of slices of the input tensors, for evaluating a formula # - dims is a list of integers giving dimensions of variables # - dims is a list of integers giving indices of variables # - xloc is a c_array, the local array which will receive the copy # - args is a list of c_variable, representing pointers to input tensors # - row_index is a c_variable (of dtype="int"), specifying which row of the matrix should be loaded # - offsets is an optional c_array (of dtype="int"), specifying variable-dependent offsets (used when broadcasting batch dimensions) # - indsref is an optional list of integers, giving index mapping for offsets # # Example: assuming i=c_variable("int", "5"), xloc=c_variable("float", "xi") and px=c_variable("float**", "px"), then # if dims = [2,2,3] and inds = [7,9,8], the call to # load_vars (dims, inds, xi, [arg0, arg1,..., arg9], row_index=i ) # will output the following code: # xi[0] = arg7[5*2+0]; # xi[1] = arg7[5*2+1]; # xi[2] = arg9[5*2+0]; # xi[3] = arg9[5*2+1]; # xi[4] = arg8[5*3+0]; # xi[5] = arg8[5*3+1]; # xi[6] = arg8[5*3+2]; # # Example (with offsets): assuming i=c_variable("int", "5"), # xloc=c_variable("float", "xi"), px=c_variable("float**", "px"), # and offsets = c_array("int", 3, "offsets"), then # if dims = [2,2,3] and inds = [7,9,8], the call to # load_vars (dims, inds, xi, [arg0, arg1,..., arg9], row_index=i, offsets=offsets) # will output the following code: # xi[0] = arg7[(5+offsets[0])*2+0]; # xi[1] = arg7[(5+offsets[0])*2+1]; # xi[2] = arg9[(5+offsets[1])*2+0]; # xi[3] = arg9[(5+offsets[1])*2+1]; # xi[4] = arg8[(5+offsets[2])*3+0]; # xi[5] = arg8[(5+offsets[2])*3+1]; # xi[6] = arg8[(5+offsets[2])*3+2]; # # Example (with offsets and indsref): assuming i=c_variable("int", "5"), # xloc=c_variable("float", "xi"), px=c_variable("float**", "px"), # offsets = c_array("int", 3, "offsets"), # if dims = [2,2,3] and inds = [7,9,8], # and indsref = [8,1,7,3,9,2], then since 7,8,9 are at positions 2,0,4 in indsref, # the call to # load_vars (dims, inds, xi, [arg0, arg1,..., arg9], row_index=i, offsets=offsets, indsref=indsref) # will output the following code: # xi[0] = arg7[(5+offsets[2])*2+0]; # xi[1] = arg7[(5+offsets[2])*2+1]; # xi[2] = arg9[(5+offsets[0])*2+0]; # xi[3] = arg9[(5+offsets[0])*2+1]; # xi[4] = arg8[(5+offsets[4])*3+0]; # xi[5] = arg8[(5+offsets[4])*3+1]; # xi[6] = arg8[(5+offsets[4])*3+2]; string = "" if len(dims) > 0: string += "{\n" string += "int a=0;\n" for u in range(len(dims)): l = indsref.index(inds[u]) if indsref else u row_index_str = ( f"({row_index.id}+{offsets.id}[{l}])" if offsets else row_index.id ) string += use_pragma_unroll() string += f"for(int v=0; v<{dims[u]}; v++) {{\n" string += ( f" {xloc.id}[a] = {args[inds[u]].id}[{row_index_str}*{dims[u]}+v];\n" ) string += " a++;\n" string += "}\n" string += "}\n" return string def load_vars_chunks( inds, dim_chunk, dim_chunk_load, dim_org, xloc, args, k, row_index=c_zero_int ): # # loads chunks of variables, unrolling dimensions and indices. # # Example: # load_chunks([7,9,8], 3, 2, 11, xi, px, k, row_index=i) # with: # xi = c_variable("float", "xi"), # px = c_variable("float**", "px") # i = c_variable("int","5"), # k = c_variable("int","k") # means : there are 3 chunks of vectors to load. They are located # at positions 7, 9 and 8 in px. Now i=5 and dim_org=11, so we start # to load vectors at positions px[7]+5*11, px[9]+5*11, px[8]+5*11. # For each, we load the kth chunk, assuming vector is divided # into chunks of size 3. And finally, we stop after loading 2 values. # # So we will execute: # xi[0] = px[7][5*11+k*3]; # xi[1] = px[7][5*11+k*3+1]; # xi[2] = px[9][5*11+k*3]; # xi[3] = px[9][5*11+k*3+1]; # xi[4] = px[8][5*11+k*3]; # xi[5] = px[8][5*11+k*3+1]; string = "" if len(inds) > 0: string += "{" string += "int a=0;\n" for u in range(len(inds)): string += use_pragma_unroll() string += f"for(int v=0; v<{dim_chunk_load}; v++) {{\n" string += f" {xloc.id}[a] = {args[inds[u]].id}[{row_index.id}*{dim_org}+{k.id}*{dim_chunk}+v];\n" string += " a++;\n" string += "}" string += "}" return string def load_vars_chunks_offsets( inds, indsref, dim_chunk, dim_chunk_load, dim_org, xloc, args, k, offsets, row_index=c_zero_int, ): # Version with variable-dependent offsets (used when broadcasting batch dimensions) # indsref gives mapping for offsets indexing # Example: # load_vars_chunks_offsets([2,3,1], [8,9,7,3,1,2], 3, 2, 11, xi, px, k, offsets, row_index=i) # Since 2,3,1 are at positions 5,3,4 respectively in the list [8,9,7,3,1,2], # will output: # xi[0] = px[2][(5+offsets[5])*11+k*3]; # xi[1] = px[2][(5+offsets[5])*11+k*3+1]; # xi[2] = px[3][(5+offsets[3])*11+k*3]; # xi[3] = px[3][(5+offsets[3])*11+k*3+1]; # xi[4] = px[1][(5+offsets[4])*11+k*3]; # xi[5] = px[1][(5+offsets[4])*11+k*3+1]; string = "" if len(inds) > 0: string = "{" string += "int a=0;\n" for u in range(len(inds)): l = indsref.index(inds[u]) string += use_pragma_unroll() string += f"for(int v=0; v<{dim_chunk_load}; v++) {{\n" string += f" {xloc.id}[a] = {args[inds[u]].id}[({row_index.id}+{offsets.id}[{l}])*{dim_org}+{k.id}*{dim_chunk}+v];\n" string += " a++;\n" string += "}" string += "}" return string def varseq_to_array(vars, vars_ptr_name): # returns the C++ code corresponding to storing the values of a sequence of variables # into an array. dtype = vars[0].dtype nvars = len(vars) # we check that all variables have the same type if not all(var.dtype == dtype for var in vars[1:]): KeOps_Error("[KeOps] internal error ; incompatible dtypes in varseq_to_array.") string = f""" {dtype} {vars_ptr_name}[{nvars}]; """ for i in range(nvars): string += f""" {vars_ptr_name}[{i}] = {vars[i].id}; """ return string def clean_keops(recompile_jit_binary=True, verbose=True): import keopscore.config.config from keopscore.config.config import get_build_folder build_path = get_build_folder() use_cuda = keopscore.config.config.use_cuda if use_cuda: from keopscore.config.config import jit_binary else: jit_binary = None for f in os.scandir(build_path): if recompile_jit_binary or f.path != jit_binary: os.remove(f.path) if verbose: KeOps_Message(f"{build_path} has been cleaned.") from keopscore.get_keops_dll import get_keops_dll get_keops_dll.reset() if use_cuda and recompile_jit_binary: from keopscore.binders.nvrtc.Gpu_link_compile import Gpu_link_compile Gpu_link_compile.compile_jit_compile_dll()
keops-main
keopscore/keopscore/utils/code_gen_utils.py
import os import pickle import keopscore # global configuration parameter to be added for the lookup : env_param = keopscore.config.config.cpp_flags class Cache: def __init__(self, fun, use_cache_file=False, save_folder="."): self.fun = fun self.library = {} self.use_cache_file = use_cache_file if use_cache_file: self.cache_file = os.path.join(save_folder, fun.__name__ + "_cache.pkl") if os.path.isfile(self.cache_file): f = open(self.cache_file, "rb") self.library = pickle.load(f) f.close() import atexit atexit.register(self.save_cache) def __call__(self, *args): str_id = "".join(list(str(arg) for arg in args)) + str(env_param) if not str_id in self.library: self.library[str_id] = self.fun(*args) return self.library[str_id] def reset(self, new_save_folder=None): self.library = {} if new_save_folder: self.save_folder = new_save_folder def save_cache(self): f = open(self.cache_file, "wb") pickle.dump(self.library, f) f.close() class Cache_partial: """ """ def __init__(self, cls, use_cache_file=False, save_folder="."): self.cls = cls self.library = {} self.use_cache_file = use_cache_file if self.use_cache_file: self.cache_file = os.path.join(save_folder, cls.__name__ + "_cache.pkl") if os.path.isfile(self.cache_file): f = open(self.cache_file, "rb") self.library_params = pickle.load(f) f.close() else: self.library_params = {} import atexit atexit.register(self.save_cache) def __call__(self, *args): str_id = "".join(list(str(arg) for arg in args)) + str(env_param) if not str_id in self.library: if self.use_cache_file: if str_id in self.library_params: params = self.library_params[str_id] self.library[str_id] = self.cls(params, fast_init=True) else: obj = self.cls(*args) self.library_params[str_id] = obj.params self.library[str_id] = obj else: self.library[str_id] = self.cls(*args) return self.library[str_id] def reset(self, new_save_folder=None): self.library = {} if self.use_cache_file: self.library_params = {} if new_save_folder: self.save_folder = new_save_folder def save_cache(self): f = open(self.cache_file, "wb") pickle.dump(self.library_params, f) f.close()
keops-main
keopscore/keopscore/utils/Cache.py
keops-main
keopscore/keopscore/utils/__init__.py
####################################################################### # . Warnings, Errors, etc. ####################################################################### import keopscore def KeOps_Message(message, use_tag=True, **kwargs): if keopscore.verbose: tag = "[KeOps] " if use_tag else "" message = tag + message print(message, **kwargs) def KeOps_Warning(message): if keopscore.verbose: message = "[KeOps] Warning : " + message print(message) def KeOps_Error(message, show_line_number=True): message = "[KeOps] Error : " + message if show_line_number: from inspect import currentframe, getframeinfo frameinfo = getframeinfo(currentframe().f_back) message += f" (error at line {frameinfo.lineno} in file {frameinfo.filename})" raise ValueError(message) def KeOps_OS_Run(command): import sys python_version = sys.version_info if python_version >= (3, 7): import subprocess out = subprocess.run(command, shell=True, capture_output=True) if out.stderr != b"": print(out.stderr.decode("utf-8")) KeOps_Error("Error compiling formula.") elif python_version >= (3, 5): import subprocess subprocess.run( command, shell=True, ) else: import os os.system(command) def find_library_abspath(lib): """ wrapper around ctypes find_library that returns the full path of the library. Warning : it also opens the shared library ! Adapted from https://stackoverflow.com/questions/35682600/get-absolute-path-of-shared-library-in-python/35683698 """ from ctypes import c_int, c_void_p, c_char_p, CDLL, byref, cast, POINTER, Structure from ctypes.util import find_library # linkmap structure, we only need the second entry class LINKMAP(Structure): _fields_ = [("l_addr", c_void_p), ("l_name", c_char_p)] res = find_library(lib) if res is None: return "" lib = CDLL(res) libdl = CDLL(find_library("dl")) dlinfo = libdl.dlinfo dlinfo.argtypes = c_void_p, c_int, c_void_p dlinfo.restype = c_int # gets typecasted later, I dont know how to create a ctypes struct pointer instance lmptr = c_void_p() # 2 equals RTLD_DI_LINKMAP, pass pointer by reference dlinfo(lib._handle, 2, byref(lmptr)) # typecast to a linkmap pointer and retrieve the name. abspath = cast(lmptr, POINTER(LINKMAP)).contents.l_name return abspath.decode("utf-8")
keops-main
keopscore/keopscore/utils/misc_utils.py
from keopscore.utils.code_gen_utils import ( c_for_loop, new_c_varname, c_variable, ) import keopscore.config.config def math_function( cpu_code, gpu_code=None, gpu_half2_code=None, gpu_float_code=None, void=False ): if gpu_code is None: gpu_code = cpu_code if gpu_half2_code is None: gpu_half2_code = gpu_code if gpu_float_code is None: gpu_float_code = gpu_code def convert_to_fun(code): if isinstance(code, str): code_fun = lambda *args: code + "(" + ",".join(arg for arg in args) + ")" else: code_fun = code return code_fun def call(*args): args = list(args) for k, arg in enumerate(args): if isinstance(arg, int): args[k] = c_variable("int", str(arg)) # N.B. first argument gives main dtype dtype = args[0].dtype if dtype == "half2": code_fun = convert_to_fun(gpu_half2_code) elif keopscore.config.config.use_cuda: if dtype == "float": code_fun = convert_to_fun(gpu_float_code) else: code_fun = convert_to_fun(gpu_code) else: code_fun = convert_to_fun(cpu_code) string = code_fun(*(arg.id for arg in args)) if void: return string else: return c_variable(dtype, string) return call keops_mul = math_function(cpu_code=lambda x, y: f"({x}*{y})", gpu_half2_code="__hmul2") keops_abs = math_function(cpu_code="abs", gpu_half2_code="__habs2") keops_cos = math_function(cpu_code="cos", gpu_half2_code="h2cos") keops_sin = math_function(cpu_code="sin", gpu_half2_code="h2sin") keops_sinxdivx = math_function(cpu_code=lambda x: f"({x} ? sin({x})/{x} : 1.0f)") keops_acos = math_function(cpu_code="acos") keops_asin = math_function(cpu_code="asin") keops_atan = math_function(cpu_code="atan") keops_atan2 = math_function(cpu_code="atan2") keops_exp = math_function(cpu_code="exp", gpu_half2_code="h2exp") keops_floor = math_function(cpu_code="floor") keops_log = math_function(cpu_code="log") keops_xlogx = math_function(cpu_code=lambda x: f"({x} ? {x} * log({x}) : 0.0f)") keops_fma = math_function(cpu_code="fma") keops_pow = math_function( cpu_code="pow", gpu_code="powf", gpu_half2_code=lambda x, y: f"h2exp(__float2half2_rn((float){y})*h2log({x}))", ) keops_powf = math_function( cpu_code="powf", gpu_half2_code=lambda x, y: f"h2exp({y}*h2log({x}))" ) keops_rcp = math_function(cpu_code=lambda x: f"(1.0f/({x}))", gpu_half2_code="h2rcp") keops_rsqrt = math_function( cpu_code=lambda x: f"(({x}==0.0f)? 0.0f : 1.0f/sqrt({x}))", gpu_code=lambda x: f"(({x}==0.0f)? 0.0f : rsqrt({x}))", gpu_half2_code=lambda x: f"h2rsqrt({x}+__heq2({x},__float2half2_rn(0.0f))) * (__float2half2_rn(1.0f)-__heq2({x},__float2half2_rn(0.0f)))", ) keops_sqrt = math_function(cpu_code="sqrt", gpu_half2_code="h2sqrt") keops_relu = math_function(cpu_code=lambda x: f"(({x}<0.0f)? 0.0f : {x})") keops_step = math_function(cpu_code=lambda x: f"(({x}<0.0f)? 0.0f : 1.0f)") keops_sign = math_function( cpu_code=lambda x: f"(({x}>0.0f)? 1.0f : ( ({x}<0.0f)? -1.0f : 0.0f ))" ) keops_clamp = math_function( cpu_code=lambda x, a, b: f"(({x}<{a})? {a} : ( ({x}>{b})? {b} : {x} ))" ) keops_clampint = math_function( cpu_code=lambda x, a, b: f"(({x}<{a})? {a} : ( ({x}>{b})? {b} : {x} ))" ) keops_mod = math_function( cpu_code=lambda x, n, d: f"({x} - {n} * floor(({x} - {d})/{n}))" ) keops_round = math_function( cpu_code=lambda x, d: f"round({x})" if eval(d) == 0 else f"(round({x}*{10**eval(d)})/{10**eval(d)})" ) keops_diffclampint = math_function( cpu_code=lambda x, a, b: f"(({x}<{a})? 0.0f : ( ({x}>{b})? 0.0f : 1.0f ))" ) keops_ifelse = math_function(cpu_code=lambda x, a, b: f"(({x}>=0.0f) ? {a} : {b})") keops_sincos = math_function( cpu_code=lambda x, s, c: f"*{s}=sin(x); *{c}=cos(x);", void=True )
keops-main
keopscore/keopscore/utils/math_functions.py
import ctypes from ctypes.util import find_library import keopscore.config.config from keopscore.utils.misc_utils import ( KeOps_Error, KeOps_Warning, find_library_abspath, KeOps_OS_Run, ) from keopscore.config.config import cxx_compiler, get_build_folder import os from os.path import join # Some constants taken from cuda.h CUDA_SUCCESS = 0 CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK = 1 CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK = 8 libcuda_folder = os.path.dirname(find_library_abspath("cuda")) libnvrtc_folder = os.path.dirname(find_library_abspath("nvrtc")) def get_cuda_include_path(): # auto detect location of cuda headers # First we look at CUDA_PATH env variable if it is set path = os.getenv("CUDA_PATH") if path: path = join(path, "include") if os.path.isfile(join(path, "cuda.h")) and os.path.isfile( join(path, "nvrtc.h") ): return path # if not successfull, we try a few standard locations: cuda_version = get_cuda_version(out_type="string") cuda_paths_to_try_start = [ join(os.path.sep, "opt", "cuda"), join(os.path.sep, "usr", "local", "cuda"), join(os.path.sep, "usr", "local", f"cuda-{cuda_version}"), ] cuda_paths_to_try_end = [ "include", join("targets", "x86_64-linux", "include"), ] for path_start in cuda_paths_to_try_start: for path_end in cuda_paths_to_try_end: path = join(path_start, path_end) if os.path.isfile(join(path, "cuda.h")) and os.path.isfile( join(path, "nvrtc.h") ): return path # if not successfull, we try to infer location from the libs cuda_include_path = None for libpath in libcuda_folder, libnvrtc_folder: for libtag in "lib", "lib64": libtag = os.path.sep + libtag + os.path.sep if libtag in libpath: includetag = os.path.sep + "include" + os.path.sep includepath = libpath.replace(libtag, includetag) if os.path.isfile(join(includepath, "cuda.h")) and os.path.isfile( join(includepath, "nvrtc.h") ): return includepath # last try, testing if by any chance the header is already in the default # include path of gcc path_cudah = get_include_file_abspath("cuda.h") if path_cudah: path = os.path.dirname(path_cudah) if os.path.isfile(join(path, "nvrtc.h")): return path # finally nothing found, so we display a warning asking the user to do something KeOps_Warning( """ The location of Cuda header files cuda.h and nvrtc.h could not be detected on your system. You must determine their location and then define the environment variable CUDA_PATH, either before launching Python or using os.environ before importing keops. For example if these files are in /vol/cuda/10.2.89-cudnn7.6.4.38/include you can do : import os os.environ['CUDA_PATH'] = '/vol/cuda/10.2.89-cudnn7.6.4.38' """ ) def get_include_file_abspath(filename): tmp_file = join(get_build_folder(), "tmp.txt") KeOps_OS_Run( f'echo "#include <{filename}>" | {cxx_compiler} -M -E -x c++ - | head -n 2 > {tmp_file}' ) strings = open(tmp_file).read().split() abspath = None for s in strings: if filename in s: abspath = s os.remove(tmp_file) return abspath def cuda_include_fp16_path(): """ We look for float 16 cuda headers cuda_fp16.h and cuda_fp16.hpp based on cuda_path locations and return their directory """ from keopscore.config.config import cuda_include_path if cuda_include_path: return cuda_include_path cuda_fp16_h_abspath = get_include_file_abspath("cuda_fp16.h") cuda_fp16_hpp_abspath = get_include_file_abspath("cuda_fp16.hpp") if cuda_fp16_h_abspath and cuda_fp16_hpp_abspath: path = os.path.dirname(cuda_fp16_h_abspath) if path != os.path.dirname(cuda_fp16_hpp_abspath): KeOps_Error("cuda_fp16.h and cuda_fp16.hpp are not in the same folder !") return path else: KeOps_Error("cuda_fp16.h and cuda_fp16.hpp were not found") def get_cuda_version(out_type="single_value"): cuda = ctypes.CDLL(find_library("cudart")) cuda_version = ctypes.c_int() cuda.cudaRuntimeGetVersion(ctypes.byref(cuda_version)) cuda_version = int(cuda_version.value) if out_type == "single_value": return cuda_version cuda_version_major = cuda_version // 1000 cuda_version_minor = (cuda_version - (1000 * cuda_version_major)) // 10 if out_type == "major,minor": return cuda_version_major, cuda_version_minor elif out_type == "string": return f"{cuda_version_major}.{cuda_version_minor}" def get_gpu_props(): """ Return number of GPU by reading libcuda. Here we assume the system has cuda support (more precisely that libcuda can be loaded) Adapted from https://gist.github.com/f0k/0d6431e3faa60bffc788f8b4daa029b1 credit: Jan Schlüter """ cuda = ctypes.CDLL(find_library("cuda")) nGpus = ctypes.c_int() error_str = ctypes.c_char_p() result = cuda.cuInit(0) if result != CUDA_SUCCESS: # cuda.cuGetErrorString(result, ctypes.byref(error_str)) # KeOps_Warning("cuInit failed with error code %d: %s" % (result, error_str.value.decode())) KeOps_Warning( "cuda was detected, but driver API could not be initialized. Switching to cpu only." ) return 0, "" result = cuda.cuDeviceGetCount(ctypes.byref(nGpus)) if result != CUDA_SUCCESS: # cuda.cuGetErrorString(result, ctypes.byref(error_str)) # KeOps_Warning("cuDeviceGetCount failed with error code %d: %s" % (result, error_str.value.decode())) KeOps_Warning( "cuda was detected, driver API has been initialized, but no working GPU has been found. Switching to cpu only." ) return 0, "" nGpus = nGpus.value def safe_call(d, result): test = result == CUDA_SUCCESS if not test: KeOps_Warning( f""" cuda was detected, driver API has been initialized, but there was an error for detecting properties of GPU device nr {d}. Switching to cpu only. """ ) return test test = True MaxThreadsPerBlock = [0] * (nGpus) SharedMemPerBlock = [0] * (nGpus) for d in range(nGpus): # getting handle to cuda device device = ctypes.c_int() result &= safe_call(d, cuda.cuDeviceGet(ctypes.byref(device), ctypes.c_int(d))) # getting MaxThreadsPerBlock info for device output = ctypes.c_int() result &= safe_call( d, cuda.cuDeviceGetAttribute( ctypes.byref(output), ctypes.c_int(CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK), device, ), ) MaxThreadsPerBlock[d] = output.value # getting SharedMemPerBlock info for device result &= safe_call( d, cuda.cuDeviceGetAttribute( ctypes.byref(output), ctypes.c_int(CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK), device, ), ) SharedMemPerBlock[d] = output.value # Building compile flags in the form "-D..." options for further compilations # (N.B. the purpose is to avoid the device query at runtime because it would slow down computations) string_flags = f"-DMAXIDGPU={nGpus-1} " for d in range(nGpus): string_flags += f"-DMAXTHREADSPERBLOCK{d}={MaxThreadsPerBlock[d]} " string_flags += f"-DSHAREDMEMPERBLOCK{d}={SharedMemPerBlock[d]} " if test: return nGpus, string_flags else: return 0, 0, ""
keops-main
keopscore/keopscore/utils/gpu_utils.py
# Test for gaussian kernel operation using LazyTensors. import time import math import torch from pykeops.torch import Genred M, N, = ( 5, 5, ) dtype = torch.float16 device_id = "cuda:0" if torch.cuda.is_available() else "cpu" x = torch.zeros(M, 1, device=device_id, dtype=dtype) b = torch.ones(N, 1, device=device_id, dtype=dtype) y = torch.zeros(N, 1, device=device_id, dtype=dtype) y[0] = 1 z = -5 * torch.ones(N, 1, device=device_id, dtype=dtype) aliases = ["x=Vi(0,1)", "b=Vj(1,1)", "y=Vj(2,1)", "z=Vj(3,1)"] formula = "SumT(y,1)" fun = Genred(formula, aliases, reduction_op="Sum", axis=1, sum_scheme="block_sum") for k in range(1): start = time.time() out = fun(x, b, y, z) end = time.time() print("time for genred:", end - start)
keops-main
keopscore/keopscore/sandbox/genred_float16.py
from keopscore.formulas import * f = Grad_WithSavedForward( Sum_Reduction(Sum((Var(0, 1, 0) - Var(1, 1, 1))), 1), Var(0, 1, 0), Var(2, 1, 1), Var(3, 1, 1), ) print(f)
keops-main
keopscore/keopscore/sandbox/formula.py
# Testing simplification rules of formulas from keopscore.formulas import * x = Var(0, 3, 0) y = Var(1, 3, 1) f = 3 * (x - y) ** 2 - 2 * (x - y) ** 2 * 2 print() print("f =", f) print()
keops-main
keopscore/keopscore/sandbox/simplification_rules.py
""" ========= TensorDot ========= This is a test script to showcase the tensordot syntax. """ import numpy as np import torch from pykeops.torch import LazyTensor M, N = 2, 10 ####################################################################################################################### # Matrix multiplication as a special case of Tensordot # ---------------------------------------------------- # device_id = "cuda:0" if torch.cuda.is_available() else "cpu" do_warmup = True a = torch.randn(4 * 7, requires_grad=True, device=device_id, dtype=torch.float64) b = torch.randn(7, requires_grad=True, device=device_id, dtype=torch.float64) c = a.reshape(4, 7) @ b ####################################################################################################################### # A single matrix multiplication # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ # # In this case no need to use KeOps: this is a sanity check. A = LazyTensor(a[None, None, :]) B = LazyTensor(b[None, None, :]) C = A.keops_tensordot(B, (4, 7), (7,), (1,), (0,)).sum_reduction(dim=1) # print(C, c) print( "Compare the two MatVecMul implementations. All good?", torch.allclose(c.flatten(), C.flatten()), )
keops-main
keopscore/keopscore/sandbox/lazytensor_tensordot.py
# Test for gaussian kernel operation using LazyTensors. import time import math import torch from pykeops.torch import LazyTensor M, N, D, DV = 2000, 4000, 3, 1 dtype = torch.float32 sum_scheme = "block_sum" device_id = "cuda:0" if torch.cuda.is_available() else "cpu" x = torch.rand(3, M, 1, D, device=device_id, dtype=dtype) / math.sqrt(D) y = torch.rand(1, 1, N, D, device=device_id, dtype=dtype) / math.sqrt(D) b = torch.randn(1, N, DV, device=device_id, dtype=dtype) def fun(x, y, b, backend): if "keops" in backend: x = LazyTensor(x) y = LazyTensor(y) Dxy = ((x * y).square()).sum(dim=3) Kxy = (-Dxy).exp() if "keops" in backend: out = Kxy.__matmul__(b, sum_scheme=sum_scheme) else: out = Kxy @ b if device_id != "cpu": torch.cuda.synchronize() # print("out:",out.flatten()[:10]) return out backends = ["keops", "torch"] out = [] for backend in backends: start = time.time() out.append(fun(x, y, b, backend).squeeze()) end = time.time() print("time for " + backend + ":", end - start) if len(out) > 1: print("relative error:", (torch.norm(out[0] - out[1]) / torch.norm(out[0])).item())
keops-main
keopscore/keopscore/sandbox/lazytensor_gaussian_batchdims.py
# Test for gaussian kernel operation using LazyTensors. import torch from pykeops.torch import LazyTensor B1, B2, B3 = 2, 3, 4 D = 3 M, N = 2000, 3000 device_id = "cuda:0" if torch.cuda.is_available() else "cpu" dtype = torch.float32 x = torch.rand(B1, 1, B3, M, 1, D, dtype=dtype, device=device_id) y = torch.rand(1, B2, 1, 1, N, D, dtype=dtype, device=device_id) p = 1 + torch.arange(B2 * B3, dtype=dtype, device=device_id).reshape(1, B2, B3, 1, 1) def fun(x, y, p, backend): if backend == "keops": x = LazyTensor(x) y = LazyTensor(y) p = LazyTensor(p.reshape(p.shape + (1,))) elif backend != "torch": raise ValueError("wrong backend") out = ((x - y).sum(dim=5) / p).exp().sum(dim=4) # print("out", backend, ":") # print(out) return out backends = ["torch", "keops"] out = [] for backend in backends: out.append(fun(x, y, p, backend).squeeze()) if len(out) > 1: print("relative error:", (torch.norm(out[0] - out[1]) / torch.norm(out[0])).item())
keops-main
keopscore/keopscore/sandbox/lazytensor_gaussian_batch.py
import sys from keopscore.utils.TestOperation import TestOperation if __name__ == "__main__": if len(sys.argv) == 1: print( "you should provide an operation to test, e.g. 'python do_test_op.py Exp'" ) else: if len(sys.argv) == 2: res = TestOperation(sys.argv[1]) elif len(sys.argv) == 3: res = TestOperation(sys.argv[1], dtype=sys.argv[2]) else: res = TestOperation( sys.argv[1], dtype=sys.argv[2], test_grad=eval(sys.argv[3]) )
keops-main
keopscore/keopscore/sandbox/do_test_op.py
# Test for gaussian kernel operation using LazyTensors. import time import math import torch from pykeops.torch import LazyTensor M, N, D, DV = 2000, 1000, 3, 1 dtype = torch.float32 sum_scheme = "block_sum" device_id = "cuda:0" if torch.cuda.is_available() else "cpu" do_warmup = True x = torch.rand(M, 1, D, device=device_id, dtype=dtype) / math.sqrt(D) y = torch.rand(1, N, D, device=device_id, dtype=dtype) / math.sqrt(D) b = torch.randn(N, DV, device=device_id, dtype=dtype) eta = torch.randn(1, N, D, device=device_id, dtype=dtype) def fun(x, y, b, eta, backend): if "keops" in backend: x = LazyTensor(x) y = LazyTensor(y) eta = LazyTensor(eta) Dxy = (x.atan2(y) * (x * (y * eta)).square()).sum(dim=2) Kxy = (-Dxy).exp() if "keops" in backend: out = Kxy.__matmul__(b, sum_scheme=sum_scheme) else: out = Kxy @ b if device_id != "cpu": torch.cuda.synchronize() # print("out:",out.flatten()[:10]) return out backends = ["keops", "torch"] out = [] for backend in backends: if do_warmup: fun( x[: min(M, 100), :, :], y[:, : min(N, 100), :], b[: min(N, 100), :], eta[:, : min(N, 100), :], backend, ) fun( x[: min(M, 100), :, :], y[:, : min(N, 100), :], b[: min(N, 100), :], eta[:, : min(N, 100), :], backend, ) start = time.time() out.append(fun(x, y, b, eta, backend).squeeze()) end = time.time() print("time for " + backend + ":", end - start) if len(out) > 1: print("relative error:", (torch.norm(out[0] - out[1]) / torch.norm(out[0])).item())
keops-main
keopscore/keopscore/sandbox/lazytensor_sandbox.py
# Test for gaussian kernel operation using LazyTensors. import time import math import torch import numpy as np from pykeops.numpy import LazyTensor M, N, D, DV = 3000, 2000, 3, 1 dtype = np.float32 do_warmup = False x = np.random.rand(M, 1, D).astype(dtype) / math.sqrt(D) y = np.random.rand(1, N, D).astype(dtype) / math.sqrt(D) b = np.random.randn(N, DV).astype(dtype) def fun(x, y, b, backend): if "keops" in backend: x = LazyTensor(x) y = LazyTensor(y) Dxy = ((x - y)).sum(axis=2) if backend == "keops": Kxy = (-Dxy).exp() else: Kxy = np.exp(-Dxy) out = Kxy @ b # print("out:",out.flatten()) return out backends = ["keops", "numpy"] out = [] for backend in backends: if do_warmup: fun( x[: min(M, 100), :, :], y[:, : min(N, 100), :], b[: min(N, 100), :], backend ) fun( x[: min(M, 100), :, :], y[:, : min(N, 100), :], b[: min(N, 100), :], backend ) start = time.time() out.append(fun(x, y, b, backend).squeeze()) end = time.time() print("time for " + backend + ":", end - start) if len(out) > 1: print("relative error:", (np.linalg.norm(out[0] - out[1]) / np.linalg.norm(out[0])))
keops-main
keopscore/keopscore/sandbox/lazytensor_gaussian_numpy.py
# Test for gaussian kernel operation using LazyTensors. import time import math import torch from pykeops.torch import LazyTensor M, N, D, DV = 1000, 1000, 3, 1 dtype = torch.float32 test_grad = True test_grad2 = False device_id = "cuda:0" if torch.cuda.is_available() else "cpu" x = torch.rand(M, 1, D, requires_grad=test_grad, device=device_id, dtype=dtype) y = torch.rand(1, N, 1, device=device_id, dtype=dtype) b = torch.randn(N, DV, device=device_id, dtype=dtype) def fun(x, y, b, backend): if "keops" in backend: x = LazyTensor(x) y = LazyTensor(y) # Kxy = ((x - 0.5).mod(1, 0.2) - y).sum(dim=2) Kxy = (x.cos() - y).sum(dim=2) out = Kxy @ b if device_id != "cpu": torch.cuda.synchronize() # print("out:",out.flatten()[:10]) return out backends = ["keops", "torch"] # "keops_old" out = [] for backend in backends: start = time.time() out.append(fun(x, y, b, backend).squeeze()) end = time.time() print("time for " + backend + ":", end - start) if len(out) > 1: print("relative error:", (torch.norm(out[0] - out[1]) / torch.norm(out[0])).item()) if test_grad: out_g = [] for k, backend in enumerate(backends): start = time.time() out_g.append( torch.autograd.grad((out[k] ** 2).sum(), [x], create_graph=True)[0] ) end = time.time() print("time for " + backend + " (grad):", end - start) if len(out_g) > 1: print( "relative error grad:", (torch.norm(out_g[0] - out_g[1]) / torch.norm(out_g[0])).item(), ) # print( # "absolute error grad:", # (torch.norm(out_g[0] - out_g[1])).item(), # ) if test_grad2: out_g2 = [] for k, backend in enumerate(backends): start = time.time() out_g2.append(torch.autograd.grad((out_g[k] ** 2).sum(), [x])[0]) end = time.time() print("time for " + backend + " (grad):", end - start) if len(out_g2) > 1: print( "relative error grad:", (torch.norm(out_g2[0] - out_g2[1]) / torch.norm(out_g2[0])).item(), ) if len(out_g) > 1: print( "relative error grad:", (torch.norm(out_g[0] - out_g[1]) / torch.norm(out_g[0])).item(), )
keops-main
keopscore/keopscore/sandbox/lazytensor_grad.py
# Test for gaussian kernel operation using LazyTensors. import time import math import torch from pykeops.torch import LazyTensor B1, B2, M, N, D, DV = 2, 3, 200, 300, 300, 1 dtype = torch.float32 sum_scheme = "block_sum" import pykeops pykeops.config.gpu_available = 0 device_id = "cuda:0" if pykeops.config.gpu_available else "cpu" do_warmup = False x = torch.rand(B1, B2, M, 1, D, device=device_id, dtype=dtype) / math.sqrt(D) y = torch.rand(B1, 1, 1, N, D, device=device_id, dtype=dtype) / math.sqrt(D) b = torch.randn(1, B2, N, DV, device=device_id, dtype=dtype) def fun(x, y, b, backend): if "keops" in backend: x = LazyTensor(x) y = LazyTensor(y) Dxy = ((x - y).square()).sum(dim=4) Kxy = (-Dxy).exp() if "keops" in backend: out = Kxy.__matmul__(b, sum_scheme=sum_scheme) else: out = Kxy @ b if device_id != "cpu": torch.cuda.synchronize() # print("out:",out) return out backends = ["keops", "torch"] out = [] for backend in backends: if do_warmup: fun( x[:, :, : min(M, 100), :, :], y[:, :, :, : min(N, 100), :], b[:, :, : min(N, 100), :], backend, ) fun( x[:, :, : min(M, 100), :, :], y[:, :, :, : min(N, 100), :], b[:, :, : min(N, 100), :], backend, ) start = time.time() out.append(fun(x, y, b, backend).squeeze()) end = time.time() print("time for " + backend + ":", end - start) if len(out) > 1: print("relative error:", (torch.norm(out[0] - out[1]) / torch.norm(out[0])).item()) print(out[0]) print(out[1])
keops-main
keopscore/keopscore/sandbox/chunks_ranges.py
# Test for gaussian kernel operation using LazyTensors. import time import math import torch from pykeops.torch import LazyTensor B1, B2, M, N, D, DV = 2, 3, 200, 300, 3, 300 dtype = torch.float32 sum_scheme = "block_sum" device_id = "cuda:0" if torch.cuda.is_available() else "cpu" do_warmup = False x = torch.rand(B1, B2, M, 1, D, device=device_id, dtype=dtype) / math.sqrt(D) y = torch.rand(B1, 1, 1, N, D, device=device_id, dtype=dtype) / math.sqrt(D) b = torch.randn(1, B2, N, DV, device=device_id, dtype=dtype) def fun(x, y, b, backend): if "keops" in backend: x = LazyTensor(x) y = LazyTensor(y) Dxy = ((x - y).square()).sum(dim=4) Kxy = (-Dxy).exp() if "keops" in backend: out = Kxy.__matmul__(b, sum_scheme=sum_scheme) else: out = Kxy @ b if device_id != "cpu": torch.cuda.synchronize() # print("out:",out[:,:10]) return out backends = ["keops", "torch"] out = [] for backend in backends: if do_warmup: fun( x[:, :, : min(M, 100), :, :], y[:, :, :, : min(N, 100), :], b[:, :, : min(N, 100), :], backend, ) fun( x[:, :, : min(M, 100), :, :], y[:, :, :, : min(N, 100), :], b[:, :, : min(N, 100), :], backend, ) start = time.time() out.append(fun(x, y, b, backend).squeeze()) end = time.time() print("time for " + backend + ":", end - start) if len(out) > 1: print("relative error:", (torch.norm(out[0] - out[1]) / torch.norm(out[0])).item())
keops-main
keopscore/keopscore/sandbox/finalchunks_ranges.py
# Test for gaussian kernel operation using LazyTensors. import time import math import torch from pykeops.torch import LazyTensor M, N, D, DV = 2000, 3000, 3, 1 dtype = torch.float32 test_grad = False test_grad2 = False device_id = "cuda:0" if torch.cuda.is_available() else "cpu" do_warmup = False x = torch.rand(M, 1, D, device=device_id, dtype=dtype) / math.sqrt(D) y = torch.rand(1, N, D, device=device_id, dtype=dtype) / math.sqrt(D) b = torch.randn(N, DV, requires_grad=test_grad, device=device_id, dtype=dtype) def fun(x, y, b, backend): if "keops" in backend: x = LazyTensor(x) y = LazyTensor(y) Dxy = ((x - y) ** 2).sum(dim=2) Kxy = (-Dxy).exp() if backend == "keops2D": out = LazyTensor.__matmul__(Kxy, b, backend="GPU_2D") else: out = Kxy @ b if device_id != "cpu": torch.cuda.synchronize() # print("out:",out) return out backends = ["keops2D", "torch"] out = [] for backend in backends: if do_warmup: fun( x[: min(M, 100), :, :], y[:, : min(N, 100), :], b[: min(N, 100), :], backend ) fun( x[: min(M, 100), :, :], y[:, : min(N, 100), :], b[: min(N, 100), :], backend ) start = time.time() out.append(fun(x, y, b, backend).squeeze()) end = time.time() print("time for " + backend + ":", end - start) if len(out) > 1: print("relative error:", (torch.norm(out[0] - out[1]) / torch.norm(out[0])).item()) if test_grad: out_g = [] for k, backend in enumerate(backends): start = time.time() out_g.append( torch.autograd.grad((out[k] ** 2).sum(), [b], create_graph=True)[0] ) end = time.time() print("time for " + backend + " (grad):", end - start) if len(out_g) > 1: print( "relative error grad:", (torch.norm(out_g[0] - out_g[1]) / torch.norm(out_g[0])).item(), ) if test_grad2: out_g2 = [] for k, backend in enumerate(backends): start = time.time() out_g2.append(torch.autograd.grad((out_g[k] ** 2).sum(), [b])[0]) end = time.time() print("time for " + backend + " (grad):", end - start) if len(out_g2) > 1: print( "relative error grad:", (torch.norm(out_g2[0] - out_g2[1]) / torch.norm(out_g2[0])).item(), ) if len(out_g) > 1: print( "relative error grad:", (torch.norm(out_g[0] - out_g[1]) / torch.norm(out_g[0])).item(), )
keops-main
keopscore/keopscore/sandbox/Conv2D.py
# Test for gaussian kernel operation using LazyTensors. import time import math import torch from pykeops.torch import LazyTensor M, N, D, DV = 20, 30, 3, 1 dtype = torch.float32 sum_scheme = "block_sum" device_id = "cuda:0" if torch.cuda.is_available() else "cpu" do_warmup = True x = torch.rand(M, 1, D, device=device_id, dtype=dtype) / math.sqrt(D) y = torch.rand(1, N, D, device=device_id, dtype=dtype) / math.sqrt(D) b = torch.randn(N, DV, device=device_id, dtype=dtype) a = torch.empty(M, DV, device=device_id, dtype=dtype) def fun(x, y, b, backend, out=None): if "keops" in backend: x = LazyTensor(x) y = LazyTensor(y) Dxy = ((x - y).square()).sum(dim=2) Kxy = (-Dxy).exp() if "keops" in backend: Kxy.__matmul__(b, sum_scheme=sum_scheme, out=out) else: out = Kxy @ b if device_id != "cpu": torch.cuda.synchronize() # print("out:",out) return out backends = ["keops", "torch"] out = [] for backend in backends: if do_warmup: fun( x[: min(M, 100), :, :], y[:, : min(N, 100), :], b[: min(N, 100), :], backend ) fun( x[: min(M, 100), :, :], y[:, : min(N, 100), :], b[: min(N, 100), :], backend ) start = time.time() out.append(fun(x, y, b, backend, out=a).squeeze()) end = time.time() print("time for " + backend + ":", end - start) if len(out) > 1: print("relative error:", (torch.norm(out[0] - out[1]) / torch.norm(out[0])).item())
keops-main
keopscore/keopscore/sandbox/lazytensor_gaussian_inplace.py
# Test for gaussian kernel operation using LazyTensors. import time import math import torch from pykeops.torch import Genred M, N, D, DV = 20, 30, 3, 1 dtype = torch.float64 device_id = "cuda:0" if torch.cuda.is_available() else "cpu" do_warmup = False x = torch.rand(M, D, device=device_id, dtype=dtype) / math.sqrt(D) y = torch.rand(N, D, device=device_id, dtype=dtype) / math.sqrt(D) b = torch.randn(N, DV, device=device_id, dtype=dtype) out = torch.empty(M, DV, device=device_id, dtype=dtype) aliases = [f"x=Vi(0,{D})", f"y=Vj(1,{D})", f"b=Vj(2,{DV})"] formula = "Exp(-Sum(Square(x-y)))*b" fun = Genred(formula, aliases, reduction_op="Sum", axis=1, sum_scheme="block_sum") if do_warmup: fun(x[: min(M, 100), :], y[: min(N, 100), :], b[: min(N, 100), :]) fun(x[: min(M, 100), :], y[: min(N, 100), :], b[: min(N, 100), :]) for k in range(10): start = time.time() fun(x, y, b, out=out) end = time.time() print("time for genred:", end - start)
keops-main
keopscore/keopscore/sandbox/genred_inplace.py
# Test for gaussian kernel operation using LazyTensors. import time import math import torch from pykeops.torch import LazyTensor M, N, D, DV = 200, 300, 3, 300 dtype = torch.float32 sum_scheme = "block_sum" device_id = "cuda:0" if torch.cuda.is_available() else "cpu" do_warmup = True x = torch.rand(M, 1, D, device=device_id, dtype=dtype) / math.sqrt(D) y = torch.rand(1, N, D, device=device_id, dtype=dtype) / math.sqrt(D) b = torch.randn(N, DV, device=device_id, dtype=dtype) def fun(x, y, b, backend): if "keops" in backend: x = LazyTensor(x) y = LazyTensor(y) Dxy = ((x - y).square()).sum(dim=2) Kxy = (-Dxy).exp() if "keops" in backend: out = Kxy.__matmul__(b, sum_scheme=sum_scheme) else: out = Kxy @ b if device_id != "cpu": torch.cuda.synchronize() # print("out:",out[:,:10]) return out backends = ["keops", "torch"] out = [] for backend in backends: if do_warmup: fun( x[: min(M, 100), :, :], y[:, : min(N, 100), :], b[: min(N, 100), :], backend ) fun( x[: min(M, 100), :, :], y[:, : min(N, 100), :], b[: min(N, 100), :], backend ) fun( x[: min(M, 100), :, :], y[:, : min(N, 100), :], b[: min(N, 100), :], backend ) start = time.time() out.append(fun(x, y, b, backend).squeeze()) end = time.time() print("time for " + backend + ":", end - start) if len(out) > 1: print("relative error:", (torch.norm(out[0] - out[1]) / torch.norm(out[0])).item())
keops-main
keopscore/keopscore/sandbox/finalchunks.py
# Test for gaussian kernel operation using LazyTensors. import time import math import torch from pykeops.torch import LazyTensor M, N, D, DV = 20, 30, 3, 1 dtype = torch.float32 sum_scheme = "block_sum" import pykeops pykeops.config.gpu_available = 0 device_id = "cuda:0" if pykeops.config.gpu_available else "cpu" do_warmup = True x = torch.rand(M, 1, D, device=device_id, dtype=dtype) / math.sqrt(D) y = torch.rand(1, N, D, device=device_id, dtype=dtype) / math.sqrt(D) b = torch.randn(N, DV, device=device_id, dtype=dtype) def fun(x, y, b, backend): if "keops" in backend: x = LazyTensor(x) y = LazyTensor(y) Dxy = ((x - y).square()).sum(dim=2) Kxy = (-Dxy).exp() if "keops" in backend: out = Kxy.__matmul__(b, sum_scheme=sum_scheme) else: out = Kxy @ b if device_id != "cpu": torch.cuda.synchronize() # print("out:",out) return out backends = ["keops", "torch"] out = [] for backend in backends: if do_warmup: fun( x[: min(M, 100), :, :], y[:, : min(N, 100), :], b[: min(N, 100), :], backend ) fun( x[: min(M, 100), :, :], y[:, : min(N, 100), :], b[: min(N, 100), :], backend ) start = time.time() out.append(fun(x, y, b, backend).squeeze()) end = time.time() print("time for " + backend + ":", end - start) if len(out) > 1: print("relative error:", (torch.norm(out[0] - out[1]) / torch.norm(out[0])).item())
keops-main
keopscore/keopscore/sandbox/lazytensor_gaussian.py
# Test for gaussian kernel operation using LazyTensors. import time import math import torch from pykeops.torch import Genred M, N, D, DV = 20, 30, 3, 1 dtype = torch.float64 device_id = "cuda:0" if torch.cuda.is_available() else "cpu" do_warmup = False x = torch.rand(M, D, device=device_id, dtype=dtype) / math.sqrt(D) y = torch.rand(N, D, device=device_id, dtype=dtype) / math.sqrt(D) b = torch.randn(N, DV, device=device_id, dtype=dtype) aliases = [f"x=Vi(0,{D})", f"y=Vj(1,{D})", f"b=Vj(2,{DV})"] formula = "Exp(-Sum(Square(x-y)))*b" fun = Genred(formula, aliases, reduction_op="Sum", axis=1, sum_scheme="block_sum") if do_warmup: fun(x[: min(M, 100), :], y[: min(N, 100), :], b[: min(N, 100), :]) fun(x[: min(M, 100), :], y[: min(N, 100), :], b[: min(N, 100), :]) for k in range(10): start = time.time() fun(x, y, b) end = time.time() print("time for genred:", end - start)
keops-main
keopscore/keopscore/sandbox/genred_gaussian.py
from keopscore.utils.code_gen_utils import clean_keops clean_keops()
keops-main
keopscore/keopscore/sandbox/do_clean_keops.py
# Non-Uniform Discrete Fourier Tranform example import time import math import torch from pykeops.torch import LazyTensor dtype = torch.float32 dtype_c = torch.complex64 M, N, D = 500, 300, 1 test_grad = False device_id = "cuda" if torch.cuda.is_available() else "cpu" x = torch.rand(1, N, D, dtype=dtype_c, requires_grad=test_grad, device=device_id) p = torch.rand(1, N, D, dtype=dtype, device=device_id) f = torch.rand(M, 1, D, dtype=dtype, device=device_id) def view_as_real(x): if torch.is_complex(x): return torch.view_as_real(x) else: return x def fun(x, p, f, backend): if "keops" in backend: x = LazyTensor(x) p = LazyTensor(p) f = LazyTensor(f) X = ((-2 * math.pi * 1j) * p * f) * x return X.sum(dim=0) backends = ["keops", "torch"] out = [] for backend in backends: start = time.time() out.append(fun(x, p, f, backend).squeeze()) end = time.time() print("time for " + backend + ":", end - start) if len(out) > 1: print( "relative error:", ( torch.norm(view_as_real(out[0] - out[1]).cpu()) / torch.norm(view_as_real(out[0]).cpu()) ).item(), ) if test_grad: out_g = [] for k, backend in enumerate(backends): start = time.time() if out[k].is_complex(): out_g.append( torch.autograd.grad((out[k].real ** 2 + out[k].imag ** 2).sum(), [x])[0] ) else: out_g.append(torch.autograd.grad((out[k] ** 2).sum(), [x])[0]) end = time.time() print("time for " + backend + " (grad):", end - start) if len(out_g) > 1: print( "relative error grad:", ( torch.norm(view_as_real(out_g[0] - out_g[1]).cpu()) / torch.norm(view_as_real(out_g[0]).cpu()) ).item(), )
keops-main
keopscore/keopscore/sandbox/complex.py
# Test for gaussian kernel operation using LazyTensors. import time import math import torch from pykeops.torch import LazyTensor M, N, D, DV = 2500, 2000, 3, 1 # M, N, D, DV = 2, 3, 3, 1 dtype = torch.float64 sum_scheme = "block_sum" device_id = 0 if torch.cuda.is_available() else -1 do_warmup = True x = torch.rand(M, 1, D, dtype=dtype) / math.sqrt(D) y = torch.rand(1, N, D, dtype=dtype) / math.sqrt(D) b = torch.randn(N, DV, dtype=dtype) def fun(x, y, b, backend): if "keops" in backend: x = LazyTensor(x) y = LazyTensor(y) Dxy = ((x - y).square()).sum(dim=2) Kxy = (-Dxy).exp() if "keops" in backend: out = Kxy.__matmul__(b, sum_scheme=sum_scheme, device_id=device_id) else: out = Kxy @ b # print("out:",out) return out backends = ["keops", "torch"] out = [] for backend in backends: if do_warmup: fun( x[: min(M, 100), :, :], y[:, : min(N, 100), :], b[: min(N, 100), :], backend ) fun( x[: min(M, 100), :, :], y[:, : min(N, 100), :], b[: min(N, 100), :], backend ) start = time.time() out.append(fun(x, y, b, backend).squeeze()) end = time.time() print("time for " + backend + ":", end - start) if len(out) > 1: print("relative error:", (torch.norm(out[0] - out[1]) / torch.norm(out[0])).item())
keops-main
keopscore/keopscore/sandbox/lazytensor_gaussian_fromhost.py