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 fro...
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 = torc...
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 ...
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() # ...
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 = tor...
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 = ...
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(...
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...
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(1000...
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_gr...
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, dt...
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,...
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,...
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.sqr...
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...
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) ker...
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) ...
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]) ...
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`. """ ##########################...
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 # ----...
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**: # # ...
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 e...
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 ...
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...
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 # ---------- # # ...
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 ...
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.pypl...
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) \rig...
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...
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 ...
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 LazyTe...
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 # ---------------- # # Sta...
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 s...
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 ...
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...
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`. """ ##########################...
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 entri...
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 :m...
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 # -----------------...
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 i...
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...
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}\Bi...
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 ...
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() ##########...
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/p...
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**...
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. """ #################################################################### #...
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...
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 **la...
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 us...
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...
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/gauss...
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 ...
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 u...
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 ...
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 mach...
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 multiplica...
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:: ...
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:: ...
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 i...
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 imple...
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().r...
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...
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__ =...
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 = T...
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 = 1...
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_...
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 = eva...
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 = i...
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 ] #####################...
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_cach...
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 "" ...
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: ...
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 cons...
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, devic...
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 multiplic...
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, ...
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...
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]) ...
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, devi...
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...
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_g...
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...
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.ran...
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(...
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=d...
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.s...
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, devi...
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 "c...
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.s...
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, requi...
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.r...
keops-main
keopscore/keopscore/sandbox/lazytensor_gaussian_fromhost.py