python_code
stringlengths 0
1.02M
| repo_name
stringlengths 9
48
| file_path
stringlengths 5
114
|
---|---|---|
# Test for gaussian kernel operation using LazyTensors.
import time
import math
import torch
from pykeops.torch import LazyTensor
M, N, D, DV = 200, 300, 300, 1
dtype = torch.float32
sum_scheme = "block_sum"
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, 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/chunks.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 | keopscore/keopscore/sandbox/complex_numpy.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)
a = np.empty((M, DV), dtype=dtype)
def fun(x, y, b, backend, out=None):
if "keops" in backend:
x = LazyTensor(x)
y = LazyTensor(y)
Dxy = ((x - y)).sum(axis=2)
if backend == "keops":
Kxy = (-Dxy).exp()
out = Kxy.__matmul__(b, out=out)
else:
Kxy = np.exp(-Dxy)
out = Kxy @ b
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, out=a).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_inplace.py |
keops-main | keopscore/keopscore/binders/__init__.py |
|
import os
import keopscore.config.config
from keopscore.config.config import get_build_folder
from keopscore.utils.code_gen_utils import get_hash_name
from keopscore.utils.misc_utils import KeOps_Error, KeOps_Message
from keopscore.config.config import cpp_flags
class LinkCompile:
"""
Base class for compiling the map_reduce schemes and providing the dll to KeOps bindings.
"""
def __init__(self):
# N.B. Here self is assumed to be populated by the __init__ of one of the MapReduce classes
# we create the hash string id corresponding to all parameters, e.g. 7b9a611f7e
self.gencode_filename = get_hash_name(
type(self),
self.red_formula_string,
self.aliases,
self.nargs,
self.dtype,
self.dtypeacc,
self.sum_scheme_string,
self.tagHostDevice,
self.tagCpuGpu,
self.tag1D2D,
self.use_half,
self.device_id,
cpp_flags,
)
# info_file is the name of the file that will contain some meta-information required by the bindings, e.g. 7b9a611f7e.nfo
self.info_file = os.path.join(
get_build_folder(), self.gencode_filename + ".nfo"
)
# gencode_file is the name of the source file to be created and then compiled, e.g. 7b9a611f7e.cpp or 7b9a611f7e.cu
self.gencode_file = os.path.join(
get_build_folder(),
self.gencode_filename + "." + self.source_code_extension,
)
def save_info(self):
# create info_file to save some parameters : dim (dimension of output vectors),
# tagI (O or 1, reduction over i or j indices),
# dimy (sum of dimensions of j-indexed vectors)
f = open(self.info_file, "w")
f.write(
f"red_formula={self.red_formula_string}\ndim={self.dim}\ntagI={self.tagI}\ndimy={self.dimy}"
)
f.close()
def read_info(self):
# read info_file to retreive dim, tagI, dimy
f = open(self.info_file, "r")
string = f.read()
f.close()
tmp = string.split("\n")
if len(tmp) != 4:
KeOps_Error("Incorrect info file")
tmp_dim, tmp_tag, tmp_dimy = (
tmp[1].split("="),
tmp[2].split("="),
tmp[3].split("="),
)
if (
len(tmp_dim) != 2
or tmp_dim[0] != "dim"
or len(tmp_tag) != 2
or tmp_tag[0] != "tagI"
or len(tmp_dimy) != 2
or tmp_dimy[0] != "dimy"
):
KeOps_Error("Incorrect info file")
self.dim = eval(tmp_dim[1])
self.tagI = eval(tmp_tag[1])
self.dimy = eval(tmp_dimy[1])
def write_code(self):
# write the generated code in the source file ; this is used as a subfunction of compile_code
f = open(self.gencode_file, "w")
f.write(self.code)
f.close()
def generate_code(self):
pass
def get_dll_and_params(self):
# main method of the class : it generates - if needed - the code and returns the name of the dll to be run for
# performing the reduction, e.g. 7b9a611f7e.so, or in the case of JIT compilation, the name of the main KeOps dll,
# and the name of the assembly code file.
if not os.path.exists(self.file_to_check):
KeOps_Message(
"Generating code for formula " + self.red_formula.__str__() + " ... ",
flush=True,
end="",
)
self.generate_code()
self.save_info()
KeOps_Message("OK", use_tag=False, flush=True)
else:
self.read_info()
return dict(
tag=self.gencode_filename,
source_file=self.true_dllname,
low_level_code_file=self.low_level_code_file,
tagI=self.tagI,
use_half=self.use_half,
tag1D2D=self.tag1D2D,
dimred=self.red_formula.dimred,
dim=self.dim,
dimy=self.dimy,
indsi=self.varloader.indsi,
indsj=self.varloader.indsj,
indsp=self.varloader.indsp,
dimsx=self.varloader.dimsx,
dimsy=self.varloader.dimsy,
dimsp=self.varloader.dimsp,
)
| keops-main | keopscore/keopscore/binders/LinkCompile.py |
keops-main | keopscore/keopscore/binders/nvrtc/__init__.py |
|
import os
from ctypes import create_string_buffer, CDLL, c_int
from os import RTLD_LAZY
import sysconfig
from keopscore.binders.LinkCompile import LinkCompile
import keopscore.config
from keopscore.config.config import (
cuda_version,
jit_binary,
cxx_compiler,
nvrtc_flags,
nvrtc_include,
jit_source_file,
cuda_available,
get_build_folder,
)
from keopscore.utils.misc_utils import KeOps_Error, KeOps_Message, KeOps_OS_Run
from keopscore.utils.gpu_utils import get_gpu_props, cuda_include_fp16_path
jit_compile_src = os.path.join(
os.path.abspath(os.path.dirname(__file__)), "nvrtc_jit.cpp"
)
def jit_compile_dll():
return os.path.join(
get_build_folder(),
"nvrtc_jit" + sysconfig.get_config_var("SHLIB_SUFFIX"),
)
class Gpu_link_compile(LinkCompile):
source_code_extension = "cu"
low_level_code_prefix = "cubin_" if cuda_version >= 11010 else "ptx_"
ngpu, gpu_props_compile_flags = get_gpu_props()
def __init__(self):
# checking that the system has a Gpu :
if not (cuda_available and Gpu_link_compile.ngpu):
KeOps_Error(
"Trying to compile cuda code... but we detected that the system has no properly configured cuda lib."
)
LinkCompile.__init__(self)
# these are used for JIT compiling mode
# low_level_code_file is filename of low level code (PTX for Cuda) or binary (CUBIN for Cuda)
# generated by the JIT compiler, e.g. ptx_7b9a611f7e
self.low_level_code_file = os.path.join(
get_build_folder(),
self.low_level_code_prefix + self.gencode_filename,
).encode("utf-8")
self.my_c_dll = CDLL(jit_compile_dll(), mode=RTLD_LAZY)
# actual dll to be called is the jit binary, TODO: check if this is relevent
self.true_dllname = jit_binary
# file to check for existence to detect compilation is needed
self.file_to_check = self.low_level_code_file
def generate_code(self):
# method to generate the code and compile it
# generate the code and save it in self.code, by calling get_code method from GpuReduc class :
self.get_code()
# write the code in the source file
self.write_code()
# we execute the main dll, passing the code as argument, and the name of the low level code file to save the assembly instructions
self.my_c_dll.Compile(
create_string_buffer(self.low_level_code_file),
create_string_buffer(self.code.encode("utf-8")),
c_int(self.use_half),
c_int(self.device_id),
create_string_buffer(
(cuda_include_fp16_path() + os.path.sep).encode("utf-8")
),
)
# retreive some parameters that will be saved into info_file.
self.tagI = self.red_formula.tagI
self.dim = self.red_formula.dim
@staticmethod
def get_compile_command(
sourcename=jit_source_file, dllname=jit_binary, extra_flags=""
):
# This is about the main KeOps binary (dll) that will be used to JIT compile all formulas.
# If the dll is not present, it compiles it from source, except if check_compile is False.
target_tag = (
"CUBIN" if Gpu_link_compile.low_level_code_prefix == "cubin_" else "PTX"
)
nvrtcGetTARGET = "nvrtcGet" + target_tag
nvrtcGetTARGETSize = nvrtcGetTARGET + "Size"
arch_tag = (
'\\"sm\\"'
if Gpu_link_compile.low_level_code_prefix == "cubin_"
else '\\"compute\\"'
)
target_type_define = f"-DnvrtcGetTARGET={nvrtcGetTARGET} -DnvrtcGetTARGETSize={nvrtcGetTARGETSize} -DARCHTAG={arch_tag}"
return f"{cxx_compiler} {nvrtc_flags} {extra_flags} {target_type_define} {nvrtc_include} {Gpu_link_compile.gpu_props_compile_flags} {sourcename} -o {dllname}"
@staticmethod
def compile_jit_compile_dll():
KeOps_Message("Compiling cuda jit compiler engine ... ", flush=True, end="")
KeOps_OS_Run(
Gpu_link_compile.get_compile_command(
sourcename=jit_compile_src,
dllname=jit_compile_dll(),
),
)
KeOps_Message("OK", use_tag=False, flush=True)
| keops-main | keopscore/keopscore/binders/nvrtc/Gpu_link_compile.py |
from keopscore.binders.LinkCompile import LinkCompile
class Cpu_link_compile(LinkCompile):
source_code_extension = "cpp"
def __init__(self):
LinkCompile.__init__(self)
# these are used for command line compiling mode
self.low_level_code_file = "".encode("utf-8")
# actual dll to be called
self.true_dllname = self.gencode_file
# file to check for existence to detect compilation is needed
self.file_to_check = self.gencode_file
def generate_code(self):
# method to generate the code and compile it
# generate the code and save it in self.code, by calling get_code method from CpuReduc class :
self.get_code()
# write the code in the source file
self.write_code()
# retreive some parameters that will be saved into info_file.
self.tagI = self.red_formula.tagI
self.dim = self.red_formula.dim
| keops-main | keopscore/keopscore/binders/cpp/Cpu_link_compile.py |
keops-main | keopscore/keopscore/binders/cpp/__init__.py |
|
from keopscore.config.chunks import dimchunk
from keopscore.utils.code_gen_utils import GetDims, GetInds, Var_loader
class Chunk_Mode_Constants:
def __init__(self, red_formula):
varloader = Var_loader(red_formula)
self.red_formula = red_formula
self.dimred = red_formula.dimred # dimension of reduction operation
self.dimsp = varloader.dimsp # dimensions of parameters variables
self.indsp = varloader.indsp
self.dimp = varloader.dimp
self.dimout = (
red_formula.dim
) # dimension of output variable of reduction operation
formula = red_formula.formula
self.dimfout = formula.dim # dimension of output variable of inner function
chunked_formula = formula.chunked_formulas(dimchunk)[0]
self.dim_org = chunked_formula["dim_org"]
self.nchunks = 1 + (self.dim_org - 1) // dimchunk
self.dimlastchunk = self.dim_org - (self.nchunks - 1) * dimchunk
self.nminargs = varloader.nminargs
self.fun_chunked = chunked_formula["formula"]
self.dimout_chunk = self.fun_chunked.dim
self.varsi_chunked = self.fun_chunked.chunked_vars(red_formula.tagI)
self.dimsx_chunked = GetDims(self.varsi_chunked)
self.indsi_chunked = GetInds(self.varsi_chunked)
self.varsj_chunked = self.fun_chunked.chunked_vars(red_formula.tagJ)
self.dimsy_chunked = GetDims(self.varsj_chunked)
self.indsj_chunked = GetInds(self.varsj_chunked)
self.fun_postchunk = formula.post_chunk_formula(self.nminargs)
self.varsi_postchunk = self.fun_postchunk.Vars(red_formula.tagI)
self.dimsx_postchunk = GetDims(self.varsi_postchunk)
self.indsi_postchunk = GetInds(self.varsi_postchunk)
self.varsj_postchunk = self.fun_postchunk.Vars(red_formula.tagJ)
self.dimsy_postchunk = GetDims(self.varsj_postchunk)
self.indsj_postchunk = GetInds(self.varsj_postchunk)
self.varsi_notchunked = list(
set.union(
set(self.varsi_postchunk),
set(self.fun_chunked.notchunked_vars(red_formula.tagI)),
)
)
# Here we detect if chunked variables are also used in the postchunk formula
# Currently the code in GpuReduc1D_chunks.py does not handle this case, so
# we will use the "chunk_postchunk_mix" tag defined below
# in get_keops_dll to disable the chunked mode for the formula.
self.chunk_postchunk_mix = (
len(set.intersection(set(self.indsi_postchunk), set(self.indsi_chunked)))
+ len(set.intersection(set(self.indsj_postchunk), set(self.indsj_chunked)))
) > 0
self.indsi_notchunked = GetInds(self.varsi_notchunked)
self.dimsx_notchunked = GetDims(self.varsi_notchunked)
self.dimx_notchunked = sum(self.dimsx_notchunked)
self.varsj_notchunked = list(
set.union(
set(self.varsj_postchunk),
set(self.fun_chunked.notchunked_vars(red_formula.tagJ)),
)
)
self.indsj_notchunked = GetInds(self.varsj_notchunked)
self.dimsy_notchunked = GetDims(self.varsj_notchunked)
self.dimy_notchunked = sum(self.dimsy_notchunked)
self.fun_lastchunked = formula.chunked_formulas(self.dimlastchunk)[0]["formula"]
self.varsi_lastchunked = self.fun_lastchunked.chunked_vars(red_formula.tagI)
self.indsi_lastchunked = GetInds(self.varsi_lastchunked)
self.dimsx_lastchunked = GetDims(self.varsi_lastchunked)
self.varsj_lastchunked = self.fun_lastchunked.chunked_vars(red_formula.tagJ)
self.indsj_lastchunked = GetInds(self.varsj_lastchunked)
self.dimsy_lastchunked = GetDims(self.varsj_lastchunked)
self.varsi = [*self.varsi_notchunked, *self.varsi_chunked]
self.dimsx = GetDims(self.varsi)
self.indsi = GetInds(self.varsi)
self.dimx = sum(self.dimsx)
self.varsj = [*self.varsj_notchunked, *self.varsj_chunked]
self.dimsy = GetDims(self.varsj)
self.indsj = GetInds(self.varsj)
self.dimy = sum(self.dimsy)
self.inds = [*self.indsi, *self.indsj, *self.indsp]
self.varsi_last = [*self.varsi_notchunked, *self.varsi_lastchunked]
self.indsi_last = GetInds(self.varsi_last)
self.dimsx_last = GetDims(self.varsi_last)
self.varsj_last = [*self.varsj_notchunked, *self.varsj_lastchunked]
self.indsj_last = GetInds(self.varsj_last)
self.dimsy_last = GetDims(self.varsj_last)
| keops-main | keopscore/keopscore/mapreduce/Chunk_Mode_Constants.py |
from .cpu import *
from ..config.config import use_cuda
if use_cuda:
from .gpu import *
| keops-main | keopscore/keopscore/mapreduce/__init__.py |
from keopscore.formulas.reductions import *
from keopscore.formulas.GetReduction import GetReduction
from keopscore.utils.code_gen_utils import Var_loader, new_c_varname, pointer, c_include
class MapReduce:
"""
base class for map-reduce schemes
"""
def __init__(
self,
red_formula_string,
aliases,
nargs,
dtype,
dtypeacc,
sum_scheme_string,
tagHostDevice,
tagCpuGpu,
tag1D2D,
use_half,
device_id,
):
self.red_formula_string = red_formula_string
self.aliases = aliases
self.red_formula = GetReduction(red_formula_string, aliases=aliases)
self.dtype = dtype
self.dtypeacc = dtypeacc
self.nargs = nargs
self.sum_scheme_string = sum_scheme_string
self.tagHostDevice, self.tagCpuGpu, self.tag1D2D = (
tagHostDevice,
tagCpuGpu,
tag1D2D,
)
self.use_half = use_half
self.device_id = device_id
self.varloader = Var_loader(self.red_formula)
def get_code(self):
self.headers = "#define C_CONTIGUOUS 1\n"
if self.use_half == 1:
self.headers += "#define USE_HALF 1\n"
self.headers += c_include("cuda_fp16.h")
else:
self.headers += "#define USE_HALF 0\n"
red_formula = self.red_formula
formula = red_formula.formula
dtype = self.dtype
dtypeacc = self.dtypeacc
nargs = self.nargs
self.sum_scheme = eval(self.sum_scheme_string)(red_formula, dtype)
self.i = i = c_variable("int", "i")
self.j = j = c_variable("int", "j")
nx = c_variable("int", "nx")
ny = c_variable("int", "ny")
self.xi = c_array(dtype, self.varloader.dimx, "xi")
self.param_loc = c_array(dtype, self.varloader.dimp, "param_loc")
argname = new_c_varname("arg")
self.arg = c_variable(pointer(pointer(dtype)), argname)
self.args = [self.arg[k] for k in range(nargs)]
self.acc = c_array(dtypeacc, red_formula.dimred, "acc")
self.acctmp = c_array(dtypeacc, red_formula.dimred, "acctmp")
self.fout = c_array(dtype, formula.dim, "fout")
self.outi = c_array(dtype, red_formula.dim, f"(out + i * {red_formula.dim})")
| keops-main | keopscore/keopscore/mapreduce/MapReduce.py |
from .GpuAssignZero import GpuAssignZero
from .GpuReduc1D import GpuReduc1D
from .GpuReduc1D_chunks import GpuReduc1D_chunks
from .GpuReduc1D_finalchunks import GpuReduc1D_finalchunks
from .GpuReduc1D_ranges import GpuReduc1D_ranges
from .GpuReduc1D_ranges_chunks import GpuReduc1D_ranges_chunks
from .GpuReduc1D_ranges_finalchunks import (
GpuReduc1D_ranges_finalchunks,
)
from .GpuReduc2D import GpuReduc2D
| keops-main | keopscore/keopscore/mapreduce/gpu/__init__.py |
from keopscore import cuda_block_size
from keopscore.config.chunks import dimfinalchunk
from keopscore.binders.nvrtc.Gpu_link_compile import Gpu_link_compile
from keopscore.formulas.reductions.Sum_Reduction import Sum_Reduction
from keopscore.formulas.reductions.sum_schemes import *
from keopscore.mapreduce.gpu.GpuAssignZero import GpuAssignZero
from keopscore.mapreduce.MapReduce import MapReduce
from keopscore.utils.code_gen_utils import (
load_vars,
load_vars_chunks,
load_vars_chunks_offsets,
sizeof,
pointer,
Var_loader,
use_pragma_unroll,
)
from keopscore.utils.misc_utils import KeOps_Error
def do_finalchunk_sub_ranges(
dtype,
fun_global,
varfinal,
dimfinalchunk_curr,
acc,
i,
j,
jstart,
start_y,
chunk,
end_x,
end_y,
nbatchdims,
indices_j,
arg,
fout,
yj,
out,
):
dimout = varfinal.dim
yjloc = c_variable(pointer(dtype), f"({yj.id} + threadIdx.x * {dimfinalchunk})")
indsj_global = Var_loader(fun_global).indsj
load_chunks_routine_j = load_vars_chunks(
[varfinal.ind],
dimfinalchunk,
dimfinalchunk_curr,
varfinal.dim,
yjloc,
arg,
chunk,
row_index=j,
)
load_chunks_routine_j_ranges = load_vars_chunks_offsets(
[varfinal.ind],
indsj_global,
dimfinalchunk,
dimfinalchunk_curr,
varfinal.dim,
yjloc,
arg,
chunk,
indices_j,
row_index=j - start_y,
)
return f"""
{acc.assign(c_zero_float)}
{dtype} *yjrel = yj;
if ({j.id} < {end_y.id}) {{ // we load yj from device global memory only if j<end_y
if ({nbatchdims.id}==0) {{
{load_chunks_routine_j}
}} else {{
{load_chunks_routine_j_ranges}
}}
}}
__syncthreads();
for (int jrel = 0; (jrel < blockDim.x) && (jrel < {end_y.id} - {jstart.id}); jrel++, yjrel += {dimfinalchunk}) {{
if ({i.id} < {end_x.id}) {{ // we compute only if needed
{use_pragma_unroll()}
for (int k=0; k<{dimfinalchunk_curr}; k++) {{
{acc.id}[k] += yjrel[k] * fout[jrel];
}}
}}
__syncthreads();
}}
if ({i.id} < {end_x.id}) {{
{use_pragma_unroll()}
for (int k=0; k<{dimfinalchunk_curr}; k++)
{out.id}[i*{dimout}+{chunk.id}*{dimfinalchunk}+k] += {acc.id}[k];
}}
__syncthreads();
"""
class GpuReduc1D_ranges_finalchunks(MapReduce, Gpu_link_compile):
# class for generating the final C++ code, Gpu version
AssignZero = GpuAssignZero
def __init__(self, *args):
MapReduce.__init__(self, *args)
Gpu_link_compile.__init__(self)
def get_code(self):
super().get_code()
dtype = self.dtype
dtypeacc = self.dtypeacc
i = self.i
j = self.j
nx = c_variable("int", "nx")
ny = c_variable("int", "ny")
jstart = c_variable("int", "jstart")
chunk = c_variable("int", "chunk")
arg = self.arg
args = self.args
yj = c_variable(pointer(dtype), "yj")
out = c_variable(pointer(dtype), "out")
fun_internal = Sum_Reduction(
self.red_formula.formula.children[0], self.red_formula.tagI
)
formula = fun_internal.formula
varfinal = self.red_formula.formula.children[1]
nchunks = 1 + (varfinal.dim - 1) // dimfinalchunk
dimlastfinalchunk = varfinal.dim - (nchunks - 1) * dimfinalchunk
varloader = Var_loader(fun_internal)
dimsx = varloader.dimsx
dimsy = varloader.dimsy
dimsp = varloader.dimsp
indsi = varloader.indsi
indsj = varloader.indsj
indsp = varloader.indsp
dimx = sum(dimsx)
dimy = sum(dimsy)
dimp = sum(dimsp)
dimout = varfinal.dim
dimfout = fun_internal.formula.dim
if dimfout != 1:
KeOps_Error("dimfout should be 1")
sum_scheme = self.sum_scheme
self.dimy = max(dimfinalchunk, dimy)
blocksize_chunks = min(
cuda_block_size, 1024, 49152 // max(1, self.dimy * sizeof(self.dtype))
)
if not isinstance(sum_scheme, block_sum):
KeOps_Error("only block_sum available")
param_loc = c_array(dtype, dimp, "param_loc")
fout = c_array(dtype, dimfout * blocksize_chunks, "fout")
xi = c_array(dtype, dimx, "xi")
acc = c_array(dtypeacc, dimfinalchunk, "acc")
yjloc = c_array(dtype, dimy, f"(yj + threadIdx.x * {dimy})")
foutjrel = c_array(dtype, dimfout, f"({fout.id}+jrel*{dimfout})")
yjrel = c_array(dtype, dimy, "yjrel")
table = varloader.table(xi, yjrel, param_loc)
lastchunk = c_variable("int", f"{nchunks-1}")
startx = c_variable("int", "start_x")
starty = c_variable("int", "start_y")
end_x = c_variable("int", "end_x")
end_y = c_variable("int", "end_y")
nbatchdims = c_variable("int", "nbatchdims")
fun_global = self.red_formula
varloader_global = Var_loader(fun_global)
indsi_global = varloader_global.indsi
indsj_global = varloader_global.indsj
nvarsi_global, nvarsj_global, nvarsp_global = (
len(varloader_global.Varsi),
len(varloader_global.Varsj),
len(varloader_global.Varsp),
)
nvars_global = nvarsi_global + nvarsj_global + nvarsp_global
offsets = c_array("int", nvars_global, "offsets")
indices_i = c_array("int", nvarsi_global, "indices_i")
indices_j = c_array("int", nvarsj_global, "indices_j")
indices_p = c_array("int", nvarsp_global, "indices_p")
declare_assign_indices_i = (
"int *indices_i = offsets;" if nvarsi_global > 0 else ""
)
declare_assign_indices_j = (
f"int *indices_j = offsets + {nvarsi_global};" if nvarsj_global > 0 else ""
)
declare_assign_indices_p = (
f"int *indices_p = offsets + {nvarsi_global} + {nvarsj_global};"
if nvarsp_global > 0
else ""
)
chunk_sub_routine = do_finalchunk_sub_ranges(
dtype,
fun_global,
varfinal,
dimfinalchunk,
acc,
i,
j,
jstart,
starty,
chunk,
end_x,
end_y,
nbatchdims,
indices_j,
arg,
fout,
yj,
out,
)
chunk_sub_routine_last = do_finalchunk_sub_ranges(
dtype,
fun_global,
varfinal,
dimlastfinalchunk,
acc,
i,
j,
jstart,
starty,
lastchunk,
end_x,
end_y,
nbatchdims,
indices_j,
arg,
fout,
yj,
out,
)
threadIdx_x = c_variable("int", "threadIdx.x")
self.code = f"""
{self.headers}
extern "C" __global__ void GpuConv1DOnDevice_ranges(int nx, int ny, int nbatchdims,
int *offsets_d, int *lookup_d, int *slices_x,
int *ranges_y, {dtype} *out, {dtype} **{arg.id}) {{
{offsets.declare()}
{declare_assign_indices_i}
{declare_assign_indices_j}
{declare_assign_indices_p}
if (nbatchdims > 0) {{
for (int k = 0; k < {nvars_global}; k++) {{
offsets[k] = offsets_d[ {nvars_global} * blockIdx.x + k ];
}}
}}
// Retrieve our position along the laaaaarge [1,~nx] axis: -----------------
int range_id= (lookup_d)[3*blockIdx.x] ;
int start_x = (lookup_d)[3*blockIdx.x+1] ;
int end_x = (lookup_d)[3*blockIdx.x+2] ;
// The "slices_x" vector encodes a set of cutting points in
// the "ranges_y" array of ranges.
// As discussed in the Genred docstring, the first "0" is implicit:
int start_slice = range_id < 1 ? 0 : slices_x[range_id-1];
int end_slice = slices_x[range_id];
// get the index of the current thread
int i = start_x + threadIdx.x;
// declare shared mem
extern __shared__ {dtype} yj[];
// load parameter(s)
{param_loc.declare()}
{load_vars(dimsp, indsp, param_loc, args)}
{fout.declare()}
// get the value of variable (index with i)
{xi.declare()}
if (i < end_x) {{
if (nbatchdims == 0) {{
{varloader.load_vars("i", xi, args, row_index=i)} // load xi variables from global memory to local thread memory
}} else {{
{varloader.load_vars("i", xi, args, row_index=threadIdx_x, offsets=indices_i, indsref=indsi_global)} // Possibly, with offsets as we support broadcasting over batch dimensions
}}
{use_pragma_unroll()}
for (int k=0; k<{dimout}; k++) {{
out[i*{dimout}+k] = 0.0f;
}}
}}
{acc.declare()}
int start_y = ranges_y[2*start_slice], end_y = 0;
for(int index = start_slice ; index < end_slice ; index++ ) {{
if( (index+1 >= end_slice) || (ranges_y[2*index+2] != ranges_y[2*index+1]) ) {{
end_y = ranges_y[2*index+1];
for (int jstart = start_y, tile = 0; jstart < end_y; jstart += blockDim.x, tile++) {{
// get the current column
int j = jstart + threadIdx.x;
if (j < end_y) {{ // we load yj from device global memory only if j<end_y
if (nbatchdims == 0) {{
{varloader.load_vars("j", yjloc, args, row_index=j)} // load yj variables from global memory to shared memory
}} else {{
{varloader.load_vars("j", yjloc, args, row_index=j-starty, offsets=indices_j, indsref=indsj_global)} // Possibly, with offsets as we support broadcasting over batch dimensions
}}
}}
__syncthreads();
if (i < end_x) {{ // we compute x1i only if needed
{dtype} * yjrel = yj; // Loop on the columns of the current block.
for (int jrel = 0; (jrel < {blocksize_chunks}) && (jrel < end_y - jstart); jrel++, yjrel += {dimy}) {{
{formula(foutjrel, table)} // Call the function, which outputs results in fout
}}
}}
__syncthreads();
for (int chunk=0; chunk<{nchunks-1}; chunk++) {{
{chunk_sub_routine}
}}
{chunk_sub_routine_last}
}}
if(index+1 < end_slice)
start_y = ranges_y[2*index+2];
}}
}}
}}
"""
| keops-main | keopscore/keopscore/mapreduce/gpu/GpuReduc1D_ranges_finalchunks.py |
from keopscore import cuda_block_size
from keopscore.config.chunks import dimchunk
from keopscore.binders.nvrtc.Gpu_link_compile import Gpu_link_compile
from keopscore.formulas.reductions.sum_schemes import *
from keopscore.mapreduce.gpu.GpuAssignZero import GpuAssignZero
from keopscore.mapreduce.MapReduce import MapReduce
from keopscore.utils.code_gen_utils import (
load_vars,
load_vars_chunks,
load_vars_chunks_offsets,
sizeof,
pointer,
table,
table4,
Var_loader,
use_pragma_unroll,
)
from keopscore.mapreduce.Chunk_Mode_Constants import Chunk_Mode_Constants
def do_chunk_sub_ranges(
dtype,
red_formula,
fun_chunked_curr,
dimchunk_curr,
dimsx,
dimsy,
indsi,
indsj,
indsi_chunked,
indsj_chunked,
acc,
tile,
i,
j,
jstart,
start_y,
chunk,
end_x,
end_y,
nbatchdims,
indices_i,
indices_j,
arg,
fout,
xi,
yj,
param_loc,
):
chk = Chunk_Mode_Constants(red_formula)
fout_tmp_chunk = c_array(dtype, chk.fun_chunked.dim)
xiloc = c_variable(pointer(dtype), f"({xi.id} + {chk.dimx_notchunked})")
yjloc = c_variable(
pointer(dtype), f"({yj.id} + threadIdx.x * {chk.dimy} + {chk.dimy_notchunked})"
)
load_chunks_routine_i = load_vars_chunks(
indsi_chunked,
dimchunk,
dimchunk_curr,
chk.dim_org,
xiloc,
arg,
chunk,
row_index=i,
)
varloader_global = Var_loader(red_formula)
indsi_global = varloader_global.indsi
indsj_global = varloader_global.indsj
threadIdx_x = c_variable("int", "threadIdx.x")
load_chunks_routine_i_batches = load_vars_chunks_offsets(
indsi_chunked,
indsi_global,
dimchunk,
dimchunk_curr,
chk.dim_org,
xiloc,
arg,
chunk,
indices_i,
row_index=threadIdx_x,
)
load_chunks_routine_j = load_vars_chunks(
indsj_chunked,
dimchunk,
dimchunk_curr,
chk.dim_org,
yjloc,
arg,
chunk,
row_index=j,
)
load_chunks_routine_j_batches = load_vars_chunks_offsets(
indsj_chunked,
indsj_global,
dimchunk,
dimchunk_curr,
chk.dim_org,
yjloc,
arg,
chunk,
indices_j,
row_index=j - start_y,
)
yjrel = c_variable(pointer(dtype), "yjrel")
chktable = table(
chk.nminargs,
dimsx,
dimsy,
chk.dimsp,
indsi,
indsj,
chk.indsp,
xi,
yjrel,
param_loc,
)
foutj = c_variable(pointer(dtype), "foutj")
return f"""
{fout_tmp_chunk.declare()}
if ({i.id} < {end_x.id}) {{
if ({nbatchdims.id}==0) {{
{load_chunks_routine_i}
}} else {{
{load_chunks_routine_i_batches}
}}
}}
if ({j.id} < {end_y.id}) {{ // we load yj from device global memory only if j<ny
if ({nbatchdims.id}==0) {{
{load_chunks_routine_j}
}} else {{
{load_chunks_routine_j_batches}
}}
}}
__syncthreads();
if ({i.id} < {end_x.id}) {{ // we compute only if needed
{dtype} *yjrel = {yj.id}; // Loop on the columns of the current block.
for (int jrel = 0; (jrel < blockDim.x) && (jrel < {end_y.id} - jstart); jrel++, yjrel += {chk.dimy}) {{
{dtype} *foutj = {fout.id} + jrel*{chk.fun_chunked.dim};
{fun_chunked_curr(fout_tmp_chunk, chktable)}
{chk.fun_chunked.acc_chunk(foutj, fout_tmp_chunk)}
}}
}}
__syncthreads();
"""
class GpuReduc1D_ranges_chunks(MapReduce, Gpu_link_compile):
# class for generating the final C++ code, Gpu version
AssignZero = GpuAssignZero
def __init__(self, *args):
MapReduce.__init__(self, *args)
Gpu_link_compile.__init__(self)
self.chk = Chunk_Mode_Constants(self.red_formula)
self.dimy = self.chk.dimy
self.blocksize_chunks = min(
cuda_block_size, 1024, 49152 // max(1, self.dimy * sizeof(self.dtype))
)
def get_code(self):
super().get_code()
red_formula = self.red_formula
dtype = self.dtype
dtypeacc = self.dtypeacc
varloader_global = Var_loader(red_formula)
indsi_global = varloader_global.indsi
indsj_global = varloader_global.indsj
i = self.i
j = self.j
arg = self.arg
args = self.args
nvarsi, nvarsj, nvarsp = (
len(self.varloader.Varsi),
len(self.varloader.Varsj),
len(self.varloader.Varsp),
)
nvars = nvarsi + nvarsj + nvarsp
indices_i = c_array("int", nvarsi, "indices_i")
indices_j = c_array("int", nvarsj, "indices_j")
indices_p = c_array("int", nvarsp, "indices_p")
declare_assign_indices_i = "int *indices_i = offsets;" if nvarsi > 0 else ""
declare_assign_indices_j = (
f"int *indices_j = offsets + {nvarsi};" if nvarsj > 0 else ""
)
declare_assign_indices_p = (
f"int *indices_p = offsets + {nvarsi} + {nvarsj};" if nvarsp > 0 else ""
)
yjrel = c_array(dtype, varloader_global.dimy, "yjrel")
jreltile = c_variable("int", "(jrel + tile * blockDim.x)")
chk = self.chk
param_loc = c_array(dtype, chk.dimp, "param_loc")
acc = c_array(dtypeacc, chk.dimred, "acc")
sum_scheme = eval(self.sum_scheme_string)(red_formula, dtype, dimred=chk.dimred)
xi = c_array(dtype, chk.dimx, "xi")
fout_chunk = c_array(
dtype, self.blocksize_chunks * chk.dimout_chunk, "fout_chunk"
)
yj = c_variable(pointer(dtype), "yj")
yjloc = c_array(dtype, chk.dimy, f"(yj + threadIdx.x * {chk.dimy})")
fout_chunk_loc = c_variable(
pointer(dtype), f"({fout_chunk.id}+jrel*{chk.dimout_chunk})"
)
tile = c_variable("int", "tile")
nx = c_variable("int", "nx")
ny = c_variable("int", "ny")
jstart = c_variable("int", "jstart")
chunk = c_variable("int", "chunk")
end_x = c_variable("int", "end_x")
end_y = c_variable("int", "end_y")
starty = c_variable("int", "start_y")
nbatchdims = c_variable("int", "nbatchdims")
chunk_sub_routine = do_chunk_sub_ranges(
dtype,
red_formula,
chk.fun_chunked,
dimchunk,
chk.dimsx,
chk.dimsy,
chk.indsi,
chk.indsj,
chk.indsi_chunked,
chk.indsj_chunked,
acc,
tile,
i,
j,
jstart,
starty,
chunk,
end_x,
end_y,
nbatchdims,
indices_i,
indices_j,
arg,
fout_chunk,
xi,
yj,
param_loc,
)
last_chunk = c_variable("int", f"{chk.nchunks-1}")
chunk_sub_routine_last = do_chunk_sub_ranges(
dtype,
red_formula,
chk.fun_lastchunked,
chk.dimlastchunk,
chk.dimsx_last,
chk.dimsy_last,
chk.indsi,
chk.indsj,
chk.indsi_lastchunked,
chk.indsj_lastchunked,
acc,
tile,
i,
j,
jstart,
starty,
last_chunk,
end_x,
end_y,
nbatchdims,
indices_i,
indices_j,
arg,
fout_chunk,
xi,
yj,
param_loc,
)
foutj = c_array(dtype, chk.dimout_chunk, "foutj")
chktable_out = table4(
chk.nminargs + 1,
chk.dimsx,
chk.dimsy,
chk.dimsp,
[chk.dimout_chunk],
chk.indsi,
chk.indsj,
chk.indsp,
[chk.nminargs],
xi,
yjrel,
param_loc,
foutj,
)
fout_tmp = c_array(dtype, chk.dimfout, "fout_tmp")
outi = c_array(dtype, chk.dimout, f"(out + i * {chk.dimout})")
threadIdx_x = c_variable("int", "threadIdx.x")
self.code = f"""
{self.headers}
extern "C" __global__ void GpuConv1DOnDevice_ranges(int nx, int ny, int nbatchdims,
int *offsets_d, int *lookup_d, int *slices_x,
int *ranges_y, {dtype} *out, {dtype} **{arg.id}) {{
int offsets[{nvars}];
{declare_assign_indices_i}
{declare_assign_indices_j}
{declare_assign_indices_p}
if (nbatchdims > 0)
for (int k = 0; k < {nvars}; k++)
offsets[k] = offsets_d[ {nvars} * blockIdx.x + k ];
// Retrieve our position along the laaaaarge [1,~nx] axis: -----------------
int range_id= (lookup_d)[3*blockIdx.x] ;
int start_x = (lookup_d)[3*blockIdx.x+1] ;
int end_x = (lookup_d)[3*blockIdx.x+2] ;
// The "slices_x" vector encodes a set of cutting points in
// the "ranges_y" array of ranges.
// As discussed in the Genred docstring, the first "0" is implicit:
int start_slice = range_id < 1 ? 0 : slices_x[range_id-1];
int end_slice = slices_x[range_id];
// get the index of the current thread
int i = start_x + threadIdx.x;
// declare shared mem
extern __shared__ {dtype} yj[];
// load parameters variables from global memory to local thread memory
{param_loc.declare()}
if (nbatchdims == 0) {{
{load_vars(chk.dimsp, chk.indsp, param_loc, args)}
}} else {{
{load_vars(chk.dimsp, chk.indsp, param_loc, args, offsets=indices_p)}
}}
{acc.declare()}
{sum_scheme.declare_temporary_accumulator()}
if (i < end_x) {{
{red_formula.InitializeReduction(acc)} // acc = 0
{sum_scheme.initialize_temporary_accumulator_first_init()}
}}
{xi.declare()}
{fout_chunk.declare()}
if (i < end_x) {{
// load xi variables from global memory to local thread memory
if (nbatchdims == 0) {{
{load_vars(chk.dimsx_notchunked, chk.indsi_notchunked, xi, args, row_index=i)}
}} else {{
{load_vars(chk.dimsx_notchunked, chk.indsi_notchunked, xi, args,
row_index=threadIdx_x, offsets=indices_i, indsref=indsi_global)}
}}
}}
int start_y = ranges_y[2*start_slice], end_y = 0;
for( int index = start_slice ; index < end_slice ; index++ ) {{
if( (index+1 >= end_slice) || (ranges_y[2*index+2] != ranges_y[2*index+1]) ) {{
//start_y = ranges_y[2*index] ;
end_y = ranges_y[2*index+1];
for(int jstart = start_y, tile = 0; jstart < end_y; jstart += blockDim.x, tile++) {{
// get the current column
int j = jstart + threadIdx.x;
if(j<end_y) // we load yj from device global memory only if j<end_y
if (nbatchdims == 0) {{
// load yj variables from global memory to shared memory
{load_vars(chk.dimsy_notchunked, chk.indsj_notchunked, yjloc, args, row_index=j)}
}} else {{
// Possibly, with offsets as we support broadcasting over batch dimensions
{load_vars(chk.dimsy_notchunked, chk.indsj_notchunked, yjloc, args,
row_index=j-starty, offsets=indices_j, indsref=indsj_global)}
}}
__syncthreads();
if(i<end_x) {{ // we compute x1i only if needed
for (int jrel = 0; (jrel < blockDim.x) && (jrel < end_y - jstart); jrel++) {{
{chk.fun_chunked.initacc_chunk(fout_chunk_loc)}
}}
{sum_scheme.initialize_temporary_accumulator_block_init()}
}}
// looping on chunks (except the last)
{use_pragma_unroll()}
for (int chunk=0; chunk<{chk.nchunks}-1; chunk++) {{
{chunk_sub_routine}
}}
// last chunk
{chunk_sub_routine_last}
if (i < end_x) {{
{dtype} * yjrel = yj; // Loop on the columns of the current block.
if (nbatchdims == 0) {{
for (int jrel = 0; (jrel < blockDim.x) && (jrel <end_y - jstart); jrel++, yjrel += {chk.dimy}) {{
{dtype} *foutj = fout_chunk + jrel*{chk.dimout_chunk};
{fout_tmp.declare()}
{chk.fun_postchunk(fout_tmp, chktable_out)}
{sum_scheme.accumulate_result(acc, fout_tmp, jreltile)}
}}
}} else {{
for (int jrel = 0; (jrel < blockDim.x) && (jrel <end_y - jstart); jrel++, yjrel += {chk.dimy}) {{
{dtype} *foutj = fout_chunk + jrel*{chk.dimout_chunk};
{fout_tmp.declare()}
{chk.fun_postchunk(fout_tmp, chktable_out)}
{sum_scheme.accumulate_result(acc, fout_tmp, jreltile)}
}}
}}
{sum_scheme.final_operation(acc)}
}}
__syncthreads();
}}
if(index+1 < end_slice) {{
start_y = ranges_y[2*index+2] ;
}}
}}
}}
if (i < end_x) {{
{red_formula.FinalizeOutput(acc, outi, i)}
}}
}}
"""
| keops-main | keopscore/keopscore/mapreduce/gpu/GpuReduc1D_ranges_chunks.py |
from keopscore import cuda_block_size
from keopscore.config.chunks import dimfinalchunk
from keopscore.binders.nvrtc.Gpu_link_compile import Gpu_link_compile
from keopscore.formulas.reductions.Sum_Reduction import Sum_Reduction
from keopscore.formulas.reductions.sum_schemes import *
from keopscore.mapreduce.gpu.GpuAssignZero import GpuAssignZero
from keopscore.mapreduce.MapReduce import MapReduce
from keopscore.utils.code_gen_utils import (
load_vars,
load_vars_chunks,
sizeof,
pointer,
Var_loader,
use_pragma_unroll,
)
from keopscore.utils.misc_utils import KeOps_Error
def do_finalchunk_sub(
dtype,
varfinal,
dimfinalchunk_curr,
acc,
i,
j,
jstart,
chunk,
nx,
ny,
arg,
fout,
yj,
out,
):
dimout = varfinal.dim
yjloc = c_variable(pointer(dtype), f"({yj.id} + threadIdx.x * {dimfinalchunk})")
load_chunks_routine_j = load_vars_chunks(
[varfinal.ind],
dimfinalchunk,
dimfinalchunk_curr,
varfinal.dim,
yjloc,
arg,
chunk,
row_index=j,
)
return f"""
{acc.assign(c_zero_float)}
{dtype} *yjrel = yj;
if ({j.id} < {ny.id}) {{ // we load yj from device global memory only if j<ny
{load_chunks_routine_j}
}}
__syncthreads();
for (int jrel = 0; (jrel < blockDim.x) && (jrel < {ny.id} - {jstart.id}); jrel++, yjrel += {dimfinalchunk}) {{
if ({i.id} < {nx.id}) {{ // we compute only if needed
{use_pragma_unroll()}
for (int k=0; k<{dimfinalchunk_curr}; k++) {{
{acc.id}[k] += yjrel[k] * fout[jrel];
}}
}}
__syncthreads();
}}
if ({i.id} < {nx.id}) {{
{use_pragma_unroll()}
for (int k=0; k<{dimfinalchunk_curr}; k++)
{out.id}[i*{dimout}+{chunk.id}*{dimfinalchunk}+k] += {acc.id}[k];
}}
__syncthreads();
"""
class GpuReduc1D_finalchunks(MapReduce, Gpu_link_compile):
# class for generating the final C++ code, Gpu version
AssignZero = GpuAssignZero
def __init__(self, *args):
MapReduce.__init__(self, *args)
Gpu_link_compile.__init__(self)
def get_code(self):
super().get_code()
dtype = self.dtype
dtypeacc = self.dtypeacc
i = self.i
j = self.j
nx = c_variable("int", "nx")
ny = c_variable("int", "ny")
jstart = c_variable("int", "jstart")
chunk = c_variable("int", "chunk")
arg = self.arg
args = self.args
yj = c_variable(pointer(dtype), "yj")
out = c_variable(pointer(dtype), "out")
fun_internal = Sum_Reduction(
self.red_formula.formula.children[0], self.red_formula.tagI
)
formula = fun_internal.formula
varfinal = self.red_formula.formula.children[1]
nchunks = 1 + (varfinal.dim - 1) // dimfinalchunk
dimlastfinalchunk = varfinal.dim - (nchunks - 1) * dimfinalchunk
varloader = Var_loader(fun_internal)
dimsx = varloader.dimsx
dimsy = varloader.dimsy
dimsp = varloader.dimsp
indsi = varloader.indsi
indsj = varloader.indsj
indsp = varloader.indsp
dimx = sum(dimsx)
dimy = sum(dimsy)
dimp = sum(dimsp)
dimout = varfinal.dim
dimfout = fun_internal.formula.dim
if dimfout != 1:
KeOps_Error("dimfout should be 1")
sum_scheme = self.sum_scheme
self.dimy = max(dimfinalchunk, dimy)
blocksize_chunks = min(
cuda_block_size, 1024, 49152 // max(1, self.dimy * sizeof(self.dtype))
)
if not isinstance(sum_scheme, block_sum):
KeOps_Error("only block_sum available")
param_loc = c_array(dtype, dimp, "param_loc")
fout = c_array(dtype, dimfout * blocksize_chunks, "fout")
xi = c_array(dtype, dimx, "xi")
acc = c_array(dtypeacc, dimfinalchunk, "acc")
yjloc = c_array(dtype, dimy, f"(yj + threadIdx.x * {dimy})")
foutjrel = c_array(dtype, dimfout, f"({fout.id}+jrel*{dimfout})")
yjrel = c_array(dtype, dimy, "yjrel")
table = self.varloader.table(xi, yjrel, param_loc)
last_chunk = c_variable("int", f"{nchunks-1}")
chunk_sub_routine = do_finalchunk_sub(
dtype,
varfinal,
dimfinalchunk,
acc,
i,
j,
jstart,
chunk,
nx,
ny,
arg,
fout,
yj,
out,
)
chunk_sub_routine_last = do_finalchunk_sub(
dtype,
varfinal,
dimlastfinalchunk,
acc,
i,
j,
jstart,
last_chunk,
nx,
ny,
arg,
fout,
yj,
out,
)
self.code = f"""
{self.headers}
extern "C" __global__ void GpuConv1DOnDevice(int nx, int ny, {dtype} *out, {dtype} **{arg.id}) {{
// get the index of the current thread
int i = blockIdx.x * blockDim.x + threadIdx.x;
// declare shared mem
extern __shared__ {dtype} yj[];
// load parameter(s)
{param_loc.declare()}
{load_vars(dimsp, indsp, param_loc, args)}
{fout.declare()}
// get the value of variable (index with i)
{xi.declare()}
if (i < nx) {{
{load_vars(dimsx, indsi, xi, args, row_index=i)} // load xi variables from global memory to local thread memory
{use_pragma_unroll()}
for (int k=0; k<{dimout}; k++) {{
out[i*{dimout}+k] = 0.0f;
}}
}}
{acc.declare()}
for (int jstart = 0, tile = 0; jstart < ny; jstart += blockDim.x, tile++) {{
// get the current column
int j = tile * blockDim.x + threadIdx.x;
if (j < ny) {{ // we load yj from device global memory only if j<ny
{load_vars(dimsy, indsj, yjloc, args, row_index=j)} // load yj variables from global memory to shared memory
}}
__syncthreads();
if (i < nx) {{ // we compute x1i only if needed
{dtype} * yjrel = yj; // Loop on the columns of the current block.
for (int jrel = 0; (jrel < {blocksize_chunks}) && (jrel < ny - jstart); jrel++, yjrel += {dimy}) {{
{formula(foutjrel, table)} // Call the function, which outputs results in fout
}}
}}
__syncthreads();
for (int chunk=0; chunk<{nchunks-1}; chunk++) {{
{chunk_sub_routine}
}}
{chunk_sub_routine_last}
}}
}}
"""
| keops-main | keopscore/keopscore/mapreduce/gpu/GpuReduc1D_finalchunks.py |
from keopscore import cuda_block_size
from keopscore.config.chunks import dimchunk
from keopscore.binders.nvrtc.Gpu_link_compile import Gpu_link_compile
from keopscore.formulas.reductions.sum_schemes import *
from keopscore.mapreduce.gpu.GpuAssignZero import GpuAssignZero
from keopscore.mapreduce.MapReduce import MapReduce
from keopscore.utils.code_gen_utils import (
load_vars,
load_vars_chunks,
sizeof,
pointer,
table,
table4,
use_pragma_unroll,
)
from keopscore.mapreduce.Chunk_Mode_Constants import Chunk_Mode_Constants
def do_chunk_sub(
dtype,
red_formula,
fun_chunked_curr,
dimchunk_curr,
dimsx,
dimsy,
indsi,
indsj,
indsi_chunked,
indsj_chunked,
acc,
tile,
i,
j,
jstart,
chunk,
nx,
ny,
arg,
fout,
xi,
yj,
param_loc,
):
chk = Chunk_Mode_Constants(red_formula)
fout_tmp_chunk = c_array(dtype, chk.fun_chunked.dim)
xiloc = c_variable(pointer(dtype), f"({xi.id} + {chk.dimx_notchunked})")
yjloc = c_variable(
pointer(dtype), f"({yj.id} + threadIdx.x * {chk.dimy} + {chk.dimy_notchunked})"
)
load_chunks_routine_i = load_vars_chunks(
indsi_chunked,
dimchunk,
dimchunk_curr,
chk.dim_org,
xiloc,
arg,
chunk,
row_index=i,
)
load_chunks_routine_j = load_vars_chunks(
indsj_chunked,
dimchunk,
dimchunk_curr,
chk.dim_org,
yjloc,
arg,
chunk,
row_index=j,
)
yjrel = c_variable(pointer(dtype), "yjrel")
chktable = table(
chk.nminargs,
dimsx,
dimsy,
chk.dimsp,
indsi,
indsj,
chk.indsp,
xi,
yjrel,
param_loc,
)
foutj = c_variable(pointer(dtype), "foutj")
return f"""
// Starting chunk_sub routine
{fout_tmp_chunk.declare()}
if ({i.id} < {nx.id}) {{
{load_chunks_routine_i}
}}
if (j < ny) {{ // we load yj from device global memory only if j<ny
{load_chunks_routine_j}
}}
__syncthreads();
if ({i.id} < {nx.id}) {{ // we compute only if needed
{dtype} *yjrel = {yj.id}; // Loop on the columns of the current block.
for (int jrel = 0; (jrel < blockDim.x) && (jrel < {ny.id} - jstart); jrel++, yjrel += {chk.dimy}) {{
{dtype} *foutj = {fout.id} + jrel*{chk.fun_chunked.dim};
{fun_chunked_curr(fout_tmp_chunk, chktable)}
{chk.fun_chunked.acc_chunk(foutj, fout_tmp_chunk)}
}}
}}
__syncthreads();
// Finished chunk_sub routine
"""
class GpuReduc1D_chunks(MapReduce, Gpu_link_compile):
# class for generating the final C++ code, Gpu version
AssignZero = GpuAssignZero
def __init__(self, *args):
MapReduce.__init__(self, *args)
Gpu_link_compile.__init__(self)
self.chk = Chunk_Mode_Constants(self.red_formula)
self.dimy = self.chk.dimy
self.blocksize_chunks = min(
cuda_block_size, 1024, 49152 // max(1, self.dimy * sizeof(self.dtype))
)
def get_code(self):
super().get_code()
red_formula = self.red_formula
dtype = self.dtype
dtypeacc = self.dtypeacc
varloader = self.varloader
i = self.i
j = self.j
arg = self.arg
args = self.args
yjrel = c_array(dtype, varloader.dimy, "yjrel")
jreltile = c_variable("int", "(jrel + tile * blockDim.x)")
chk = self.chk
param_loc = c_array(dtype, chk.dimp, "param_loc")
acc = c_array(dtypeacc, chk.dimred, "acc")
sum_scheme = eval(self.sum_scheme_string)(red_formula, dtype, dimred=chk.dimred)
xi = c_array(dtype, chk.dimx, "xi")
fout_chunk = c_array(
dtype, self.blocksize_chunks * chk.dimout_chunk, "fout_chunk"
)
yj = c_variable(pointer(dtype), "yj")
yjloc = c_array(dtype, chk.dimy, f"(yj + threadIdx.x * {chk.dimy})")
fout_chunk_loc = c_variable(
pointer(dtype), f"({fout_chunk.id}+jrel*{chk.dimout_chunk})"
)
tile = c_variable("int", "tile")
nx = c_variable("int", "nx")
ny = c_variable("int", "ny")
jstart = c_variable("int", "jstart")
chunk = c_variable("int", "chunk")
chunk_sub_routine = do_chunk_sub(
dtype,
red_formula,
chk.fun_chunked,
dimchunk,
chk.dimsx,
chk.dimsy,
chk.indsi,
chk.indsj,
chk.indsi_chunked,
chk.indsj_chunked,
acc,
tile,
i,
j,
jstart,
chunk,
nx,
ny,
arg,
fout_chunk,
xi,
yj,
param_loc,
)
last_chunk = c_variable("int", f"{chk.nchunks - 1}")
chunk_sub_routine_last = do_chunk_sub(
dtype,
red_formula,
chk.fun_lastchunked,
chk.dimlastchunk,
chk.dimsx_last,
chk.dimsy_last,
chk.indsi,
chk.indsj,
chk.indsi_lastchunked,
chk.indsj_lastchunked,
acc,
tile,
i,
j,
jstart,
last_chunk,
nx,
ny,
arg,
fout_chunk,
xi,
yj,
param_loc,
)
foutj = c_array(dtype, chk.dimout_chunk, "foutj")
chktable_out = table4(
chk.nminargs + 1,
chk.dimsx,
chk.dimsy,
chk.dimsp,
[chk.dimout_chunk],
chk.indsi,
chk.indsj,
chk.indsp,
[chk.nminargs],
xi,
yjrel,
param_loc,
foutj,
)
fout_tmp = c_array(dtype, chk.dimfout, "fout_tmp")
outi = c_array(dtype, chk.dimout, f"(out + i * {chk.dimout})")
self.code = f"""
{self.headers}
extern "C" __global__ void GpuConv1DOnDevice(int nx, int ny, {dtype} *out, {dtype} **{arg.id}) {{
// get the index of the current thread
int i = blockIdx.x * blockDim.x + threadIdx.x;
// declare shared mem
extern __shared__ {dtype} yj[];
// load parameters variables from global memory to local thread memory
{param_loc.declare()}
{load_vars(chk.dimsp, chk.indsp, param_loc, args)}
{acc.declare()}
{sum_scheme.declare_temporary_accumulator()}
if (i < nx) {{
{red_formula.InitializeReduction(acc)} // acc = 0
{sum_scheme.initialize_temporary_accumulator_first_init()}
}}
{xi.declare()}
{fout_chunk.declare()}
if (i < nx) {{
{load_vars(chk.dimsx_notchunked, chk.indsi_notchunked, xi, args, row_index=i)} // load xi variables from global memory to local thread memory
}}
for (int jstart = 0, tile = 0; jstart < ny; jstart += blockDim.x, tile++) {{
// get the current column
int j = tile * blockDim.x + threadIdx.x;
if (j < ny) {{ // we load yj from device global memory only if j<ny
{load_vars(chk.dimsy_notchunked, chk.indsj_notchunked, yjloc, args, row_index=j)}
}}
__syncthreads();
if (i < nx) {{ // we compute x1i only if needed
for (int jrel = 0; (jrel < blockDim.x) && (jrel < ny - jstart); jrel++) {{
{chk.fun_chunked.initacc_chunk(fout_chunk_loc)}
}}
{sum_scheme.initialize_temporary_accumulator_block_init()}
}}
// looping on chunks (except the last)
{use_pragma_unroll()}
for (int chunk=0; chunk<{chk.nchunks}-1; chunk++) {{
{chunk_sub_routine}
}}
// last chunk
{chunk_sub_routine_last}
if (i < nx) {{
{dtype} * yjrel = yj; // Loop on the columns of the current block.
for (int jrel = 0; (jrel < blockDim.x) && (jrel < ny - jstart); jrel++, yjrel += {chk.dimy}) {{
{dtype} *foutj = fout_chunk + jrel*{chk.dimout_chunk};
{fout_tmp.declare()}
{chk.fun_postchunk(fout_tmp, chktable_out)}
{sum_scheme.accumulate_result(acc, fout_tmp, jreltile)}
}}
{sum_scheme.final_operation(acc)}
}}
__syncthreads();
}}
if (i < nx) {{
{red_formula.FinalizeOutput(acc, outi, i)}
}}
}}
"""
| keops-main | keopscore/keopscore/mapreduce/gpu/GpuReduc1D_chunks.py |
from keopscore.binders.nvrtc.Gpu_link_compile import Gpu_link_compile
from keopscore.mapreduce.gpu.GpuAssignZero import GpuAssignZero
from keopscore.mapreduce.MapReduce import MapReduce
from keopscore.utils.code_gen_utils import (
c_variable,
c_array,
)
class GpuReduc1D(MapReduce, Gpu_link_compile):
# class for generating the final C++ code, Gpu version
AssignZero = GpuAssignZero
def __init__(self, *args):
MapReduce.__init__(self, *args)
Gpu_link_compile.__init__(self)
self.dimy = self.varloader.dimy
def get_code(self):
super().get_code()
red_formula = self.red_formula
dtype = self.dtype
varloader = self.varloader
i = self.i
j = self.j
fout = self.fout
outi = self.outi
acc = self.acc
arg = self.arg
args = self.args
sum_scheme = self.sum_scheme
param_loc = self.param_loc
xi = self.xi
yjloc = c_array(dtype, varloader.dimy, f"(yj + threadIdx.x * {varloader.dimy})")
yjrel = c_array(dtype, varloader.dimy, "yjrel")
table = varloader.table(self.xi, yjrel, self.param_loc)
jreltile = c_variable("int", "(jrel + tile * blockDim.x)")
self.code = f"""
{self.headers}
extern "C" __global__ void GpuConv1DOnDevice(int nx, int ny, {dtype} *out, {dtype} **{arg.id}) {{
// get the index of the current thread
int i = blockIdx.x * blockDim.x + threadIdx.x;
// declare shared mem
extern __shared__ {dtype} yj[];
// load parameters variables from global memory to local thread memory
{param_loc.declare()}
{varloader.load_vars("p", param_loc, args)}
{fout.declare()}
{xi.declare()}
{acc.declare()}
{sum_scheme.declare_temporary_accumulator()}
if (i < nx) {{
{red_formula.InitializeReduction(acc)} // acc = 0
{sum_scheme.initialize_temporary_accumulator_first_init()}
{varloader.load_vars('i', xi, args, row_index=i)} // load xi variables from global memory to local thread memory
}}
for (int jstart = 0, tile = 0; jstart < ny; jstart += blockDim.x, tile++) {{
// get the current column
int j = tile * blockDim.x + threadIdx.x;
if (j < ny) {{ // we load yj from device global memory only if j<ny
{varloader.load_vars("j", yjloc, args, row_index=j)}
}}
__syncthreads();
if (i < nx) {{ // we compute x1i only if needed
{dtype} * yjrel = yj;
{sum_scheme.initialize_temporary_accumulator_block_init()}
for (int jrel = 0; (jrel < blockDim.x) && (jrel < ny - jstart); jrel++, yjrel += {varloader.dimy}) {{
{red_formula.formula(fout, table)} // Call the function, which outputs results in fout
{sum_scheme.accumulate_result(acc, fout, jreltile)}
}}
{sum_scheme.final_operation(acc)}
}}
__syncthreads();
}}
if (i < nx) {{
{red_formula.FinalizeOutput(acc, outi, i)}
}}
}}
"""
| keops-main | keopscore/keopscore/mapreduce/gpu/GpuReduc1D.py |
from keopscore.binders.nvrtc.Gpu_link_compile import Gpu_link_compile
from keopscore.formulas.reductions.sum_schemes import block_sum, kahan_scheme
from keopscore.mapreduce.gpu.GpuAssignZero import GpuAssignZero
from keopscore.mapreduce.MapReduce import MapReduce
from keopscore.utils.code_gen_utils import c_variable, c_array, use_pragma_unroll
from keopscore.utils.misc_utils import KeOps_Error
class GpuReduc2D(MapReduce, Gpu_link_compile):
# class for generating the final C++ code, Gpu version
AssignZero = GpuAssignZero
def __init__(self, *args):
MapReduce.__init__(self, *args)
Gpu_link_compile.__init__(self)
self.dimy = self.varloader.dimy
def get_code(self):
super().get_code()
i = self.i
j = self.j
red_formula = self.red_formula
dtype = self.dtype
dimin = red_formula.dimred
dimout = red_formula.dim
varloader = self.varloader
dtypeacc = self.dtypeacc
acc2 = c_array(dtypeacc, dimin, "acc2")
inloc = c_array(dtype, dimin, f"(in + (tid+y*nx)*{dimin})")
outloc = c_array(dtype, dimout, f"(out+tid*{dimout})")
dimsx = varloader.dimsx
dimsy = varloader.dimsy
dimsp = varloader.dimsp
indsi = varloader.indsi
indsj = varloader.indsj
indsp = varloader.indsp
dimx = sum(dimsx)
dimy = sum(dimsy)
dimp = sum(dimsp)
dimred = red_formula.dimred
dimfout = red_formula.formula.dim
fout = c_array(dtype, dimfout, "fout")
param_loc = c_array(dtype, dimp, "param_loc")
xi = c_array(dtype, dimx, "xi")
sum_scheme = self.sum_scheme
# N.B. To be consistent with the convention used in GpuConv1D, when SUM_SCHEME == BLOCK_SUM=1 we accumulate results in TYPE
# instead of __TYPEACC__ in each block, __TYPEACC__ will be used only to sum up results from each block
if isinstance(sum_scheme, block_sum):
acc = c_array(dtype, dimred, "acc")
elif isinstance(sum_scheme, direct_sum):
acc = c_array(dtypeacc, dimred, "acc")
else:
KeOps_Error("incorrect reduction scheme")
yjloc = c_array(dtype, varloader.dimy, f"(yj + threadIdx.x * {varloader.dimy})")
arg = self.arg
args = self.args
yjrel = c_array(dtype, dimy, "yjrel")
table = varloader.table(self.xi, yjrel, self.param_loc)
jrelloc = c_variable("int", "(blockDim.x*blockIdx.y+jrel)")
tid = c_variable("int", "tid")
self.code = f"""
{self.headers}
extern "C" __global__ void reduce2D({dtype} *in, {dtype} *out, int sizeY, int nx) {{
/* Function used as a final reduction pass in the 2D scheme,
* once the block reductions have been made.
* Takes as input:
* - in, a sizeY * (nx * DIMIN ) array
* - out, an nx * DIMOUT array
*
* Computes, in parallel, the "columnwise"-reduction (which correspond to lines of blocks)
* of *in and stores the result in out.
*/
int tid = blockIdx.x * blockDim.x + threadIdx.x;
/* As shown below, the code that is used to store the block-wise sum
"tmp" in parallel is:
if(i<nx)
for(int k=0; k<DIMX1; k++)
(*px)[blockIdx.y*DIMX1*nx+i*DIMX1+k] = tmp[k];
*/
/* // This code should be a bit more efficient (more parallel) in the case
// of a simple "fully parallel" reduction op such as "sum", "max" or "min"
TYPE res = 0;
if(tid < nx*DIMVECT) {{
for (int i = 0; i < sizeY; i++)
res += in[tid + i*nx*DIMVECT]; // We use "+=" as a reduction op. But it could be anything, really!
// res = in[tid+ nx* DIMVECT];
out[tid] = res;
}}
*/
// However, for now, we use a "vectorized" reduction op.,
// which can also handle non-trivial reductions such as "LogSumExp"
{acc2.declare()}
{red_formula.InitializeReduction(acc2)} // acc = 0
if(tid < nx) {{
for (int y = 0; y < sizeY; y++) {{
{red_formula.ReducePair(acc2, inloc)} // acc += in[(tid+y*nx) *DIMVECT : +DIMVECT];
}}
{red_formula.FinalizeOutput(acc2, outloc, tid)}
}}
}}
extern "C" __global__ void GpuConv2DOnDevice(int nx, int ny, {dtype} *out, {dtype} **{arg.id}) {{
{fout.declare()}
// Load the parameter vector in the Thread Memory, for improved efficiency
{param_loc.declare()}
{varloader.load_vars("p", param_loc, args)} // load parameters variables from global memory to local thread memory
// Weird syntax to create a pointer in shared memory.
extern __shared__ char yj_char[];
{dtype}* const yj = reinterpret_cast<{dtype}*>(yj_char);
// Step 1 : Load in Thread Memory the information needed in the current line ---------------------------
int i = blockIdx.x * blockDim.x + threadIdx.x;
{xi.declare()}
{acc.declare()}
{sum_scheme.tmp_acc.declare()} //# if isinstance(sum_scheme, kahan_scheme) else ""
if(i<nx) {{ // we will compute outi only if i is in the range
{red_formula.InitializeReduction(acc)} // acc = 0
{sum_scheme.tmp_acc.assign(c_zero_float) if isinstance(sum_scheme, kahan_scheme) else ""}
// Load xi from device global memory.
// Remember that we use an interleaved memory scheme where
// xi = [ x1i, x2i, x3i, ... ].
{varloader.load_vars('i', xi, args, row_index=i)} // load xi variables from global memory to local thread memory
}}
// Step 2 : Load in Shared Memory the information needed in the current block of the product -----------
// In the 1D scheme, we use a loop to run through the line.
// In the 2D scheme presented here, the computation is done in parallel wrt both lines and columns.
// Hence, we use "blockId.y" to get our current column number.
int j = blockIdx.y * blockDim.x + threadIdx.x; // Same blockDim in x and y : squared tiles.
if(j<ny) {{ // we load yj from device global memory only if j<ny
{varloader.load_vars("j", yjloc, args, row_index=j)} // load yj variables from global memory to shared memory
}}
// More precisely : the j-th line of py is loaded to yj, at a location which depends on the
// current threadId.
__syncthreads(); // Make sure nobody lags behind
// Step 3 : Once the data is loaded, execute fun --------------------------------------------------------
// N.B.: There's no explicit summation here. Just calls to fun, which *accumulates* the results
// along the line, but does not *have* to use a "+=" as reduction operator.
// In the future, we could provide other reductions: max, min, ... whatever's needed.
if(i<nx) {{ // we compute x1i only if needed
{dtype}* yjrel = yj; // Loop on the columns of the current block.
for(int jrel = 0; (jrel<blockDim.x) && ((blockDim.x*blockIdx.y+jrel)< ny); jrel++, yjrel+={dimy}) {{
{red_formula.formula(fout,table)} // Call the function, which outputs results in fout
{sum_scheme.accumulate_result(acc, fout, jrelloc, hack=True)}
}}
}}
__syncthreads();
// Step 4 : Save the result in global memory -----------------------------------------------------------
// The current thread has computed the "linewise-sum" of a small block of the full Kernel Product
// matrix, which corresponds to KP[ blockIdx.x * blockDim.x : (blockIdx.x+1) * blockDim.x ,
// blockIdx.y * blockDim.x : (blockIdx.y+1) * blockDim.x ]
// We accumulate it in the output array out, which has in fact gridSize.y * nx
// lines of size DIMRED. The final reduction, which "sums over the block lines",
// shall be done in a later step.
if(i<nx) {{
{use_pragma_unroll()}
for(int k=0; k<{dimred}; k++) {{
out[blockIdx.y*{dimred}*nx+i*{dimred}+k] = acc[k];
}}
}}
}}
"""
| keops-main | keopscore/keopscore/mapreduce/gpu/GpuReduc2D.py |
from keopscore.binders.nvrtc.Gpu_link_compile import Gpu_link_compile
from keopscore.mapreduce.gpu.GpuAssignZero import GpuAssignZero
from keopscore.mapreduce.MapReduce import MapReduce
from keopscore.utils.code_gen_utils import (
c_variable,
c_array,
c_include,
)
class GpuReduc1D_ranges(MapReduce, Gpu_link_compile):
# class for generating the final C++ code, Gpu version
AssignZero = GpuAssignZero
def __init__(self, *args):
MapReduce.__init__(self, *args)
Gpu_link_compile.__init__(self)
self.dimy = self.varloader.dimy
def get_code(self):
super().get_code()
red_formula = self.red_formula
dtype = self.dtype
varloader = self.varloader
i = self.i
j = self.j
fout = self.fout
outi = self.outi
acc = self.acc
arg = self.arg
args = self.args
sum_scheme = self.sum_scheme
nvarsi, nvarsj, nvarsp = (
len(self.varloader.Varsi),
len(self.varloader.Varsj),
len(self.varloader.Varsp),
)
nvars = nvarsi + nvarsj + nvarsp
param_loc = self.param_loc
xi = self.xi
yjloc = c_array(dtype, varloader.dimy, f"(yj + threadIdx.x * {varloader.dimy})")
yjrel = c_array(dtype, varloader.dimy, "yjrel")
table = varloader.table(self.xi, yjrel, self.param_loc)
jreltile = c_variable("int", "(jrel + tile * blockDim.x)")
indices_i = c_array("int", nvarsi, "indices_i")
indices_j = c_array("int", nvarsj, "indices_j")
indices_p = c_array("int", nvarsp, "indices_p")
declare_assign_indices_i = "int *indices_i = offsets;" if nvarsi > 0 else ""
declare_assign_indices_j = (
f"int *indices_j = offsets + {nvarsi};" if nvarsj > 0 else ""
)
declare_assign_indices_p = (
f"int *indices_p = offsets + {nvarsi} + {nvarsj};" if nvarsp > 0 else ""
)
starty = c_variable("int", "start_y")
threadIdx_x = c_variable("int", "threadIdx.x")
if dtype == "half2":
self.headers += c_include("cuda_fp16.h")
self.code = f"""
{self.headers}
extern "C" __global__ void GpuConv1DOnDevice_ranges(int nx, int ny, int nbatchdims,
int *offsets_d, int *lookup_d, int *slices_x,
int *ranges_y, {dtype} *out, {dtype} **{arg.id}) {{
int offsets[{nvars}];
{declare_assign_indices_i}
{declare_assign_indices_j}
{declare_assign_indices_p}
if (nbatchdims > 0)
for (int k = 0; k < {nvars}; k++)
offsets[k] = offsets_d[ {nvars} * blockIdx.x + k ];
// Retrieve our position along the laaaaarge [1,~nx] axis: -----------------
int range_id= (lookup_d)[3*blockIdx.x] ;
int start_x = (lookup_d)[3*blockIdx.x+1] ;
int end_x = (lookup_d)[3*blockIdx.x+2] ;
// The "slices_x" vector encodes a set of cutting points in
// the "ranges_y" array of ranges.
// As discussed in the Genred docstring, the first "0" is implicit:
int start_slice = range_id < 1 ? 0 : slices_x[range_id-1];
int end_slice = slices_x[range_id];
// get the index of the current thread
int i = start_x + threadIdx.x;
// declare shared mem
extern __shared__ {dtype} yj[];
// load parameter(s)
{param_loc.declare()}
if (nbatchdims == 0) {{
{varloader.load_vars("p", param_loc, args)}
}} else {{
{varloader.load_vars("p", param_loc, args, offsets=indices_p)}
}}
{fout.declare()}
{xi.declare()}
{acc.declare()}
{sum_scheme.declare_temporary_accumulator()}
if(i<end_x) {{
{red_formula.InitializeReduction(acc)} // acc = 0
{sum_scheme.initialize_temporary_accumulator_first_init()}
if (nbatchdims == 0) {{
{varloader.load_vars('i', xi, args, row_index=i)} // load xi variables from global memory to local thread memory
}} else {{
{varloader.load_vars('i', xi, args, row_index=threadIdx_x, offsets=indices_i)} // Possibly, with offsets as we support broadcasting over batch dimensions
}}
}}
int start_y = ranges_y[2*start_slice], end_y = 0;
for( int index = start_slice ; index < end_slice ; index++ ) {{
if( (index+1 >= end_slice) || (ranges_y[2*index+2] != ranges_y[2*index+1]) ) {{
//start_y = ranges_y[2*index] ;
end_y = ranges_y[2*index+1];
for(int jstart = start_y, tile = 0; jstart < end_y; jstart += blockDim.x, tile++) {{
// get the current column
int j = jstart + threadIdx.x;
if(j<end_y) // we load yj from device global memory only if j<end_y
if (nbatchdims == 0) {{
{varloader.load_vars('j', yjloc, args, row_index=j)} // load yj variables from global memory to shared memory
}} else {{
{varloader.load_vars('j', yjloc, args, row_index=j-starty, offsets=indices_j)} // Possibly, with offsets as we support broadcasting over batch dimensions
}}
__syncthreads();
if(i<end_x) {{ // we compute x1i only if needed
{dtype} * yjrel = yj; // Loop on the columns of the current block.
{sum_scheme.initialize_temporary_accumulator_block_init()}
if (nbatchdims == 0) {{
for(int jrel = 0; (jrel < blockDim.x) && (jrel<end_y-jstart); jrel++, yjrel+={varloader.dimy}) {{
{red_formula.formula(fout,table)} // Call the function, which outputs results in xi[0:DIMX1]
{sum_scheme.accumulate_result(acc, fout, jreltile+starty)}
}}
}} else {{
for(int jrel = 0; (jrel < blockDim.x) && (jrel<end_y-jstart); jrel++, yjrel+={varloader.dimy}) {{
{red_formula.formula(fout,table)} // Call the function, which outputs results in fout
{sum_scheme.accumulate_result(acc, fout, jreltile)}
}}
}}
{sum_scheme.final_operation(acc)}
}}
__syncthreads();
}}
if(index+1 < end_slice)
start_y = ranges_y[2*index+2] ;
}}
}}
if(i<end_x) {{
{red_formula.FinalizeOutput(acc, outi, i)}
}}
}}
"""
| keops-main | keopscore/keopscore/mapreduce/gpu/GpuReduc1D_ranges.py |
from keopscore.binders.nvrtc.Gpu_link_compile import Gpu_link_compile
from keopscore.mapreduce.MapReduce import MapReduce
from keopscore.utils.code_gen_utils import (
c_include,
c_zero_float,
)
class GpuAssignZero(MapReduce, Gpu_link_compile):
# class for generating the final C++ code, Gpu version
def __init__(self, *args):
MapReduce.__init__(self, *args)
Gpu_link_compile.__init__(self)
self.dimy = self.varloader.dimy
def get_code(self):
super().get_code()
outi = self.outi
dtype = self.dtype
arg = self.arg
varloader = self.varloader
if dtype == "half2":
self.headers += c_include("cuda_fp16.h")
self.code = f"""
{self.headers}
extern "C" __global__ void GpuConv1DOnDevice(int nx, int ny, {dtype} *out, {dtype} **{arg.id}) {{
// get the index of the current thread
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < nx) {{
{outi.assign(c_zero_float)}
}}
}}
"""
| keops-main | keopscore/keopscore/mapreduce/gpu/GpuAssignZero.py |
from keopscore import debug_ops_at_exec
from keopscore.binders.cpp.Cpu_link_compile import Cpu_link_compile
from keopscore.mapreduce.cpu.CpuAssignZero import CpuAssignZero
from keopscore.mapreduce.MapReduce import MapReduce
from keopscore.utils.code_gen_utils import c_include
import keopscore
class CpuReduc(MapReduce, Cpu_link_compile):
"""
class for generating the final C++ code, Cpu version
"""
AssignZero = CpuAssignZero
def __init__(self, *args):
MapReduce.__init__(self, *args)
Cpu_link_compile.__init__(self)
self.dimy = self.varloader.dimy
def get_code(self):
super().get_code()
i = self.i
j = self.j
red_formula = self.red_formula
fout = self.fout
outi = self.outi
acc = self.acc
arg = self.arg
args = self.args
table = self.varloader.direct_table(args, i, j)
sum_scheme = self.sum_scheme
headers = ["cmath", "stdlib.h"]
if keopscore.config.config.use_OpenMP:
headers.append("omp.h")
if debug_ops_at_exec:
headers.append("iostream")
self.headers += c_include(*headers)
self.code = f"""
{self.headers}
template < typename TYPE >
int CpuConv_{self.gencode_filename}(int nx, int ny, TYPE* out, TYPE **{arg.id}) {{
#pragma omp parallel for
for (int i = 0; i < nx; i++) {{
{fout.declare()}
{acc.declare()}
{sum_scheme.declare_temporary_accumulator()}
{red_formula.InitializeReduction(acc)}
{sum_scheme.initialize_temporary_accumulator()}
for (int j = 0; j < ny; j++) {{
{red_formula.formula(fout,table)}
{sum_scheme.accumulate_result(acc, fout, j)}
{sum_scheme.periodic_accumulate_temporary(acc, j)}
}}
{sum_scheme.final_operation(acc)}
{red_formula.FinalizeOutput(acc, outi, i)}
}}
return 0;
}}
"""
self.code += f"""
#include "stdarg.h"
#include <vector>
template < typename TYPE >
int launch_keops_{self.gencode_filename}(int nx, int ny, int tagI, TYPE *out, TYPE **arg) {{
if (tagI==1) {{
int tmp = ny;
ny = nx;
nx = tmp;
}}
return CpuConv_{self.gencode_filename}< TYPE >(nx, ny, out, arg);
}}
template < typename TYPE >
int launch_keops_cpu_{self.gencode_filename}(int dimY,
int nx,
int ny,
int tagI,
int tagZero,
int use_half,
int dimred,
int use_chunk_mode,
std::vector< int > indsi, std::vector< int > indsj, std::vector< int > indsp,
int dimout,
std::vector< int > dimsx, std::vector< int > dimsy, std::vector< int > dimsp,
int **ranges,
std::vector< int > shapeout, TYPE *out,
TYPE **arg,
std::vector< std::vector< int > > argshape) {{
return launch_keops_{self.gencode_filename} < TYPE >(nx, ny, tagI, out, arg);
}}
"""
| keops-main | keopscore/keopscore/mapreduce/cpu/CpuReduc.py |
from .CpuReduc_ranges import CpuReduc_ranges
from .CpuReduc import CpuReduc
from .CpuAssignZero import CpuAssignZero
| keops-main | keopscore/keopscore/mapreduce/cpu/__init__.py |
from keopscore import debug_ops_at_exec
from keopscore.binders.cpp.Cpu_link_compile import Cpu_link_compile
from keopscore.mapreduce.MapReduce import MapReduce
from keopscore.utils.code_gen_utils import (
c_include,
c_zero_float,
)
import keopscore
class CpuAssignZero(MapReduce, Cpu_link_compile):
# class for generating the final C++ code, Cpu version
def __init__(self, *args):
MapReduce.__init__(self, *args)
Cpu_link_compile.__init__(self)
self.dimy = self.varloader.dimy
def get_code(self):
super().get_code()
outi = self.outi
dtype = self.dtype
arg = self.arg
args = self.args
headers = ["stdlib.h"]
if keopscore.config.config.use_OpenMP:
headers.append("omp.h")
if debug_ops_at_exec:
headers.append("iostream")
self.headers += c_include(*headers)
self.code = f"""
{self.headers}
template < typename TYPE >
int AssignZeroCpu_{self.gencode_filename}(int nx, int ny, TYPE* out, TYPE **{arg.id}) {{
#pragma omp parallel for
for (int i = 0; i < nx; i++) {{
{outi.assign(c_zero_float)}
}}
return 0;
}}
#include "stdarg.h"
#include <vector>
template < typename TYPE >
int launch_keops_{self.gencode_filename}(int nx, int ny, int tagI, TYPE *out, TYPE **arg) {{
if (tagI==1) {{
int tmp = ny;
ny = nx;
nx = tmp;
}}
return AssignZeroCpu_{self.gencode_filename}< TYPE > (nx, ny, out, arg);
}}
template < typename TYPE >
int launch_keops_cpu_{self.gencode_filename}(int dimY,
int nx,
int ny,
int tagI,
int tagZero,
int use_half,
int dimred,
int use_chunk_mode,
std::vector< int > indsi, std::vector< int > indsj, std::vector< int > indsp,
int dimout,
std::vector< int > dimsx, std::vector< int > dimsy, std::vector< int > dimsp,
int **ranges,
std::vector< int > shapeout, TYPE *out,
TYPE **arg,
std::vector< std::vector< int > > argshape) {{
return launch_keops_{self.gencode_filename}< TYPE > (nx, ny, tagI, out, arg);
}}
"""
| keops-main | keopscore/keopscore/mapreduce/cpu/CpuAssignZero.py |
from keopscore import debug_ops_at_exec
from keopscore.binders.cpp.Cpu_link_compile import Cpu_link_compile
from keopscore.mapreduce.cpu.CpuAssignZero import CpuAssignZero
from keopscore.mapreduce.MapReduce import MapReduce
from keopscore.utils.code_gen_utils import (
c_variable,
c_array,
c_include,
)
import keopscore
class CpuReduc_ranges(MapReduce, Cpu_link_compile):
# class for generating the final C++ code, Cpu version
AssignZero = CpuAssignZero
def __init__(self, *args):
MapReduce.__init__(self, *args)
Cpu_link_compile.__init__(self)
self.dimy = self.varloader.dimy
def get_code(self):
super().get_code()
i = self.i
j = self.j
dtype = self.dtype
red_formula = self.red_formula
fout = self.fout
outi = self.outi
acc = self.acc
acctmp = self.acctmp
arg = self.arg
args = self.args
nargs = len(args)
xi = self.xi
yj = c_array(dtype, self.varloader.dimy, "yj")
param_loc = self.param_loc
varloader = self.varloader
table = varloader.table(xi, yj, param_loc)
nvarsi, nvarsj, nvarsp = (
len(self.varloader.Varsi),
len(self.varloader.Varsj),
len(self.varloader.Varsp),
)
tagHostDevice, tagCpuGpu, tag1D2D = (
self.tagHostDevice,
self.tagCpuGpu,
self.tag1D2D,
)
sum_scheme = self.sum_scheme
indices_i = c_array("int", nvarsi, "indices_i")
indices_j = c_array("int", nvarsj, "indices_j")
indices_p = c_array("int", nvarsp, "indices_p")
imstartx = c_variable("int", "i-start_x")
jmstarty = c_variable("int", "j-start_y")
headers = ["cmath", "stdlib.h"]
if keopscore.config.config.use_OpenMP:
headers.append("omp.h")
if debug_ops_at_exec:
headers.append("iostream")
self.headers += c_include(*headers)
self.code = f"""
{self.headers}
#define do_keops_checks 0
#if do_keops_checks
#include <string>
#include <iostream>
#endif
#if do_keops_checks
#define Error_msg_no_cuda "[KeOps] This KeOps shared object has been compiled without cuda support: - 1) to perform computations on CPU, simply set tagHostDevice to 0 - 2) to perform computations on GPU, please recompile the formula with a working version of cuda."
void keops_error(std::string message) {{
throw std::runtime_error(message);
}}
#endif
#if do_keops_checks
void check_nargs(int nargs, int nminargs) {{
if(nargs<nminargs) {{
keops_error("[KeOps] : not enough input arguments");
}}
}}
#endif
#include "include/Sizes.h"
#include "include/ranges_utils.h"
#include "include/Ranges.h"
template< typename TYPE>
int CpuConv_ranges_{self.gencode_filename}(int nx, int ny,
int nbatchdims, int* shapes,
std::vector< int > indsi, std::vector< int > indsj, std::vector< int > indsp,
int nranges_x, int nranges_y, int **ranges,
TYPE* out, TYPE **{arg.id}) {{
int sizei = indsi.size();
int sizej = indsj.size();
int sizep = indsp.size();
// Separate and store the shapes of the "i" and "j" variables + parameters --------------
//
// shapes is an array of size (1+nargs)*(nbatchdims+3), which looks like:
// [ A, .., B, M, N, D_out] -> output
// [ A, .., B, M, 1, D_1 ] -> "i" variable
// [ A, .., B, 1, N, D_2 ] -> "j" variable
// [ A, .., B, 1, 1, D_3 ] -> "parameter"
// [ A, .., 1, M, 1, D_4 ] -> N.B.: we support broadcasting on the batch dimensions!
// [ 1, .., 1, M, 1, D_5 ] -> (we'll just ask users to fill in the shapes with *explicit* ones)
int shapes_i[sizei * (nbatchdims + 1)], shapes_j[sizej * (nbatchdims + 1)], shapes_p[sizep * (nbatchdims + 1)];
// First, we fill shapes_i with the "relevant" shapes of the "i" variables,
// making it look like, say:
// [ A, .., B, M]
// [ A, .., 1, M]
// [ A, .., A, M]
// Then, we do the same for shapes_j, but with "N" instead of "M".
// And finally for the parameters, with "1" instead of "M".
fill_shapes(nbatchdims, shapes, shapes_i, shapes_j, shapes_p, {red_formula.tagJ}, indsi, indsj, indsp);
// Actual for-for loop -----------------------------------------------------
{param_loc.declare()}
{varloader.load_vars("p", param_loc, args)} // If nbatchdims == 0, the parameters are fixed once and for all
// Set the output to zero, as the ranges may not cover the full output -----
{acctmp.declare()} // __TYPEACC__ acctmp[DIMRED];
for (int i = 0; i < nx; i++) {{
{red_formula.InitializeReduction(acctmp)}
{red_formula.FinalizeOutput(acctmp, outi, i)}
}}
// N.B.: In the following code, we assume that the x-ranges do not overlap.
// Otherwise, we'd have to assume that DIMRED == DIMOUT
// or allocate a buffer of size nx * DIMRED. This may be done in the future.
// Cf. reduction.h:
// FUN::tagJ = 1 for a reduction over j, result indexed by i
// FUN::tagJ = 0 for a reduction over i, result indexed by j
int nranges = {red_formula.tagJ} ? nranges_x : nranges_y;
int* ranges_x = {red_formula.tagJ} ? ranges[0] : ranges[3];
int* slices_x = {red_formula.tagJ} ? ranges[1] : ranges[4];
int* ranges_y = {red_formula.tagJ} ? ranges[2] : ranges[5];
int indices_i[sizei], indices_j[sizej], indices_p[sizep]; // Buffers for the "broadcasted indices"
for (int k = 0; k < sizei; k++) {{ indices_i[k] = 0; }} // Fill the "offsets" with zeroes,
for (int k = 0; k < sizej; k++) {{ indices_j[k] = 0; }} // the default value when nbatchdims == 0.
for (int k = 0; k < sizep; k++) {{ indices_p[k] = 0; }}
for (int range_index = 0; range_index < nranges; range_index++) {{
int start_x = ranges_x[2 * range_index];
int end_x = ranges_x[2 * range_index + 1];
int start_slice = (range_index < 1) ? 0 : slices_x[range_index - 1];
int end_slice = slices_x[range_index];
// If needed, compute the "true" start indices of the range, turning
// the "abstract" index start_x into an array of actual "pointers/offsets" stored in indices_i:
if (nbatchdims > 0) {{
vect_broadcast_index(start_x, nbatchdims, sizei, shapes, shapes_i, indices_i);
// And for the parameters, too:
vect_broadcast_index(range_index, nbatchdims, sizep, shapes, shapes_p, indices_p);
{varloader.load_vars("p", param_loc, args, offsets=indices_p)} // Load the paramaters, once per tile
}}
#pragma omp parallel for
for (int i = start_x; i < end_x; i++) {{
{xi.declare()}
{yj.declare()}
{fout.declare()}
{acc.declare()}
{sum_scheme.declare_temporary_accumulator()}
if (nbatchdims == 0) {{
{varloader.load_vars("i", xi, args, row_index=i)}
}} else {{
{varloader.load_vars("i", xi, args, row_index=imstartx, offsets=indices_i)}
}}
{red_formula.InitializeReduction(acc)}
{sum_scheme.initialize_temporary_accumulator()}
for (int slice = start_slice; slice < end_slice; slice++) {{
int start_y = ranges_y[2 * slice];
int end_y = ranges_y[2 * slice + 1];
// If needed, compute the "true" start indices of the range, turning
// the "abstract" index start_y into an array of actual "pointers/offsets" stored in indices_j:
if (nbatchdims > 0) {{
vect_broadcast_index(start_y, nbatchdims, sizej, shapes, shapes_j, indices_j);
}}
if (nbatchdims == 0) {{
for (int j = start_y; j < end_y; j++) {{
{varloader.load_vars("j", yj, args, row_index=j)}
{red_formula.formula(fout,table)}
{sum_scheme.accumulate_result(acc, fout, j)}
}}
}} else {{
for (int j = start_y; j < end_y; j++) {{
{varloader.load_vars("j", yj, args, row_index=jmstarty, offsets=indices_j)}
{red_formula.formula(fout,table)}
{sum_scheme.accumulate_result(acc, fout, jmstarty)}
}}
}}
}}
{sum_scheme.final_operation(acc)}
{red_formula.FinalizeOutput(acc, outi, i)}
}}
}}
return 0;
}}
"""
self.code += f"""
#include "stdarg.h"
#include <vector>
template < typename TYPE >
int launch_keops_{self.gencode_filename}(int nx, int ny,
int tagI, int use_half, int dimred,
int use_chunk_mode,
std::vector< int > indsi, std::vector< int > indsj, std::vector< int > indsp,
int dimout,
std::vector< int > dimsx, std::vector< int > dimsy, std::vector< int > dimsp,
int **ranges,
TYPE *out, int nargs, TYPE** arg,
std::vector<std::vector< int >> argshape) {{
Sizes< TYPE > SS (nargs, arg, argshape, nx, ny,tagI, use_half,
dimout,
indsi, indsj, indsp,
dimsx, dimsy, dimsp
);
if (use_half)
SS.switch_to_half2_indexing();
Ranges < TYPE > RR(SS, ranges);
nx = SS.nx;
ny = SS.ny;
if (tagI==1) {{
int tmp = ny;
ny = nx;
nx = tmp;
std::vector< int > tmp_v;
tmp_v = indsj;
indsj = indsi;
indsi = tmp_v;
tmp_v = dimsy;
dimsy = dimsx;
dimsx = tmp_v;
}}
return CpuConv_ranges_{self.gencode_filename}< TYPE> (nx, ny, SS.nbatchdims, SS.shapes,
indsi, indsj, indsp,
RR.nranges_x, RR.nranges_y, RR.castedranges,
out, arg);
}}
template < typename TYPE >
int launch_keops_cpu_{self.gencode_filename}(int dimY,
int nx,
int ny,
int tagI,
int tagZero,
int use_half,
int dimred,
int use_chunk_mode,
std::vector< int > indsi, std::vector< int > indsj, std::vector< int > indsp,
int dimout,
std::vector< int > dimsx, std::vector< int > dimsy, std::vector< int > dimsp,
int **ranges,
std::vector< int > shapeout, TYPE *out,
TYPE **arg,
std::vector< std::vector< int > > argshape) {{
return launch_keops_{self.gencode_filename}< TYPE >(nx,
ny,
tagI,
use_half,
dimred,
use_chunk_mode,
indsi, indsj, indsp,
dimout,
dimsx, dimsy, dimsp,
ranges,
out,
argshape.size(),
arg,
argshape);
}}
"""
| keops-main | keopscore/keopscore/mapreduce/cpu/CpuReduc_ranges.py |
from keopscore.utils.code_gen_utils import VectApply
from keopscore.formulas.Operation import Operation
from keopscore.utils.misc_utils import KeOps_Error
class VectorizedScalarOp(Operation):
# class for operations that are vectorized or broadcasted
# scalar operations,
# such as Exp(f), Cos(f), Mult(f,g), Subtract(f,g), etc.
def __init__(self, *args, params=()):
dims = set(arg.dim for arg in args)
if len(dims) > 2 or (len(dims) == 2 and min(dims) != 1):
KeOps_Error("dimensions are not compatible for VectorizedScalarOp")
super().__init__(*args, params=params)
@property
def dim(self):
# dim gives the output dimension of the operation,
# here it is the same as the output dimension of the child operation
return max(child.dim for child in self.children)
def Op(self, out, table, *args):
# Atomic evaluation of the operation : it consists in a simple
# for loop around the call to the correponding scalar operation
return VectApply(self.ScalarOp, out, *args)
def ScalarOp(self, out, *args):
# returns the atomic piece of c++ code to evaluate the function on arg and return
# the result in out
return out.assign(type(self).ScalarOpFun(*args, *self.params))
def DiffT(self, v, gradin):
derivatives = self.Derivative(*self.children, *self.params)
if len(self.children) == 1:
derivatives = (derivatives,)
return sum(f.DiffT(v, gradin * df) for f, df in zip(self.children, derivatives))
def Derivative(self):
pass
@property
def is_chunkable(self):
return all(child.is_chunkable for child in self.children)
def chunked_version(self, dimchk):
return type(self)(
*(
(child if child.dim == 1 else child.chunked_version(dimchk))
for child in self.children
),
*self.params
)
def chunked_vars(self, cat):
res = set()
for child in self.children:
if child.dim != 1:
res = set.union(res, set(child.chunked_vars(cat)))
return list(res)
def notchunked_vars(self, cat):
res = set()
for child in self.children:
if child.dim == 1:
res = set.union(res, set(child.Vars(cat)))
else:
res = set.union(res, set(child.notchunked_vars(cat)))
return list(res)
enable_test = True
| keops-main | keopscore/keopscore/formulas/VectorizedScalarOp.py |
keops-main | keopscore/keopscore/formulas/checks.py |
|
from .complex import *
from .maths import *
from .reductions import *
from .variables import *
from .autodiff import *
| keops-main | keopscore/keopscore/formulas/__init__.py |
from keopscore.utils.code_gen_utils import new_c_varname, c_array
from keopscore.utils.Tree import Tree
from keopscore import debug_ops, debug_ops_at_exec
from keopscore.utils.misc_utils import KeOps_Error
###################
## Base class
###################
class Operation(Tree):
"""Base class for all keops building block operations in a formula"""
def __init__(self, *args, params=()):
# *args are other instances of Operation, they are the child operations of self
self.children = args
self.params = params
# The variables in the current formula is the union of the variables in the child operations.
# Note that this requires implementing properly __eq__ and __hash__ methods in Var class.
# N.B. We need to sort according to ind.
set_vars = (
set.union(*(set(arg.Vars_) for arg in args)) if len(args) > 0 else set()
)
self.Vars_ = sorted(list(set_vars), key=lambda v: v.ind)
def Vars(self, cat="all"):
# if cat=="all", returns the list of all variables in a formula, stored in self.Vars_
# if cat is an integer between 0 and 2, returns the list of variables v such that v.cat=cat
if cat == "all":
return self.Vars_
else:
res = []
for v in self.Vars_:
if v.cat == cat:
res.append(v)
return res
def replace(self, old, new):
# replace all occurences of subformula old by new in self.
if self == old:
return new
else:
new_children = [child.replace(old, new) for child in self.children]
return type(self)(*new_children, *self.params)
def __call__(self, out, table):
"""returns the C++ code string corresponding to the evaluation of the formula
- out is a c_variable in which the result of the evaluation is stored
- table is the list of c_variables corresponding to actual local variables
required for evaluation : each Var(ind,*,*) corresponds to table[ind]"""
from keopscore.formulas.variables.Var import Var
string = f"\n{{\n// Starting code block for {self.__repr__()}.\n\n"
if debug_ops:
print(f"Building code block for {self.__repr__()}")
print("out=", out)
print("dim of out : ", out.dim)
print("table=", table)
for v in table:
print(f"dim of {v} : ", v.dim)
if debug_ops_at_exec:
string += f'printf("\\n\\nComputing {self.__repr__()} :\\n");\n'
args = []
# Evaluation of the child operations
for child in self.children:
if isinstance(child, Var):
# if the child of the operation is a Var, we do not need to evaluate it,
# we simply record the corresponding c_variable
arg = table[child.ind]
else:
# otherwise, we need to evaluate the child operation.
# We first create a new c_array to store the result of the child operation.
# This c_array must have a unique name in the code, to avoid conflicts
# when we will recursively evaluate nested operations.
template_string_id = "out_" + child.string_id.lower()
arg_name = new_c_varname(template_string_id)
arg = c_array(out.dtype, child.dim, arg_name)
# Now we append into string the C++ code to declare the array
string += f"{arg.declare()}\n"
# Now we evaluate the child operation and append the result into string
string += child(arg, table)
args.append(arg)
# Finally, evaluation of the operation itself
string += self.Op(out, table, *args)
# some debugging helper :
if debug_ops_at_exec:
for arg in args:
string += arg.c_print
string += out.c_print
string += f'printf("\\n\\n");\n'
if debug_ops:
print(f"Finished building code block for {self.__repr__()}")
string += f"\n\n// Finished code block for {self.__repr__()}.\n}}\n\n"
return string
def __mul__(self, other):
"""f*g redirects to Mult(f,g)"""
from keopscore.formulas.maths.Mult import Mult
return Mult(self, int2Op(other))
def __rmul__(self, other):
from keopscore.formulas.maths.Mult import Mult
return Mult(int2Op(other), self)
def __truediv__(self, other):
"""f/g redirects to Divide(f,g)"""
from keopscore.formulas.maths.Divide import Divide
return Divide(self, int2Op(other))
def __rtruediv__(self, other):
if other == 1:
from keopscore.formulas.maths.Inv import Inv
return Inv(self)
else:
return int2Op(other) / self
def __add__(self, other):
"""f+g redirects to Add(f,g)"""
from keopscore.formulas.maths.Add import Add
return Add(self, int2Op(other))
def __radd__(self, other):
"""f+g redirects to Add(f,g)"""
return int2Op(other) + self
def __sub__(self, other):
"""f-g redirects to Subtract(f,g)"""
from keopscore.formulas.maths.Subtract import Subtract
return Subtract(self, int2Op(other))
def __rsub__(self, other):
"""f-g redirects to Subtract(f,g)"""
return int2Op(other) - self
def __neg__(self):
"""-f redirects to Minus(f)"""
from keopscore.formulas.maths.Minus import Minus
return Minus(self)
def __pow__(self, other):
if other == 2:
"""f**2 redirects to Square(f)"""
from keopscore.formulas.maths.Square import Square
return Square(self)
elif isinstance(other, int):
"""f**m with m integer redirects to Pow(f,m)"""
from keopscore.formulas.maths.Pow import Pow
return Pow(self, other)
else:
from keopscore.formulas.maths.Powf import Powf
raise Powf(self, other)
def __or__(self, other):
"""f|g redirects to Scalprod(f,g)"""
from keopscore.formulas.maths.Scalprod import Scalprod
return Scalprod(self, other)
def __eq__(self, other):
return (
type(self) == type(other)
and self.children == other.children
and self.params == other.params
)
def Op(self, out, table, param):
pass
def chunked_version(self, dimchk):
return None
@property
def is_chunkable(self):
return False
def chunked_formulas(self, dimchk):
res = []
for child in self.children:
res += child.chunked_formulas(dimchk)
return res
@property
def num_chunked_formulas(self):
return sum([child.num_chunked_formulas for child in self.children])
def post_chunk_formula(self, ind):
args = []
for child in self.children:
args.append(child.post_chunk_formula(ind))
ind += child.num_chunked_formulas
return type(self)(*args, *self.params)
enable_test = False
def int2Op(x):
if isinstance(x, int):
from keopscore.formulas.variables.IntCst import IntCst
return IntCst(x)
elif isinstance(x, Operation):
return x
else:
KeOps_Error("invalid type : " + str(type(x)))
##########################
##### Broadcast ####
##########################
# N.B. this is used internally
def Broadcast(arg, dim):
from keopscore.formulas.maths import SumT
if arg.dim == dim or dim == 1:
return arg
elif arg.dim == 1:
return SumT(arg, dim)
else:
KeOps_Error("dimensions are not compatible for Broadcast operation")
| keops-main | keopscore/keopscore/formulas/Operation.py |
import ast, inspect
import keopscore.formulas
from keopscore.utils.code_gen_utils import get_hash_name
from keopscore.formulas.reductions import *
from keopscore.formulas.maths import *
from keopscore.formulas.complex import *
from keopscore.formulas.variables import *
from keopscore.formulas.autodiff import *
class GetReduction:
library = {}
def __new__(self, red_formula_string, aliases=[]):
string_id_hash = get_hash_name(red_formula_string, aliases)
if string_id_hash in GetReduction.library:
return GetReduction.library[string_id_hash]
else:
self.check_formula(red_formula_string)
aliases_dict = {}
for alias in aliases:
self.check_formula(alias)
if "=" in alias:
varname, var = alias.split("=")
aliases_dict[varname] = eval(var)
reduction = eval(red_formula_string, globals(), aliases_dict)
GetReduction.library[string_id_hash] = reduction
return reduction
@staticmethod
def check_formula(string):
formula_class = dict(inspect.getmembers(keopscore.formulas))
parsed = ast.parse(string)
for node in ast.walk(parsed):
if isinstance(node, ast.Call) and (
node.func.id not in formula_class.keys()
):
print(node.func.id)
# raise NotImplementedError
| keops-main | keopscore/keopscore/formulas/GetReduction.py |
from keopscore.formulas.Operation import Operation
from keopscore.formulas.variables.Var import Var
from keopscore.config.chunks import enable_chunk, dim_treshold_chunk, specdims_use_chunk
class Chunkable_Op(Operation):
def chunked_version(self, dimchk):
chunked_args = [child.chunked_version(dimchk) for child in self.children]
if self.params == ():
return type(self)(*chunked_args)
else:
return type(self)(*chunked_args, params=self.params)
def chunked_vars(self, cat):
res = set()
for child in self.children:
res = set.union(res, set(child.chunked_vars(cat)))
return list(res)
def notchunked_vars(self, cat):
return []
@property
def use_chunk(self):
test = enable_chunk & all(child.is_chunkable for child in self.children)
child = self.children[0]
subtest = (child.dim >= dim_treshold_chunk) | (child.dim in specdims_use_chunk)
test &= subtest
return test
def chunked_formula(self, dimchk):
if self.use_chunk:
return dict(
formula=self.chunked_version(dimchk), dim_org=self.children[0].dim
)
else:
return None
def chunked_formulas(self, dimchk):
chk_f = self.chunked_formula(dimchk)
res = [chk_f] if chk_f is not None else []
for child in self.children:
res += child.chunked_formulas(dimchk)
return res
@property
def num_chunked_formulas(self):
return (
sum(child.num_chunked_formulas for child in self.children) + self.use_chunk
)
def post_chunk_formula(self, ind):
if self.use_chunk:
return Var(ind, 1, 3)
else:
return type(self)(
*(child.post_chunk_formula(ind) for child in self.children),
params=self.params
)
| keops-main | keopscore/keopscore/formulas/Chunkable_Op.py |
from keopscore.utils.code_gen_utils import ComplexVectApply
from keopscore.formulas.Operation import Operation
from keopscore.utils.misc_utils import KeOps_Error
class VectorizedComplexScalarOp(Operation):
# class for operations that are vectorized or broadcasted
# complex scalar operations,
# such as ComplexExp(f), ComplexMult(f), ComplexAdd(f,g), etc.
def __init__(self, *args, params=()):
dims = set(arg.dim for arg in args)
if max(dims) % 2 != 0 or len(dims) > 2 or (len(dims) == 2 and min(dims) != 2):
KeOps_Error("dimensions are not compatible for VectorizedComplexScalarOp")
super().__init__(*args, params=params)
@property
def dim(self):
# dim gives the output dimension of the operation,
# here it is the same as the output dimension of the child operation
return max(child.dim for child in self.children)
def Op(self, out, table, *args):
# Atomic evaluation of the operation : it consists in a simple
# for loop around the call to the correponding scalar operation
return ComplexVectApply(self.ScalarOp, out, *args)
| keops-main | keopscore/keopscore/formulas/VectorizedComplexScalarOp.py |
from .Grad import Grad
from .Grad_WithSavedForward import Grad_WithSavedForward
| keops-main | keopscore/keopscore/formulas/autodiff/__init__.py |
# same as Grad with additional saved forward variable. This is only used for taking gradients of reductions operations.
def Grad_WithSavedForward(red_formula, v, gradin, f0):
return red_formula.DiffT(v, gradin, f0)
| keops-main | keopscore/keopscore/formulas/autodiff/Grad_WithSavedForward.py |
from keopscore.formulas import Var
from keopscore.utils.code_gen_utils import GetInds
from keopscore.utils.misc_utils import KeOps_Error
# /////////////////////////////////////////////////////////////
# /// GRADIENT OPERATOR : Grad< F, V, Gradin > ////
# /////////////////////////////////////////////////////////////
# Defines [\partial_V F].gradin function
# Symbolic differentiation is a straightforward recursive operation,
# provided that the operators have implemented their DiffT "compiler methods":
def Grad(formula, v, gradin=None):
if gradin is None:
if v.cat == 2:
KeOps_Error("not implemented")
inds = GetInds(formula.Vars_)
ind = 1 + max(inds) if len(inds) > 0 else 0
dim = formula.dim
cat = 1 - v.cat
gradin = Var(ind, dim, cat)
return formula.DiffT(v, gradin)
| keops-main | keopscore/keopscore/formulas/autodiff/Grad.py |
from keopscore.formulas.Operation import Operation
from keopscore.utils.code_gen_utils import c_for_loop
from keopscore.formulas.complex.Real2Complex import Real2Complex
from keopscore.formulas.complex.ComplexMult import ComplexMult
from keopscore.utils.misc_utils import KeOps_Error
# /////////////////////////////////////////////////////////////////////////
# //// ComplexRealScal ////
# /////////////////////////////////////////////////////////////////////////
class ComplexRealScal_Impl(Operation):
string_id = "ComplexRealScal"
def __init__(self, f, g):
if f.dim != 1:
KeOps_Error("Dimension of F must be 1")
if g.dim % 2 != 0:
KeOps_Error("Dimension of G must be even")
self.dim = g.dim
super().__init__(f, g)
def Op(self, out, table, inF, inG):
forloop, i = c_for_loop(0, self.dim, 2, pragma_unroll=True)
body = out[i].assign(inF[0] * inG[i])
body += out[i + 1].assign(inF[0] * inG[i + 1])
return forloop(body)
def DiffT(self, v, gradin):
f, g = self.children
AltFormula = ComplexMult(Real2Complex(f), g)
return AltFormula.DiffT(v, gradin)
def ComplexRealScal(f, g):
return ComplexRealScal_Impl(f, g) if f.dim == 1 else ComplexRealScal_Impl(g, f)
| keops-main | keopscore/keopscore/formulas/complex/ComplexRealScal.py |
from keopscore.formulas.VectorizedComplexScalarOp import VectorizedComplexScalarOp
from keopscore.utils.code_gen_utils import (
c_for_loop,
new_c_varname,
c_variable,
)
from keopscore.utils.math_functions import keops_exp, keops_cos, keops_sin
from keopscore.utils.code_gen_utils import c_variable
from keopscore.formulas.complex.ComplexReal import ComplexReal
from keopscore.formulas.complex.ComplexImag import ComplexImag
from keopscore.formulas.complex.Real2Complex import Real2Complex
from keopscore.formulas.complex.Imag2Complex import Imag2Complex
from keopscore.formulas.maths.Exp import Exp
from keopscore.formulas.maths.Cos import Cos
from keopscore.formulas.maths.Sin import Sin
# /////////////////////////////////////////////////////////////////////////
# //// ComplexExp ////
# /////////////////////////////////////////////////////////////////////////
class ComplexExp(VectorizedComplexScalarOp):
string_id = "ComplexExp"
def ScalarOp(self, out, inF):
r = c_variable(out.dtype, new_c_varname("r"))
string = r.declare_assign(keops_exp(inF[0]))
string += out[0].assign(r * keops_cos(inF[1]))
string += out[1].assign(r * keops_sin(inF[1]))
return string
# building equivalent formula for autodiff
def DiffT(self, v, gradin):
f = self.children[0]
AltAbs = Exp(ComplexReal(f))
AltReal = AltAbs * Cos(ComplexImag(f))
AltImag = AltAbs * Sin(ComplexImag(f))
AltFormula = Real2Complex(AltReal) + Imag2Complex(AltImag)
return AltFormula.DiffT(v, gradin)
| keops-main | keopscore/keopscore/formulas/complex/ComplexExp.py |
from keopscore.formulas.Operation import Operation
from keopscore.utils.code_gen_utils import c_zero_float, c_for_loop
# /////////////////////////////////////////////////////////////////////////
# //// Imag2Complex ////
# /////////////////////////////////////////////////////////////////////////
class Imag2Complex(Operation):
string_id = "Imag2Complex"
def __init__(self, f):
self.dim = 2 * f.dim
super().__init__(f)
def Op(self, out, table, inF):
forloop, i = c_for_loop(0, self.dim, 2, pragma_unroll=True)
body = out[i].assign(c_zero_float)
body += out[i + 1].assign(inF[i / 2])
return forloop(body)
def DiffT(self, v, gradin):
from keopscore.formulas.complex.ComplexImag import ComplexImag
f = self.children[0]
return f.DiffT(v, ComplexImag(gradin))
| keops-main | keopscore/keopscore/formulas/complex/Imag2Complex.py |
from keopscore.formulas.Operation import Operation
from keopscore.utils.code_gen_utils import c_zero_float, c_for_loop
# /////////////////////////////////////////////////////////////////////////
# //// Real2Complex ////
# /////////////////////////////////////////////////////////////////////////
class Real2Complex(Operation):
string_id = "Real2Complex"
def __init__(self, f):
self.dim = 2 * f.dim
super().__init__(f)
def Op(self, out, table, inF):
forloop, i = c_for_loop(0, self.dim, 2, pragma_unroll=True)
body = out[i].assign(inF[i / 2])
body += out[i + 1].assign(c_zero_float)
return forloop(body)
def DiffT(self, v, gradin):
from keopscore.formulas.complex.ComplexReal import ComplexReal
f = self.children[0]
return f.DiffT(v, ComplexReal(gradin))
| keops-main | keopscore/keopscore/formulas/complex/Real2Complex.py |
from keopscore.formulas.Operation import Operation
from keopscore.utils.code_gen_utils import c_for_loop
from keopscore.formulas.complex.Imag2Complex import Imag2Complex
from keopscore.utils.misc_utils import KeOps_Error
# /////////////////////////////////////////////////////////////////////////
# //// ComplexImag ////
# /////////////////////////////////////////////////////////////////////////
class ComplexImag(Operation):
string_id = "ComplexImag"
def __init__(self, f):
if f.dim % 2 != 0:
KeOps_Error("Dimension of F must be even")
self.dim = int(f.dim / 2)
super().__init__(f)
def Op(self, out, table, inF):
f = self.children[0]
forloop, i = c_for_loop(0, f.dim, 2, pragma_unroll=True)
return forloop(out[i / 2].assign(inF[i + 1]))
def DiffT(self, v, gradin):
f = self.children[0]
return f.DiffT(v, Imag2Complex(gradin))
| keops-main | keopscore/keopscore/formulas/complex/ComplexImag.py |
from keopscore.formulas.Operation import Operation
from keopscore.utils.code_gen_utils import c_zero_float, c_for_loop
from keopscore.utils.misc_utils import KeOps_Error
# /////////////////////////////////////////////////////////////////////////
# //// ComplexSum ////
# /////////////////////////////////////////////////////////////////////////
class ComplexSum(Operation):
string_id = "ComplexSum"
def __init__(self, f):
if f.dim % 2 != 0:
KeOps_Error("Dimension of F must be even")
self.dim = 2
super().__init__(f)
def Op(self, out, table, inF):
f = self.children[0]
string = out[0].assign(c_zero_float)
string += out[1].assign(out[0])
forloop, i = c_for_loop(0, f.dim, 2, pragma_unroll=True)
body = out[0].add_assign(inF[i])
body += out[1].add_assign(inF[i + 1])
string += forloop(body)
return string
def DiffT(self, v, gradin):
from keopscore.formulas.complex.ComplexSumT import ComplexSumT
f = self.children[0]
return f.DiffT(v, ComplexSumT(gradin, f.dim))
| keops-main | keopscore/keopscore/formulas/complex/ComplexSum.py |
from keopscore.formulas.maths.Atan2 import Atan2
from keopscore.formulas.complex.ComplexReal import ComplexReal
from keopscore.formulas.complex.ComplexImag import ComplexImag
# /////////////////////////////////////////////////////////////////////////
# //// ComplexAngle ////
# /////////////////////////////////////////////////////////////////////////
def ComplexAngle(f):
return Atan2(ComplexImag(f), ComplexReal(f))
| keops-main | keopscore/keopscore/formulas/complex/ComplexAngle.py |
from keopscore.formulas.Operation import Operation
from keopscore.utils.code_gen_utils import c_for_loop
from keopscore.formulas.complex.ComplexReal import ComplexReal
from keopscore.formulas.complex.ComplexMult import ComplexMult
from keopscore.formulas.complex.Conj import Conj
from keopscore.utils.misc_utils import KeOps_Error
# /////////////////////////////////////////////////////////////////////////
# //// ComplexSquareAbs ////
# /////////////////////////////////////////////////////////////////////////
class ComplexSquareAbs(Operation):
string_id = "ComplexSquareAbs"
def __init__(self, f):
if f.dim % 2 != 0:
KeOps_Error("Dimension of F must be even")
self.dim = int(f.dim / 2)
super().__init__(f)
def Op(self, out, table, inF):
f = self.children[0]
forloop, i = c_for_loop(0, f.dim, 2, pragma_unroll=True)
return forloop(out[i / 2].assign(inF[i] * inF[i] + inF[i + 1] * inF[i + 1]))
def DiffT(self, v, gradin):
f = self.children[0]
AltFormula = ComplexReal(ComplexMult(f, Conj(f)))
return AltFormula.DiffT(v, gradin)
| keops-main | keopscore/keopscore/formulas/complex/ComplexSquareAbs.py |
from keopscore.formulas.VectorizedComplexScalarOp import VectorizedComplexScalarOp
# /////////////////////////////////////////////////////////////////////////
# //// ComplexSubtract ////
# /////////////////////////////////////////////////////////////////////////
class ComplexSubtract(VectorizedComplexScalarOp):
string_id = "ComplexSubtract"
def ScalarOp(self, out, inF, inG):
string = out[0].assign(inF[0] - inG[0])
string += out[1].assign(inF[1] - inG[1])
return string
def DiffT(self, v, gradin):
f, g = self.children
return ComplexSubtract(f.DiffT(v, gradin), g.DiffT(v, gradin))
| keops-main | keopscore/keopscore/formulas/complex/ComplexSubtract.py |
from .ComplexAbs import ComplexAbs
from .ComplexAdd import ComplexAdd
from .ComplexAngle import ComplexAngle
from .ComplexDivide import ComplexDivide
from .ComplexExp import ComplexExp
from .ComplexExp1j import ComplexExp1j
from .ComplexImag import ComplexImag
from .ComplexMult import ComplexMult
from .ComplexReal import ComplexReal
from .ComplexRealScal import ComplexRealScal
from .ComplexSquareAbs import ComplexSquareAbs
from .ComplexSubtract import ComplexSubtract
from .ComplexSum import ComplexSum
from .ComplexSumT import ComplexSumT
from .Conj import Conj
from .Imag2Complex import Imag2Complex
from .Real2Complex import Real2Complex
| keops-main | keopscore/keopscore/formulas/complex/__init__.py |
from keopscore.formulas.complex.ComplexSquareAbs import ComplexSquareAbs
from keopscore.formulas.maths.Sqrt import Sqrt
# /////////////////////////////////////////////////////////////////////////
# //// ComplexAbs ////
# /////////////////////////////////////////////////////////////////////////
def ComplexAbs(f):
return Sqrt(ComplexSquareAbs(f))
| keops-main | keopscore/keopscore/formulas/complex/ComplexAbs.py |
from keopscore.formulas.complex.Real2Complex import Real2Complex
from keopscore.formulas.complex.ComplexMult import ComplexMult
from keopscore.formulas.complex.ComplexSquareAbs import ComplexSquareAbs
from keopscore.formulas.complex.Conj import Conj
from keopscore.formulas.maths.Inv import Inv
# /////////////////////////////////////////////////////////////////////////
# //// ComplexDivide ////
# /////////////////////////////////////////////////////////////////////////
def ComplexDivide(f, g):
return ComplexMult(Real2Complex(Inv(ComplexSquareAbs(g))), ComplexMult(f, Conj(g)))
| keops-main | keopscore/keopscore/formulas/complex/ComplexDivide.py |
from keopscore.formulas.VectorizedComplexScalarOp import VectorizedComplexScalarOp
from keopscore.formulas.complex.Conj import Conj
# /////////////////////////////////////////////////////////////////////////
# //// ComplexMult ////
# /////////////////////////////////////////////////////////////////////////
class ComplexMult(VectorizedComplexScalarOp):
string_id = "ComplexMult"
def ScalarOp(self, out, inF, inG):
string = out[0].assign(inF[0] * inG[0] - inF[1] * inG[1])
string += out[1].assign(inF[0] * inG[1] + inF[1] * inG[0])
return string
def DiffT(self, v, gradin):
f, g = self.children
DiffTF = f.DiffT(v, gradin)
DiffTG = g.DiffT(v, gradin)
return DiffTF(v, ComplexMult(Conj(g), gradin)) + DiffTG(
v, ComplexMult(Conj(f), gradin)
)
| keops-main | keopscore/keopscore/formulas/complex/ComplexMult.py |
from keopscore.formulas.Operation import Operation
from keopscore.utils.code_gen_utils import c_for_loop
from keopscore.formulas.complex.Real2Complex import Real2Complex
from keopscore.utils.misc_utils import KeOps_Error
# /////////////////////////////////////////////////////////////////////////
# //// ComplexReal ////
# /////////////////////////////////////////////////////////////////////////
class ComplexReal(Operation):
string_id = "ComplexReal"
def __init__(self, f):
if f.dim % 2 != 0:
KeOps_Error("Dimension of F must be even")
self.dim = int(f.dim / 2)
super().__init__(f)
def Op(self, out, table, inF):
f = self.children[0]
forloop, i = c_for_loop(0, f.dim, 2, pragma_unroll=True)
return forloop(out[i / 2].assign(inF[i]))
def DiffT(self, v, gradin):
f = self.children[0]
return f.DiffT(v, Real2Complex(gradin))
| keops-main | keopscore/keopscore/formulas/complex/ComplexReal.py |
from keopscore.formulas.Operation import Operation
from keopscore.utils.code_gen_utils import c_for_loop
from keopscore.utils.misc_utils import KeOps_Error
# /////////////////////////////////////////////////////////////////////////
# //// adjoint of ComplexSum ////
# /////////////////////////////////////////////////////////////////////////
class ComplexSumT(Operation):
string_id = "ComplexSumT"
def __init__(self, f, dim):
if f.dim != 2:
KeOps_Error("Dimension of F must be 2")
self.dim = dim
super().__init__(f)
def Op(self, out, table, inF):
forloop, i = c_for_loop(0, self.dim, 2, pragma_unroll=True)
body = out[i].assign(inF[0])
body += out[i + 1].assign(inF[1])
return forloop(body)
def DiffT(self, v, gradin):
from keopscore.formulas.complex.ComplexSum import ComplexSum
f = self.children[0]
return f.DiffT(v, ComplexSum(gradin))
| keops-main | keopscore/keopscore/formulas/complex/ComplexSumT.py |
from keopscore.formulas.VectorizedComplexScalarOp import VectorizedComplexScalarOp
# /////////////////////////////////////////////////////////////////////////
# //// Conj : complex conjugate ////
# /////////////////////////////////////////////////////////////////////////
class Conj(VectorizedComplexScalarOp):
string_id = "Conj"
def ScalarOp(self, out, inF):
string = out[0].assign(inF[0])
string += out[1].assign(-inF[1])
return string
def DiffT(self, v, gradin):
f = self.children[0]
return f.DiffT(v, Conj(gradin))
| keops-main | keopscore/keopscore/formulas/complex/Conj.py |
from keopscore.formulas.VectorizedComplexScalarOp import VectorizedComplexScalarOp
# /////////////////////////////////////////////////////////////////////////
# //// ComplexAdd ////
# /////////////////////////////////////////////////////////////////////////
class ComplexAdd(VectorizedComplexScalarOp):
string_id = "ComplexAdd"
def ScalarOp(self, out, inF, inG):
string = out[0].assign(inF[0] + inG[0])
string += out[1].assign(inF[1] + inG[1])
return string
def DiffT(self, v, gradin):
f, g = self.children
return ComplexAdd(f.DiffT(v, gradin), g.DiffT(v, gradin))
| keops-main | keopscore/keopscore/formulas/complex/ComplexAdd.py |
from keopscore.formulas.Operation import Operation
from keopscore.utils.code_gen_utils import c_for_loop
from keopscore.utils.math_functions import keops_sincos
from keopscore.formulas.complex.Real2Complex import Real2Complex
from keopscore.formulas.complex.Imag2Complex import Imag2Complex
from keopscore.formulas.maths.Cos import Cos
from keopscore.formulas.maths.Sin import Sin
# /////////////////////////////////////////////////////////////////////////
# //// ComplexExp1j ////
# /////////////////////////////////////////////////////////////////////////
class ComplexExp1j(Operation):
string_id = "ComplexExp1j"
def __init__(self, f):
self.dim = 2 * f.dim
super().__init__(f)
def Op(self, out, table, inF):
forloop, i = c_for_loop(0, self.dim, 2, pragma_unroll=True)
body = keops_sincos(inF[i / 2], out[i] + 1, out[i])
return forloop(body)
def DiffT(self, v, gradin):
# building equivalent formula for autodiff
f = self.children[0]
AltFormula = Real2Complex(Cos(f)) + Imag2Complex(Sin(f))
return AltFormula.DiffT(v, gradin)
| keops-main | keopscore/keopscore/formulas/complex/ComplexExp1j.py |
from .IntCst import IntCst
from .Var import Var
from .Zero import Zero
| keops-main | keopscore/keopscore/formulas/variables/__init__.py |
from keopscore.utils.code_gen_utils import c_zero_float
from keopscore.formulas.Operation import Operation
class Zero(Operation):
"""zero operation : encodes a vector of zeros"""
string_id = "Zero"
def __init__(self, dim):
super().__init__()
self.dim = dim
self.params = (dim,)
# custom __eq__ method
def __eq__(self, other):
return type(self) == type(other) and self.dim == other.dim
def Op(self, out, table):
return out.assign(c_zero_float)
def DiffT(self, v, gradin):
return Zero(v.dim)
| keops-main | keopscore/keopscore/formulas/variables/Zero.py |
from keopscore.utils.code_gen_utils import cast_to, c_variable
from keopscore.formulas.Operation import Operation
from keopscore.formulas.variables.Zero import Zero
class IntCst_Impl(Operation):
# constant integer "operation"
string_id = "IntCst"
print_spec = "", "pre", 0
def __init__(self, val):
super().__init__()
self.val = val
self.dim = 1
self.params = (val,)
# custom __eq__ method
def __eq__(self, other):
return type(self) == type(other) and self.val == other.val
def Op(self, out, table):
float_val = c_variable("float", f"(float){self.val}")
return f"*{out.id} = {cast_to(out.dtype, float_val)};\n"
def DiffT(self, v, gradin):
return Zero(v.dim)
# N.B. The following separate function should theoretically be implemented
# as a __new__ method of the previous class, but this can generate infinite recursion problems
def IntCst(arg):
if arg == 0:
return Zero(1)
else:
return IntCst_Impl(arg)
| keops-main | keopscore/keopscore/formulas/variables/IntCst.py |
from keopscore.utils.code_gen_utils import VectCopy
from keopscore.formulas.Operation import Operation
#######################
## Var operation
#######################
class Var(Operation):
"""Var operation class. Var(ind,dim,cat) is a symbolic
object that encodes an input tensor in the call to the
KeOps routine, where
- ind gives the position of the input tensor in the list of tensors sent to the routine
- dim gives the "dimension" of the data : each input tensor is interpreted as a matrix
of size (n,dim), where n is dynamically handled and dim is known at compile time.
- cat is the "category" of the variable : either a "i"-indexed variable (cat=0),
a "j"-indexed variable (cat=1), or a parameter variable (cat=2)"""
string_id = "Var"
def __init__(self, ind, dim, cat):
super().__init__()
self.ind = ind
self.dim = dim
self.cat = cat
self.Vars_ = {self}
self.params = (ind, dim, cat)
# custom __eq__ and __hash__ methods, required to handle properly the union of two sets of Var objects
def __eq__(self, other):
return (
type(self) == type(other)
and self.ind == other.ind
and self.dim == other.dim
and self.cat == other.cat
)
def __hash__(self):
return hash((self.ind, self.dim, self.cat))
def Op(self, out, table):
return VectCopy(out, table[self.ind])
# Assuming that the gradient wrt. Var is GRADIN, how does it affect V ?
# Var::DiffT<V, grad_input> = grad_input if V == Var (in the sense that it represents the same symb. var.)
# Zero(V::DIM) otherwise
def DiffT(self, v, gradin):
from keopscore.formulas.variables.Zero import Zero
return gradin if v == self else Zero(v.dim)
def chunked_version(self, dimchk):
return Var(self.ind, dimchk, self.cat)
@property
def is_chunkable(self):
return True
def chunked_formulas(self, dimchk):
return []
@property
def num_chunked_formulas(self):
return 0
def post_chunk_formula(self, ind):
return Var(self.ind, self.dim, self.cat)
def chunked_vars(self, cat):
return self.Vars(cat)
def notchunked_vars(self, cat):
return set()
| keops-main | keopscore/keopscore/formulas/variables/Var.py |
from keopscore.formulas.Operation import Broadcast
from keopscore.formulas.VectorizedScalarOp import VectorizedScalarOp
from keopscore.formulas.maths.Scalprod import Scalprod
from keopscore.formulas.maths.Square import Square
from keopscore.formulas.variables.Zero import Zero
from keopscore.utils.math_functions import keops_mul
from keopscore.formulas.variables.IntCst import IntCst_Impl
from keopscore.formulas.maths.SumT import SumT, SumT_Impl
from keopscore.utils.misc_utils import KeOps_Error
##########################
###### Mult #####
##########################
class Mult_Impl(VectorizedScalarOp):
"""the binary multiply operation"""
string_id = "Mult"
print_spec = "*", "mid", 3
ScalarOpFun = keops_mul
# \diff_V (A*B) = (\diff_V A) * B + A * (\diff_V B)
def DiffT(self, v, gradin):
fa, fb = self.children
if fa.dim == 1 and fb.dim > 1:
return fa.DiffT(v, Scalprod(gradin, fb)) + fb.DiffT(v, fa * gradin)
elif fb.dim == 1 and fa.dim > 1:
return fa.DiffT(v, fb * gradin) + fb.DiffT(v, Scalprod(gradin, fa))
else:
return fa.DiffT(v, fb * gradin) + fb.DiffT(v, fa * gradin)
# parameters for testing the operation (optional)
nargs = 2 # number of arguments
torch_op = "torch.mul" # equivalent PyTorch operation
# N.B. The following separate function should theoretically be implemented
# as a __new__ method of the previous class, but this can generate infinite recursion problems
def Mult(arg0, arg1):
if isinstance(arg0, Zero):
return Broadcast(arg0, arg1.dim)
elif isinstance(arg1, Zero):
return Broadcast(arg1, arg0.dim)
elif isinstance(arg0, IntCst_Impl):
if arg0.val == 1:
# 1*f -> f
return arg1
if arg0.val == -1:
# -1*f -> -f
return -arg1
elif isinstance(arg1, IntCst_Impl):
# m*n -> mn
return IntCst_Impl(arg0.val * arg1.val)
if isinstance(arg1, IntCst_Impl):
# f*n -> n*f (bringing integers to the left)
return Mult(arg1, arg0)
elif isinstance(arg1, Mult_Impl) and isinstance(arg1.children[0], IntCst_Impl):
# f*(n*g) -> (n*f)*g
return (arg1.children[0] * arg0) * arg1.children[1]
elif arg0 == arg1:
# f*f -> f^2
return Square(arg0)
elif isinstance(arg1, SumT_Impl):
# f*SumT(g)
if isinstance(arg0, SumT_Impl):
# SumT(f)*SumT(g) -> SumT(f*g)
if arg0.dim != arg1.dim: # should never happen...
KeOps_Error("dimensions are not compatible for Mult operation")
return SumT(arg0.children[0] * arg1.children[0], arg0.dim)
elif arg0.dim == 1:
# f*SumT(g) -> SumT(f*g)
return SumT(arg0 * arg1.children[0], arg1.dim)
elif arg1.dim == arg0.dim:
# f*SumT(g) -> f*g (broadcasted)
return arg0 * arg1.children[0]
else:
KeOps_Error("dimensions are not compatible for Mult operation")
elif isinstance(arg0, SumT_Impl):
# SumT(f)*g -> g*SumT(f)
return arg1 * arg0
else:
return Mult_Impl(arg0, arg1)
| keops-main | keopscore/keopscore/formulas/maths/Mult.py |
from keopscore.formulas.Operation import Operation
from keopscore.formulas.maths.ArgMax import ArgMax
from keopscore.formulas.maths.OneHot import OneHot
from keopscore.utils.code_gen_utils import c_for_loop, c_if, value
from keopscore.utils.misc_utils import KeOps_Error
############################
###### Max #####
############################
class Max(Operation):
string_id = "Max"
def __init__(self, f):
super().__init__(f)
if f.dim < 1:
KeOps_Error("Max operation is only possible when dimension is non zero.")
self.dim = 1
self.argdim = f.dim
def Op(self, out, table, arg):
loop, k = c_for_loop(1, arg.dim, 1, pragma_unroll=True)
string = value(out).assign(arg[0])
if out.dtype == "half2":
loop_string = f"""
// we have to work element-wise...
__half2 cond = __hlt2(*{out.id},{arg[k].id}); // cond = (out > outF[k]) (element-wise)
__half2 negcond = __float2half2_rn(1.0f)-cond; // negcond = 1-cond
*{out.id} = cond * {arg[k].id} + negcond * *{out.id}; // out = cond * outF[k] + (1-cond) * out
"""
string += loop(loop_string)
else:
string += loop(c_if(arg[k] > value(out), value(out).assign(arg[k])))
return string
def DiffT(self, v, gradin):
f = self.children[0]
return f.DiffT(v, OneHot(ArgMax(f), self.argdim) * gradin)
# parameters for testing the operation (optional)
enable_test = True # enable testing for this operation
nargs = 1 # number of arguments
test_argdims = [5] # dimensions of arguments for testing
torch_op = "lambda x : torch.max(x, dim=-1, keepdim=True)[0].type(x.dtype)"
| keops-main | keopscore/keopscore/formulas/maths/Max.py |
from keopscore.formulas.VectorizedScalarOp import VectorizedScalarOp
from keopscore.utils.math_functions import keops_pow
class Pow(VectorizedScalarOp):
"""the integer power vectorized operation
Pow(f,m) where m is integer, computes f^m
"""
def __init__(self, f, m):
super().__init__(f, params=(m,))
string_id = "Pow"
ScalarOpFun = keops_pow
@staticmethod
def Derivative(f, m):
from keopscore.formulas.variables.IntCst import IntCst
return IntCst(m) * Pow(f, m - 1)
# parameters for testing the operation (optional)
nargs = 1 # number of arguments (excluding parameters)
test_ranges = [(0, 2)] # ranges of arguments
test_params = [2] # values of parameters for testing
torch_op = "lambda x,m : torch.pow(x, m)"
| keops-main | keopscore/keopscore/formulas/maths/Pow.py |
from keopscore.formulas.Operation import Operation
from keopscore.utils.code_gen_utils import (
c_variable,
c_for_loop,
c_zero_float,
)
from keopscore.utils.misc_utils import KeOps_Error
# /////////////////////////////////////////////////////////////////////////
# //// Vector-matrix product b x A ////
# /////////////////////////////////////////////////////////////////////////
class VecMatMult(Operation):
string_id = "VecMatMult"
def __init__(self, B, A):
# A is vector of size n*p, interpreted as matrix, B is vector of size n, interpreted as row vector
# output is vector of size p
if A.dim % B.dim != 0:
KeOps_Error(
"Dimensions of A and B are not compatible for vector-matrix product"
)
super().__init__(B, A)
self.dim = A.dim // B.dim
def Op(self, out, table, inB, inA):
q = c_variable("int")
loop, i = c_for_loop(0, self.dim, 1, pragma_unroll=True)
inner_loop, k = c_for_loop(0, inB.dim, 1, pragma_unroll=True)
return f"""
#if C_CONTIGUOUS // row major
{q.declare_assign(0)}
{loop(out[i].assign(c_zero_float) + inner_loop(out[i].add_assign(inA[k * self.dim + i] * inB[k])))}
#else // column major
{q.declare_assign(0)}
{loop(out[i].assign(c_zero_float) + inner_loop(out[i].add_assign(inA[q] * inB[k]) + q.add_assign(1)))}
#endif
"""
def DiffT(self, v, gradin):
from keopscore.formulas.maths.MatVecMult import MatVecMult
from keopscore.formulas.maths.TensorProd import TensorProd
B, A = self.children
return A.DiffT(v, TensorProd(B, gradin)) + B.DiffT(v, MatVecMult(A, gradin))
| keops-main | keopscore/keopscore/formulas/maths/VecMatMult.py |
from keopscore.formulas.Operation import Operation
from keopscore.utils.code_gen_utils import value
from keopscore.utils.misc_utils import KeOps_Error
############################
###### ELEMENT EXTRACTION : Elem(f,m) (aka get_item) #####
############################
class Elem(Operation):
string_id = "Elem"
def __init__(self, f, m):
super().__init__(f, params=(m,))
if f.dim <= m:
KeOps_Error("Index out of bound in Elem")
self.dim = 1
self.m = m
def Op(self, out, table, arg):
return value(out).assign(arg[self.m])
def DiffT(self, v, gradin):
from keopscore.formulas.maths.ElemT import ElemT
f = self.children[0]
return f.DiffT(v, ElemT(gradin, f.dim, self.m))
# parameters for testing the operation (optional)
enable_test = True # enable testing for this operation
nargs = 1 # number of arguments
test_argdims = [5] # dimensions of arguments for testing
test_params = [3] # dimensions of parameters for testing
torch_op = "lambda x, m : x[..., m][..., None]"
| keops-main | keopscore/keopscore/formulas/maths/Elem.py |
from keopscore.formulas.VectorizedScalarOp import VectorizedScalarOp
from keopscore.formulas.maths.DiffClampInt import DiffClampInt
from keopscore.utils.math_functions import keops_clampint
class ClampInt(VectorizedScalarOp):
"""ClampInt(x,a,b) = a if x<a, x if a<=x<=b, b if b<x
N.B. same as Clamp but a and b are fixed integers.
ClampInt may be faster than Clamp because we avoid the transfer
of A and B in memory.
"""
string_id = "ClampInt"
def __init__(self, x, a, b):
super().__init__(x, params=(a, b))
ScalarOpFun = keops_clampint
@staticmethod
def Derivative(x, a, b):
return DiffClampInt(x, a, b)
# parameters for testing the operation (optional)
test_params = [0, 1] # parameters to try
torch_op = "torch.clamp" # equivalent PyTorch operation
| keops-main | keopscore/keopscore/formulas/maths/ClampInt.py |
from keopscore.formulas.Operation import Broadcast
from keopscore.formulas.VectorizedScalarOp import VectorizedScalarOp
from keopscore.formulas.maths.Mult import Mult_Impl
from keopscore.formulas.variables.IntCst import IntCst, IntCst_Impl
from keopscore.formulas.variables.Zero import Zero
##########################
###### Add #####
##########################
class Add_Impl(VectorizedScalarOp):
"""the binary addition operation"""
string_id = "Add"
print_spec = "+", "mid", 4
def ScalarOp(self, out, arg0, arg1):
# returns the atomic piece of c++ code to evaluate the function on arg and return
# the result in out
return f"{out.id} = {arg0.id}+{arg1.id};\n"
def DiffT(self, v, gradin):
fa, fb = self.children
return fa.DiffT(v, gradin) + fb.DiffT(v, gradin)
# parameters for testing the operation (optional)
nargs = 2 # number of arguments
# N.B. The following separate function could theoretically be implemented
# as a __new__ method of the previous class, but this can generate infinite recursion problems
def Add(arg0, arg1):
if isinstance(arg0, Zero):
return Broadcast(arg1, arg0.dim)
elif isinstance(arg1, Zero):
return Broadcast(arg0, arg1.dim)
elif arg0 == arg1:
return IntCst(2) * arg0
elif isinstance(arg0, Mult_Impl) and isinstance(arg0.children[0], IntCst_Impl):
if arg0.children[1] == arg1:
# factorization : n*x + x = (n+1)*x
return IntCst(arg0.children[0].val + 1) * arg1
elif (
isinstance(arg1, Mult_Impl)
and isinstance(arg1.children[0], IntCst_Impl)
and arg1.children[1] == arg0.children[1]
):
# factorization : m*x + n*x = (m+n)*x
return (
IntCst(arg0.children[0].val + arg1.children[0].val) * arg0.children[1]
)
if (
isinstance(arg1, Mult_Impl)
and isinstance(arg1.children[0], IntCst_Impl)
and arg1.children[1] == arg0
):
# factorization : x + n*x = (n+1)*x
return IntCst(arg1.children[0].val + 1) * arg0
return Add_Impl(arg0, arg1)
| keops-main | keopscore/keopscore/formulas/maths/Add.py |
from keopscore.formulas.Operation import Operation
from keopscore.utils.code_gen_utils import (
c_variable,
c_for_loop,
c_zero_float,
)
from keopscore.utils.misc_utils import KeOps_Error
# /////////////////////////////////////////////////////////////////////////
# //// Matrix-vector product A x b ////
# /////////////////////////////////////////////////////////////////////////
class MatVecMult(Operation):
string_id = "MatVecMult"
def __init__(self, A, B):
# A is vector of size n*p, interpreted as matrix, B is vector of size p, interpreted as column vector
# output is vector of size n
if A.dim % B.dim != 0:
KeOps_Error(
"Dimensions of A and B are not compatible for matrix-vector product"
)
super().__init__(A, B)
self.dim = A.dim // B.dim
def Op(self, out, table, inA, inB):
q = c_variable("int")
loop, i = c_for_loop(0, self.dim, 1, pragma_unroll=True)
inner_loop, k = c_for_loop(0, inB.dim, 1, pragma_unroll=True)
return f"""
#if C_CONTIGUOUS // row major
{q.declare_assign(0)}
{loop(out[i].assign(c_zero_float) + inner_loop(out[i].add_assign(inA[q] * inB[k]) + q.add_assign(1)))}
#else // column major
{loop(out[i].assign(c_zero_float) + inner_loop(out[i].add_assign(inA[k * self.dim + i] * inB[k])))}
#endif
"""
def DiffT(self, v, gradin):
from keopscore.formulas.maths import TensorProd, VecMatMult
A, B = self.children
return A.DiffT(v, TensorProd(gradin, B)) + B.DiffT(v, VecMatMult(gradin, A))
# parameters for testing the operation (optional)
enable_test = True # enable testing for this operation
nargs = 2 # number of arguments
test_argdims = [6, 2] # dimensions of arguments for testing
torch_op = None # equivalent PyTorch operation
| keops-main | keopscore/keopscore/formulas/maths/MatVecMult.py |
from keopscore.formulas.Operation import Broadcast
from keopscore.formulas.VectorizedScalarOp import VectorizedScalarOp
from keopscore.formulas.variables.Zero import Zero
from keopscore.formulas.maths.Mult import Mult_Impl
from keopscore.formulas.variables.IntCst import IntCst, IntCst_Impl
##########################
###### Subtract #####
##########################
class Subtract_Impl(VectorizedScalarOp):
"""the binary subtract operation"""
string_id = "Subtract"
print_spec = "-", "mid", 4
def ScalarOp(self, out, arg0, arg1):
# returns the atomic piece of c++ code to evaluate the function on arg and return
# the result in out
return f"{out.id} = {arg0.id}-{arg1.id};\n"
def DiffT(self, v, gradin):
fa, fb = self.children
return fa.DiffT(v, gradin) - fb.DiffT(v, gradin)
# parameters for testing the operation (optional)
nargs = 2 # number of arguments
torch_op = "torch.sub" # equivalent PyTorch operation
# N.B. The following separate function should theoretically be implemented
# as a __new__ method of the previous class, but this can generate infinite recursion problems
def Subtract(arg0, arg1):
if isinstance(arg0, Zero):
return -Broadcast(arg1, arg0.dim)
elif isinstance(arg1, Zero):
return Broadcast(arg0, arg1.dim)
elif arg0 == arg1:
return Zero(arg0.dim)
elif isinstance(arg0, Mult_Impl) and isinstance(arg0.children[0], IntCst_Impl):
if arg0.children[1] == arg1:
# factorization : n*x - x = (n-1)*x
return IntCst(arg0.children[0].val - 1) * arg1
elif (
isinstance(arg1, Mult_Impl)
and isinstance(arg1.children[0], IntCst_Impl)
and arg1.children[1] == arg0.children[1]
):
# factorization : m*x - n*x = (m-n)*x
return (
IntCst(arg0.children[0].val - arg1.children[0].val) * arg0.children[1]
)
if (
isinstance(arg1, Mult_Impl)
and isinstance(arg1.children[0], IntCst_Impl)
and arg1.children[1] == arg0
):
# factorization : x - n*x = (1-n)*x
return IntCst(1 - arg1.children[0].val) * arg0
else:
return Subtract_Impl(arg0, arg1)
| keops-main | keopscore/keopscore/formulas/maths/Subtract.py |
from keopscore.formulas.VectorizedScalarOp import VectorizedScalarOp
from keopscore.formulas.variables.Zero import Zero
##########################
###### Minus #####
##########################
class Minus_Impl(VectorizedScalarOp):
"""the "minus" vectorized operation"""
string_id = "Minus"
print_spec = "-", "pre", 2
def ScalarOp(self, out, arg):
# returns the atomic piece of c++ code to evaluate the function on arg and return
# the result in out
return f"{out.id} = -{arg.id};\n"
def DiffT(self, v, gradin):
f = self.children[0]
return -f.DiffT(v, gradin)
# parameters for testing the operation (optional)
nargs = 1 # number of arguments
torch_op = "torch.neg" # equivalent PyTorch operation
# N.B. The following separate function should theoretically be implemented
# as a __new__ method of the previous class, but this can generate infinite recursion problems
def Minus(arg):
if isinstance(arg, Zero):
return arg
else:
return Minus_Impl(arg)
| keops-main | keopscore/keopscore/formulas/maths/Minus.py |
from keopscore.formulas.VectorizedScalarOp import VectorizedScalarOp
from keopscore.utils.math_functions import keops_rcp
##########################
###### INVERSE : Inv<F> #####
##########################
class Inv(VectorizedScalarOp):
"""the "Inv" vectorized operation"""
string_id = "Inv"
print_spec = "1/", "pre", 2
ScalarOpFun = keops_rcp
@staticmethod
def Derivative(f):
return -1 / f**2
# parameters for testing the operation (optional)
torch_op = "lambda x : 1 / x"
| keops-main | keopscore/keopscore/formulas/maths/Inv.py |
from keopscore.formulas.VectorizedScalarOp import VectorizedScalarOp
from keopscore.formulas.maths.IntInv import IntInv
from keopscore.formulas.maths.Rsqrt import Rsqrt
from keopscore.utils.math_functions import keops_sqrt
##########################
###### Sqrt #####
##########################
class Sqrt(VectorizedScalarOp):
"""the square root vectorized operation"""
string_id = "Sqrt"
ScalarOpFun = keops_sqrt
@staticmethod
def Derivative(f):
return IntInv(2) * Rsqrt(f)
# parameters for testing the operation (optional)
test_ranges = [(0, 2)] # range of argument
| keops-main | keopscore/keopscore/formulas/maths/Sqrt.py |
from keopscore.formulas.VectorizedScalarOp import VectorizedScalarOp
from keopscore.formulas.maths.IntInv import IntInv
##########################
###### Rsqrt #####
##########################
class Rsqrt(VectorizedScalarOp):
"""the inverse square root vectorized operation"""
string_id = "Rsqrt"
def ScalarOp(self, out, arg):
from keopscore.utils.math_functions import keops_rsqrt
# returns the atomic piece of c++ code to evaluate the function on arg and return
# the result in out
return out.assign(keops_rsqrt(arg))
@staticmethod
def Derivative(f):
return IntInv(-2) * Rsqrt(f) ** 3
# parameters for testing the operation (optional)
test_ranges = [(0.5, 2)] # range of argument
| keops-main | keopscore/keopscore/formulas/maths/Rsqrt.py |
from keopscore.formulas.Operation import Operation
from keopscore.formulas.maths.Extract import Extract
from keopscore.utils.code_gen_utils import VectCopy
############################
###### Concat #####
############################
class Concat(Operation):
string_id = "Concat"
def __init__(self, arg0, arg1):
super().__init__(arg0, arg1)
self.dim = arg0.dim + arg1.dim
def Op(self, out, table, arg0, arg1):
out0, out1 = out.split(arg0.dim, arg1.dim)
return VectCopy(out0, arg0) + VectCopy(out1, arg1)
def DiffT(self, v, gradin):
f = self.children[0]
g = self.children[1]
return f.DiffT(v, Extract(gradin, 0, f.dim)) + g.DiffT(
v, Extract(gradin, f.dim, g.dim)
)
# parameters for testing the operation (optional)
enable_test = True # enable testing for this operation
nargs = 2 # number of arguments
test_argdims = [5, 3] # dimensions of arguments for testing
torch_op = None
| keops-main | keopscore/keopscore/formulas/maths/Concat.py |
from keopscore.formulas.VectorizedScalarOp import VectorizedScalarOp
from keopscore.utils.math_functions import keops_log
class Log(VectorizedScalarOp):
"""the logarithm vectorized operation"""
string_id = "Log"
ScalarOpFun = keops_log
@staticmethod
def Derivative(f):
return 1 / f
# parameters for testing the operation (optional)
test_ranges = [(0, 2)] # range of argument
| keops-main | keopscore/keopscore/formulas/maths/Log.py |
from keopscore.formulas.maths.SqNorm2 import SqNorm2
class SqDist:
def __new__(cls, arg0, arg1):
return SqNorm2(arg0 - arg1)
enable_test = False
| keops-main | keopscore/keopscore/formulas/maths/SqDist.py |
from keopscore.formulas.maths.Square import Square
from keopscore.formulas.maths.Sum import Sum
class SqNormDiag:
"""
Anisotropic (but diagonal) norm, if S.dim == A.dim: SqNormDiag(S,A) = sum_i s_i*a_i*a_i
"""
def __new__(cls, S, A):
return Sum(S * Square(A))
enable_test = False
| keops-main | keopscore/keopscore/formulas/maths/SqNormDiag.py |
from keopscore.formulas.maths.SqNorm2 import SqNorm2
class WeightedSqDist:
"""
WEIGHTED SQUARED DISTANCE : WeightedSqDist(S,A)
"""
def __new__(cls, S, A):
return S * SqNorm2(A)
enable_test = False
| keops-main | keopscore/keopscore/formulas/maths/WeightedSqDist.py |
from keopscore.formulas.VectorizedScalarOp import VectorizedScalarOp
from keopscore.formulas.maths.Rsqrt import Rsqrt
from keopscore.utils.math_functions import keops_asin
class Asin(VectorizedScalarOp):
"""the arc-sine vectorized operation"""
string_id = "Asin"
ScalarOpFun = keops_asin
@staticmethod
def Derivative(f):
return Rsqrt(1 - f**2)
# parameters for testing the operation (optional)
test_ranges = [(-1, 1)] # range of argument
| keops-main | keopscore/keopscore/formulas/maths/Asin.py |
from keopscore.formulas.maths.Sum import Sum
from keopscore.formulas.maths.TensorProd import TensorProd
class SymSqNorm:
"""
Fully anisotropic norm, if S.dim == A.dim * A.dim
SymSqNorm(A,X) = sum_{ij} a_ij * x_i*x_j
"""
def __new__(cls, A, X):
return Sum(A * TensorProd(X, X))
enable_test = False
| keops-main | keopscore/keopscore/formulas/maths/SymSqNorm.py |
from keopscore.formulas.maths.Rsqrt import Rsqrt
from keopscore.formulas.maths.SqNorm2 import SqNorm2
class Normalize:
def __new__(cls, arg):
return Rsqrt(SqNorm2(arg)) * arg
enable_test = False
| keops-main | keopscore/keopscore/formulas/maths/Normalize.py |
from keopscore.formulas.VectorizedScalarOp import VectorizedScalarOp
from keopscore.utils.math_functions import keops_cos
class Cos(VectorizedScalarOp):
"""the cosine vectorized operation"""
string_id = "Cos"
ScalarOpFun = keops_cos
@staticmethod
def Derivative(f):
from .Sin import Sin
return -Sin(f)
| keops-main | keopscore/keopscore/formulas/maths/Cos.py |
from keopscore.formulas.VectorizedScalarOp import VectorizedScalarOp
from keopscore.utils.math_functions import keops_atan2
# //////////////////////////////////////////////////////////////
# //// ATAN2 : Atan2< F, G > ////
# //////////////////////////////////////////////////////////////
class Atan2(VectorizedScalarOp):
string_id = "Atan2"
ScalarOpFun = keops_atan2
@staticmethod
def Derivative(f, g):
r2 = f**2 + g**2
return g / r2, -f / r2
| keops-main | keopscore/keopscore/formulas/maths/Atan2.py |
from keopscore.formulas.Operation import Operation
from keopscore.utils.code_gen_utils import c_zero_float
from keopscore.utils.misc_utils import KeOps_Error
# //////////////////////////////////////////////////////////////
# //// ONE-HOT REPRESENTATION : OneHot<F,DIM> ////
# //////////////////////////////////////////////////////////////
class OneHot(Operation):
string_id = "OneHot"
def __init__(self, f, dim):
if f.dim != 1:
KeOps_Error("One-hot representation is only supported for scalar formulas.")
if dim < 1:
KeOps_Error("A one-hot vector should have length >= 1.")
super().__init__(f)
self.dim = dim
self.params = (dim,)
def Op(self, out, table, arg0):
if out.dtype == "half2" and arg0.dtype == "half2":
return f"""
#pragma unroll
for (int k = 0; k < {self.dim}; k++)
{out.id}[k] = __heq2(h2rint(*{arg0.id}),__float2half2_rn(k));
"""
else:
string = out.assign(c_zero_float)
string += f"""
{out.id}[(int)(*{arg0.id}+.5)] = 1.0;
"""
return string
def DiffT(self, v, gradin):
from keopscore.formulas.variables.Zero import Zero
return Zero(v.dim)
| keops-main | keopscore/keopscore/formulas/maths/OneHot.py |
from keopscore.formulas.Operation import Operation
from keopscore.utils.code_gen_utils import value, c_zero_float, c_for_loop
from keopscore.utils.misc_utils import KeOps_Error
############################
###### ELEMENT "INJECTION" : ElemT(f,m,n)
############################
class ElemT(Operation):
string_id = "ElemT"
def __init__(self, f, n, m):
super().__init__(f, params=(n, m))
if f.dim != 1:
KeOps_Error("Input of ElemT should be a scalar")
self.dim = n
self.n = n
self.m = m
def Op(self, out, table, arg):
n, m = self.n, self.m
loop1, k = c_for_loop(0, m, 1, pragma_unroll=True)
string = loop1(out[k].assign(c_zero_float))
string += out[m].assign(value(arg))
loop2, k = c_for_loop(m + 1, n, 1, pragma_unroll=True)
string += loop2(out[k].assign(c_zero_float))
return string
def DiffT(self, v, gradin):
from keopscore.formulas.maths.Elem import Elem
f = self.children[0]
return f.DiffT(v, Elem(gradin, self.m))
# parameters for testing the operation (optional)
enable_test = True # enable testing for this operation
nargs = 1 # number of arguments
test_argdims = [1] # dimensions of arguments for testing
test_params = [5, 3] # dimensions of parameters for testing
def torch_op(x, n, m): # equivalent PyTorch operation
import torch
out = torch.zeros((*x.shape[:-1], n), device=x.device, dtype=x.dtype)
out[..., m][..., None] = x
return out
| keops-main | keopscore/keopscore/formulas/maths/ElemT.py |
from keopscore.formulas.VectorizedScalarOp import VectorizedScalarOp
from keopscore.formulas.maths.Sign import Sign
from keopscore.utils.math_functions import keops_abs
class Abs(VectorizedScalarOp):
"""the absolute value vectorized operation"""
string_id = "Abs"
ScalarOpFun = keops_abs
@staticmethod
def Derivative(f):
return Sign(f)
| keops-main | keopscore/keopscore/formulas/maths/Abs.py |
from .Abs import Abs
from .Acos import Acos
from .Add import Add
from .ArgMax import ArgMax
from .ArgMin import ArgMin
from .Asin import Asin
from .Atan import Atan
from .Atan2 import Atan2
from .Clamp import Clamp
from .ClampInt import ClampInt
from .Concat import Concat
from .Cos import Cos
from .DiffClampInt import DiffClampInt
from .Divide import Divide
from .Elem import Elem
from .ElemT import ElemT
from .Exp import Exp
from .Extract import Extract
from .ExtractT import ExtractT
from .Floor import Floor
from .GradMatrix import GradMatrix
from .IfElse import IfElse
from .IntInv import IntInv
from .Inv import Inv
from .Log import Log
from .MatVecMult import MatVecMult
from .Max import Max
from .Min import Min
from .Minus import Minus
from .Mod import Mod
from .Mult import Mult
from .Norm2 import Norm2
from .Normalize import Normalize
from .Pow import Pow
from .Powf import Powf
from .ReLU import ReLU
from .Round import Round
from .Rsqrt import Rsqrt
from .Scalprod import Scalprod
from .Sign import Sign
from .Sin import Sin
from .SinXDivX import SinXDivX
from .SqDist import SqDist
from .SqNorm2 import SqNorm2
from .SqNormDiag import SqNormDiag
from .SqNormIso import SqNormIso
from .Sqrt import Sqrt
from .Square import Square
from .Step import Step
from .Subtract import Subtract
from .Sum import Sum
from .SumT import SumT
from .SymSqNorm import SymSqNorm
from .TensorDot import TensorDot
from .TensorProd import TensorProd
from .VecMatMult import VecMatMult
from .WeightedSqDist import WeightedSqDist
from .WeightedSqNorm import WeightedSqNorm
from .XLogX import XLogX
__all__ = [
"Abs",
"Acos",
"Add",
"ArgMax",
"ArgMin",
"Asin",
"Atan",
"Atan2",
"Clamp",
"ClampInt",
"Concat",
"Cos",
"DiffClampInt",
"Divide",
"Elem",
"ElemT",
"Exp",
"Extract",
"ExtractT",
"GradMatrix",
"Floor",
"IfElse",
"IntInv",
"Inv",
"Log",
"MatVecMult",
"Max",
"Min",
"Minus",
"Mod",
"Mult",
"Norm2",
"Normalize",
"Pow",
"Powf",
"ReLU",
"Round",
"Rsqrt",
"Scalprod",
"Sign",
"Sin",
"SinXDivX",
"SqDist",
"SqNorm2",
"SqNormDiag",
"SqNormIso",
"Sqrt",
"Square",
"Step",
"Subtract",
"Sum",
"SumT",
"SymSqNorm",
"TensorDot",
"TensorProd",
"VecMatMult",
"WeightedSqDist",
"WeightedSqNorm",
"XLogX",
]
| keops-main | keopscore/keopscore/formulas/maths/__init__.py |
from keopscore.formulas.Operation import Broadcast
from keopscore.formulas.VectorizedScalarOp import VectorizedScalarOp
from keopscore.formulas.maths.Scalprod import Scalprod
from keopscore.formulas.maths.Square import Square
from keopscore.formulas.variables.Zero import Zero
from keopscore.utils.misc_utils import KeOps_Error
##########################
###### Divide #####
##########################
class Divide_Impl(VectorizedScalarOp):
"""the binary divide operation"""
string_id = "Divide"
print_spec = "/", "mid", 3
def ScalarOp(self, out, arg0, arg1):
"""returns the atomic piece of c++ code to evaluate the function on arg and return the result in out"""
return f"{out.id} = {arg0.id} / {arg1.id};\n"
# \diff_V (A/B) = ((\diff_V A) * B - A * (\diff_V B)) / B^2
def DiffT(self, v, gradin):
fa, fb = self.children
if fa.dim == 1 and fb.dim > 1:
return (
fa.DiffT(v, Scalprod(gradin, fb)) - fb.DiffT(v, fa * gradin)
) / Square(fb)
elif fb.dim == 1 and fa.dim > 1:
return (
fa.DiffT(v, fb * gradin) - fb.DiffT(v, Scalprod(gradin, fa))
) / Square(fb)
else:
return (fa.DiffT(v, fb * gradin) - fb.DiffT(v, fa * gradin)) / Square(fb)
# parameters for testing the operation (optional)
nargs = 2 # number of arguments
# N.B. The following separate function should theoretically be implemented
# as a __new__ method of the previous class, but this can generate infinite recursion problems
def Divide(arg0, arg1):
if isinstance(arg0, Zero):
return Broadcast(arg0, arg1.dim)
elif isinstance(arg1, Zero):
KeOps_Error("division by zero")
else:
return Divide_Impl(arg0, arg1)
| keops-main | keopscore/keopscore/formulas/maths/Divide.py |
from keopscore.formulas.Operation import Operation
from keopscore.formulas.variables.Zero import Zero
from keopscore.utils.code_gen_utils import value
from keopscore.utils.misc_utils import KeOps_Error
##########################
###### SumT #####
##########################
class SumT_Impl(Operation):
# the adjoint of the summation operation
string_id = "SumT"
def __init__(self, arg, dim):
super().__init__(arg, params=(dim,))
self.dim = dim
def Op(self, out, table, arg):
return out.assign(value(arg))
def DiffT(self, v, gradin):
from keopscore.formulas.maths.Sum import Sum
f = self.children[0]
return f.DiffT(v, Sum(gradin))
# N.B. The following separate function should theoretically be implemented
# as a __new__ method of the previous class, but this can generate infinite recursion problems
def SumT(arg, dim):
if arg.dim != 1:
KeOps_Error("dimension of argument must be 1 for SumT operation")
elif isinstance(arg, Zero):
return Zero(dim)
else:
return SumT_Impl(arg, dim)
| keops-main | keopscore/keopscore/formulas/maths/SumT.py |
from keopscore.formulas.Operation import Operation
from keopscore.formulas.variables.Zero import Zero
from keopscore.utils.code_gen_utils import (
c_zero_float,
c_for_loop,
c_if,
value,
c_variable,
)
from keopscore.utils.misc_utils import KeOps_Error
############################
###### ArgMax #####
############################
class ArgMax(Operation):
string_id = "ArgMax"
def __init__(self, f):
super().__init__(f)
if f.dim < 1:
KeOps_Error("ArgMax operation is only possible when dimension is non zero.")
self.dim = 1
def Op(self, out, table, arg):
tmp = c_variable(out.dtype)
loop, k = c_for_loop(1, arg.dim, 1, pragma_unroll=True)
string = value(out).assign(c_zero_float) + tmp.declare_assign(arg[0])
if out.dtype == "half2":
loop_string = f"""
// we have to work element-wise...
__half2 cond = __hlt2({tmp.id},{arg[k].id}); // cond = (tmp > outF[k]) (element-wise)
__half2 negcond = __float2half2_rn(1.0f)-cond; // negcond = 1-cond
*{out.id} = cond * __float2half2_rn({k.id}) + negcond * *{out.id}; // out = cond * k + (1-cond) * out
{tmp.id} = cond * {arg[k].id} + negcond * {tmp.id}; // tmp = cond * outF[k] + (1-cond) * tmp
"""
string += loop(loop_string)
else:
string += loop(
c_if(arg[k] > tmp, tmp.assign(arg[k]) + value(out).assign(k))
)
return string
def DiffT(self, v, gradin):
return Zero(v.dim)
# parameters for testing the operation (optional)
enable_test = True # enable testing for this operation
nargs = 1 # number of arguments
test_argdims = [5] # dimensions of arguments for testing
torch_op = "lambda x : torch.argmax(x, dim=-1, keepdim=True).type(x.dtype)"
no_torch_grad = True
| keops-main | keopscore/keopscore/formulas/maths/ArgMax.py |
from keopscore.formulas.VectorizedScalarOp import VectorizedScalarOp
from keopscore.formulas.variables.Zero import Zero
from keopscore.utils.math_functions import keops_floor
class Floor(VectorizedScalarOp):
"""the floor vectorized operation"""
string_id = "Floor"
ScalarOpFun = keops_floor
def DiffT(self, v, gradin):
return Zero(v.dim)
| keops-main | keopscore/keopscore/formulas/maths/Floor.py |
from keopscore.formulas.maths.Scalprod import Scalprod
class SqNorm2:
def __new__(cls, arg0):
return Scalprod(arg0, arg0)
enable_test = False
| keops-main | keopscore/keopscore/formulas/maths/SqNorm2.py |
from keopscore.formulas.VectorizedScalarOp import VectorizedScalarOp
from keopscore.utils.math_functions import keops_diffclampint
"""
//////////////////////////////////////////////////////////////
//// DIFFCLAMPINT : DiffClampInt< F, A, B > ////
//////////////////////////////////////////////////////////////
// DiffClampInt(x,a,b) = 0 if x<a, 1 if a<=x<=b, 0 if b<x
// N.B. used as derivative of ClampInt operation
"""
class DiffClampInt(VectorizedScalarOp):
string_id = "DiffClampInt"
def __init__(self, x, a, b):
super().__init__(x, params=(a, b))
ScalarOpFun = keops_diffclampint
def DiffT(self, v, gradin):
from keopscore.formulas import Zero
return Zero(v.dim)
# parameters for testing the operation (optional)
enable_test = (
False # (because it will be tested anyway if we test the gradient of ClampInt)
)
| keops-main | keopscore/keopscore/formulas/maths/DiffClampInt.py |
from keopscore.formulas.maths.SqNorm2 import SqNorm2
class SqNormIso:
"""
ISOTROPIC NORM : SqNormIso(S,A)
"""
def __new__(cls, S, A):
return S * SqNorm2(A)
enable_test = False
| keops-main | keopscore/keopscore/formulas/maths/SqNormIso.py |
from keopscore.formulas.VectorizedScalarOp import VectorizedScalarOp
from keopscore.utils.math_functions import keops_ifelse
class IfElse(VectorizedScalarOp):
"""the if/else vectorized operation
IfElse(f,a,b) = a if f>=0, b otherwise
"""
string_id = "IfElse"
ScalarOpFun = keops_ifelse
def DiffT(self, v, gradin):
f, a, b = self.children
return IfElse(f, a.DiffT(v, gradin), b.DiffT(v, gradin))
# parameters for testing the operation (optional)
nargs = 3 # number of arguments
| keops-main | keopscore/keopscore/formulas/maths/IfElse.py |
from keopscore.formulas.VectorizedScalarOp import VectorizedScalarOp
from keopscore.utils.math_functions import keops_powf
class Powf(VectorizedScalarOp):
"""the Power vectorized operation"""
string_id = "Powf"
ScalarOpFun = keops_powf
@staticmethod
def Derivative(a, b):
from keopscore.formulas.maths.Log import Log
return b * Powf(a, b - 1), Log(a) * Powf(a, b)
# parameters for testing the operation (optional)
test_ranges = [(0, 2), (-1, 1)] # ranges of arguments
torch_op = "lambda x,y : torch.pow(x, y)"
| keops-main | keopscore/keopscore/formulas/maths/Powf.py |
from keopscore.formulas.Operation import Operation
from keopscore.formulas.maths.ArgMin import ArgMin
from keopscore.formulas.maths.OneHot import OneHot
from keopscore.utils.code_gen_utils import c_for_loop, c_if, value
from keopscore.utils.misc_utils import KeOps_Error
############################
###### Min #####
############################
class Min(Operation):
string_id = "Min"
def __init__(self, f):
super().__init__(f)
if f.dim < 1:
KeOps_Error("Min operation is only possible when dimension is non zero.")
self.dim = 1
def Op(self, out, table, arg):
f = self.children[0]
loop, k = c_for_loop(1, f.dim, 1, pragma_unroll=True)
string = value(out).assign(arg[0])
if out.dtype == "half2":
loop_string = f"""
// we have to work element-wise...
__half2 cond = __hgt2(*{out.id},{arg[k].id}); // cond = (out > outF[k]) (element-wise)
__half2 negcond = __float2half2_rn(1.0f)-cond; // negcond = 1-cond
*{out.id} = cond * {arg[k].id} + negcond * *{out.id}; // out = cond * outF[k] + (1-cond) * out
"""
string += loop(loop_string)
else:
string += loop(c_if(arg[k] < value(out), value(out).assign(arg[k])))
return string
def DiffT(self, v, gradin):
f = self.children[0]
return f.DiffT(v, OneHot(ArgMin(f), f.dim) * gradin)
# parameters for testing the operation (optional)
enable_test = True # enable testing for this operation
nargs = 1 # number of arguments
test_argdims = [5] # dimensions of arguments for testing
torch_op = "lambda x : torch.min(x, dim=-1, keepdim=True)[0].type(x.dtype)"
| keops-main | keopscore/keopscore/formulas/maths/Min.py |
from keopscore.formulas.Operation import Operation
from keopscore.utils.code_gen_utils import c_zero_float, VectCopy
from keopscore.utils.misc_utils import KeOps_Error
# //////////////////////////////////////////////////////////////
# //// VECTOR "INJECTION" : ExtractT<F,START,DIM> ////
# //////////////////////////////////////////////////////////////
class ExtractT(Operation):
string_id = "ExtractT"
def __init__(self, f, start, dim):
if start + f.dim > dim or start < 0:
KeOps_Error("Index out of bound in ExtractT")
super().__init__(f, params=(start, dim))
self.start = start
self.dim = dim
self.dimarg = f.dim
def Op(self, out, table, arg):
# returns the atomic piece of c++ code to evaluate the function on arg and return
# the result in out
out_prev, out_mid, out_end = out.split(
self.start, self.dimarg, self.dim - self.start - self.dimarg
)
return "\n".join(
(
out_prev.assign(c_zero_float),
VectCopy(out_mid, arg),
out_end.assign(c_zero_float),
)
)
def DiffT(self, v, gradin):
from keopscore.formulas.maths.Extract import Extract
f = self.children[0]
return f.DiffT(v, Extract(gradin, self.start, f.dim))
# parameters for testing the operation (optional)
enable_test = True # enable testing for this operation
nargs = 1 # number of arguments
test_argdims = [5] # dimensions of arguments for testing
test_params = [3, 10] # dimensions of parameters for testing
def torch_op(x, s, d): # equivalent PyTorch operation
import torch
out = torch.zeros((*x.shape[:-1], d), device=x.device, dtype=x.dtype)
out[..., s : (s + x.shape[-1])] = x
return out
| keops-main | keopscore/keopscore/formulas/maths/ExtractT.py |
from keopscore.formulas.VectorizedScalarOp import VectorizedScalarOp
from keopscore.formulas.maths.ClampInt import ClampInt
from keopscore.utils.math_functions import keops_clamp
class Clamp(VectorizedScalarOp):
"""Clamp(x,a,b) = a if x<a, x if a<=x<=b, b if b<x"""
string_id = "Clamp"
ScalarOpFun = keops_clamp
def DiffT(self, v, gradin):
# N.B. Clamp(F,G,H) = Clamp((F-G)/(H-G),0,1) * (H-G) + G
# We use this fact to avoid writing another custom operation for the gradient.
# (This may be slower however...)
f, g, h = self.children
Alt_Clamp = ClampInt((f - g) / (h - g), 0, 1) * (h - g) + g
return Alt_Clamp.DiffT(v, gradin)
# parameters for testing the operation (optional)
nargs = 3 # number of arguments
torch_op = None # equivalent PyTorch operation
| keops-main | keopscore/keopscore/formulas/maths/Clamp.py |
from keopscore.formulas.Operation import Operation
from keopscore.utils.code_gen_utils import use_pragma_unroll
####################################
###### Tensor Dot Product #####
####################################
def prod(x):
# product of all elements in list of integers
res = 1
for item in x:
res *= item
return res
def select(x, ind):
# indexing of list via list of integers
return [x[i] for i in ind]
def delete(x, ind):
# delete items given by indices in list
n = len(x)
indkeep = list(set(range(n)) - set(ind))
indkeep.sort()
return select(x, indkeep)
def cumprod_array(x):
# special cumulative product
if len(x) == 0:
return x
else:
def cumprod(x):
res = x.copy()
for i in range(1, len(x)):
res[i] *= res[i - 1]
return res
return cumprod(x[1:][::-1])[::-1] + [1]
def permutation(perm, arr):
if perm is None:
return arr
else:
tmp = sorted(range(len(perm)), key=perm.__getitem__)
return select(arr, tmp)
class TensorDot(Operation):
string_id = "TensorDot"
def __init__(self, fa, fb, dimsfa, dimsfb, contfa, contfb, permute=None):
dimsfa = list(dimsfa)
dimsfb = list(dimsfb)
contfa = list(contfa)
contfb = list(contfb)
assert select(dimsfb, contfb) == select(dimsfa, contfa)
assert fa.dim == prod(dimsfa)
assert fb.dim == prod(dimsfb)
super().__init__(fa, fb)
self.dimfa = dimsfa
self.dimfb = dimsfb
self.contdims = select(dimsfa, contfa)
self.indices_keepdim_a = delete(list(range(len(dimsfa))), contfa)
self.keepdims_a = delete(dimsfa, contfa)
self.contdims_a = select(dimsfa, contfa)
self.list_strides_dimsfa = cumprod_array(dimsfa)
self.indices_keepdim_b = delete(list(range(len(dimsfb))), contfb)
self.keepdims_b = delete(dimsfb, contfb)
self.contdims_b = select(dimsfb, contfb)
self.list_strides_dimsfb = cumprod_array(dimsfb)
self.keepdims = self.keepdims_a + self.keepdims_b
self.list_strides_keepdim = cumprod_array(permutation(permute, self.keepdims))
self.dim = fa.dim * fb.dim
self.dim = int(self.dim / prod(self.contdims) ** 2) if len(contfa) else self.dim
if permute is None:
permute = list(range(len(self.keepdims)))
else:
assert permutation(permute, permute) == list(range(len(self.keepdims)))
self.permute = permute
# loop
self.loopdim = self.keepdims + self.contdims_a
self.dimloop = prod(self.loopdim)
self.number_of_dimloop = len(dimsfa) + len(dimsfb) - len(contfa)
self.ala = list(range(len(self.keepdims_a))) + list(
range(len(self.keepdims), self.number_of_dimloop)
)
self.ali = self.indices_keepdim_a + contfa
self.list_indices_a_intot = permutation(self.ali, self.ala)
self.bla = list(range(len(self.keepdims_a), len(self.keepdims))) + list(
range(len(self.keepdims), self.number_of_dimloop)
)
self.bli = self.indices_keepdim_b + contfb
self.list_indices_b_intot = permutation(self.bli, self.bla)
# Gradient
self.dimfa_grad = permutation(permute, self.keepdims)
self.list_indices_keepdim_a_inout = list(range(0, len(self.keepdims_a)))
self.reordered_contfa = permutation(contfb, contfa)
self.reordered_keepdim_a = permutation(
select(permute, self.list_indices_keepdim_a_inout), self.indices_keepdim_a
)
self.moveaxis_a = self.reordered_keepdim_a + self.reordered_contfa
self.list_indices_keepdim_b_inout = list(
range(len(self.keepdims_a), len(self.keepdims))
)
self.reordered_contfb = permutation(contfa, contfb)
self.reordered_keepdim_b = permutation(
select(permute, self.list_indices_keepdim_b_inout), self.indices_keepdim_b
)
self.moveaxis_b = self.reordered_keepdim_b + self.reordered_contfb
self.contfa_grad = select(permute, self.list_indices_keepdim_b_inout)
self.contfb_grad = select(permute, self.list_indices_keepdim_a_inout)
def Op(self, out, table, arg0, arg1):
# returns the atomic piece of c++ code to evaluate the function on arg and return
# the result in out
str_code = ""
for i in range(len(self.loopdim)):
str_code += (
f"for(int TD_var_{chr(70 + i)}=0; TD_var_{chr(70 + i)}<{self.loopdim[i]}; ++TD_var_{chr(70 + i)})"
+ "{\n"
+ i * " "
)
list_indices_keepdim = permutation(self.permute, range(len(self.keepdims)))
str_out_indices = ""
for i, v in enumerate(list_indices_keepdim):
str_out_indices += (
f"TD_var_{chr(70 + v)} * {self.list_strides_keepdim[i]} + "
)
str_a_indices = ""
for i, v in enumerate(self.list_indices_a_intot):
str_a_indices += f"TD_var_{chr(70 + v)} * {self.list_strides_dimsfa[i]} + "
str_b_indices = ""
for i, v in enumerate(self.list_indices_b_intot):
str_b_indices += f"TD_var_{chr(70 + v)} * {self.list_strides_dimsfb[i]} + "
str_code += (
len(self.loopdim) * " "
+ f"{out.id}[{str_out_indices[:-2]}] += {arg0.id}[{str_a_indices[:-2]}] * {arg1.id}[{str_b_indices[:-2]}];\n"
)
str_code += len(self.loopdim) * "}\n"
return f"""
#if C_CONTIGUOUS // row major
{use_pragma_unroll()}
for (int i = 0; i < {out.dim}; i++)
{out.id}[i] = ({out.dtype})(0.0f);
{use_pragma_unroll()}
{str_code}
#else // column major
#endif
"""
def DiffT(self, v, gradin):
f = self.children[0]
g = self.children[1]
return f.DiffT(
v,
TensorDot(
gradin,
g,
self.dimfa_grad,
self.dimfb,
self.contfa_grad,
self.indices_keepdim_b,
self.moveaxis_a,
),
) + g.DiffT(
v,
TensorDot(
gradin,
f,
self.dimfa_grad,
self.dimfa,
self.contfb_grad,
self.indices_keepdim_a,
self.moveaxis_b,
),
)
| keops-main | keopscore/keopscore/formulas/maths/TensorDot.py |
from keopscore.formulas.VectorizedScalarOp import VectorizedScalarOp
from keopscore.formulas.variables.Zero import Zero
from keopscore.utils.math_functions import keops_step
class Step(VectorizedScalarOp):
"""the Step vectorized operation"""
string_id = "Step"
ScalarOpFun = keops_step
def DiffT(self, v, gradin):
return Zero(v.dim)
| keops-main | keopscore/keopscore/formulas/maths/Step.py |
from keopscore.formulas.VectorizedScalarOp import VectorizedScalarOp
from keopscore.formulas.variables.Zero import Zero
from keopscore.utils.math_functions import keops_round
class Round(VectorizedScalarOp):
"""the Round vectorized operation
Round(f,d) where d is integer, rounds f to d decimals
"""
def __init__(self, f, d):
super().__init__(f, params=(d,))
string_id = "Round"
ScalarOpFun = keops_round
def DiffT(self, v, gradin):
return Zero(v.dim)
# parameters for testing the operation (optional)
nargs = 1 # number of arguments
test_params = [3] # parameters to try
torch_op = None # equivalent PyTorch operation
| keops-main | keopscore/keopscore/formulas/maths/Round.py |
from keopscore.formulas.VectorizedScalarOp import VectorizedScalarOp
from keopscore.formulas.maths.Step import Step
from keopscore.utils.math_functions import keops_relu
class ReLU(VectorizedScalarOp):
"""the ReLU vectorized operation"""
string_id = "ReLU"
ScalarOpFun = keops_relu
@staticmethod
def Derivative(f):
return Step(f)
| keops-main | keopscore/keopscore/formulas/maths/ReLU.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.