python_code
stringlengths 0
679k
| repo_name
stringlengths 9
41
| file_path
stringlengths 6
149
|
---|---|---|
################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
################################################################################
import numpy as np
from cuda import cuda
from pycutlass.memory_manager import *
from typing import TYPE_CHECKING
try:
import torch
torch_available = True
except ImportError:
torch_available = False
if TYPE_CHECKING:
import torch
try:
import cupy as cp
cupy_available = True
except ImportError:
cupy_available = False
if TYPE_CHECKING:
import cupy as cp
class NumpyFrontend:
"""
Frontend node for numpy
"""
@staticmethod
def argument(np_tensor: 'np.ndarray', is_output: 'bool') -> cuda.CUdeviceptr:
"""Convert the input numpy tensor to CUDA device pointer
:param np_tensor: input numpy nd array
:param is_output: whether the tensor is output
:return: CUDA device pointer
"""
# copy the data to device
if is_output:
return device_mem_alloc(np_tensor.size * np_tensor.itemsize)
else:
return todevice(np_tensor)
class TorchFrontend:
"""
Frontend node for torch
"""
@staticmethod
def argument(torch_tensor: 'torch.Tensor') -> cuda.CUdeviceptr:
"""Convert the input torch tensor to CUDA device pointer
:param torch_tensor: input torch tensor
:param is_output: whether the tensor is output
:return: CUDA device pointer
"""
# check the device of torch_tensor
if not torch_tensor.is_cuda:
torch_tensor = torch_tensor.to("cuda")
return cuda.CUdeviceptr(torch_tensor.data_ptr())
class CupyFrontend:
"""
Frontend node for cupy
"""
@staticmethod
def argument(cupy_ndarray: 'cp.ndarray'):
return cuda.CUdeviceptr(int(cupy_ndarray.data.ptr))
| warp-main | warp/native/cutlass/tools/library/scripts/pycutlass/src/pycutlass/frontend.py |
import re
def SubstituteTemplate(template, values):
text = template
changed = True
while changed:
changed = False
for key, value in values.items():
regex = "\\$\\{%s\\}" % key
newtext = re.sub(regex, value, text)
if newtext != text:
changed = True
text = newtext
return text
from pycutlass.type_hint import *
from pycutlass.tensor_ref import *
from pycutlass.operation import *
from pycutlass.epilogue import *
from pycutlass.parser import *
from pycutlass.compiler import ArtifactManager
from pycutlass.memory_manager import *
from pycutlass.arguments import *
from pycutlass.library import *
from pycutlass.c_types import *
from pycutlass.gemm_operation import *
from pycutlass.conv2d_operation import *
from pycutlass.compiler import *
from pycutlass.utils import *
from pycutlass.frontend import *
from pycutlass.reduction_operation import *
from pycutlass.compiler import *
# module-wide variables
import sys
this = sys.modules[__name__]
# artifact manager
this.compiler = ArtifactManager()
def get_memory_pool(init_pool_size=0, max_pool_size=2**34):
this.memory_pool = PoolMemoryManager(
init_pool_size=init_pool_size,
max_pool_size=max_pool_size
)
return this.memory_pool
| warp-main | warp/native/cutlass/tools/library/scripts/pycutlass/src/pycutlass/__init__.py |
################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
################################################################################
from typeguard import typechecked
from cuda import cuda
from typing import Union
import numpy as np
from typeguard import typechecked
from pycutlass import *
# @typechecked
class Conv2dArguments(ArgumentBase):
"""
Argument wrapper for Conv2d. It encodes problem information and
user-provide tensors into the kernel's argument.
:param operation: the Conv2d operation to take the argument
:type operation: :class:`pycutlass.Conv2dOperation`
:param problem_size: the Conv2d problem size
:type problem_size: :class:`cutlass.conv.Conv2dProblemSize`
:param A: tensor A
:type A: cuda.CUdeviceptr | numpy.ndarray | torch.Tensor | cupy.ndarray
:param B: tensor B
:type B: cuda.CUdeviceptr | numpy.ndarray | torch.Tensor | cupy.ndarray
:param C: tensor C
:type C: cuda.CUdeviceptr | numpy.ndarray | torch.Tensor | cupy.ndarray
:param D: tensor D
:type D: cuda.CUdeviceptr | numpy.ndarray | torch.Tensor | cupy.ndarray
:param split_k_mode: conv2d split K mode, defaults to
cutlass.conv.SplitKMode.Serial
:type split_k_mode: cutlass.conv.SplitKMode, optional
:param output_op: output operator, optional
:type output_op: :class:`pycutlass.LinearCombinationFunctorArguments`
"""
def __init__(self, operation: 'Conv2dOperation',
problem_size: 'cutlass.conv.Conv2dProblemSize',
A: 'Union[cuda.CUdeviceptr, np.ndarray, torch.Tensor]',
B: 'Union[cuda.CUdeviceptr, np.ndarray, torch.Tensor]',
C: 'Union[cuda.CUdeviceptr, np.ndarray, torch.Tensor]',
D: 'Union[cuda.CUdeviceptr, np.ndarray, torch.Tensor]',
split_k_mode: 'cutlass.conv.SplitKMode'
= cutlass.conv.SplitKMode.Serial, **kwargs) -> None:
self.operation = operation
#: convolution kind
self.conv_kind: cutlass.conv.Operator = operation.conv_kind
self.layout_A: cutlass.layout = operation.A.layout
self.layout_B: cutlass.layout = operation.B.layout
self.layout_C: cutlass.layout = operation.C.layout
self.element_A = operation.A.element
self.element_B = operation.B.element
self.element_C = operation.C.element
if self.layout_C == cutlass.TensorNC32HW32:
B = self.reorder_tensor_B(B, problem_size)
super().__init__(A, B, C, D, **kwargs)
# preprocessing output ops
if 'output_op' in kwargs.keys() and \
split_k_mode != cutlass.conv.SplitKMode.Parallel:
self.output_op = kwargs['output_op']
else:
self.output_op = self.operation.epilogue_type(1.0, 0.0)
if "split_k_slices" in kwargs.keys():
self.split_k_mode = split_k_mode
self.split_k_slices = kwargs["split_k_slices"]
else:
self.split_k_mode = cutlass.conv.SplitKMode.Serial
self.split_k_slices = 1
#: problem_size
self.problem_size: cutlass.conv.Conv2dProblemSize = problem_size
self.problem_size.split_k_slices = self.split_k_slices
if hasattr(self, "tensor_c_numel"):
c_coord = cutlass.conv.implicit_gemm_tensor_c_extent(
self.conv_kind, problem_size)
if (self.tensor_c_numel == c_coord.at(3) and
self.tensor_c_numel < c_coord.size()):
self.bias = True
#
# initialize the argument
#
self.initialize()
# @typechecked
def reorder_tensor_B(self, tensor_B: 'np.ndarray',
problem_size: 'cutlass.conv.Conv2dProblemSize'):
"""
Reorder tensor_B for interleaved layout
:param tensor_B: input tensor B
:type tensor_B: numpy.ndarray
:param problem_size: Conv2d problem size
:type problem_size: :class:`cutlass.conv.Conv2dProblemSize`
:return: reordered tensor B
:rtype: numpy.ndarray
"""
reordered_tensor_B = np.empty_like(tensor_B)
tensor_ref_B = self.get_tensor_ref(
tensor_B, self.element_B, self.layout_B, problem_size, "b")
reordered_tensor_ref_B = self.get_tensor_ref(
reordered_tensor_B, self.element_B,
self.layout_B, problem_size, "b")
cutlass.conv.host.reorder_convK(
reordered_tensor_ref_B, tensor_ref_B, self.conv_kind, problem_size)
return reordered_tensor_B
def get_tensor_ref(
self, tensor, dtype, tensor_layout, problem_size, operand):
if operand == "a":
tensor_coord = cutlass.conv.implicit_gemm_tensor_a_extent(
self.conv_kind, problem_size)
elif operand == "b":
tensor_coord = cutlass.conv.implicit_gemm_tensor_b_extent(
self.conv_kind, problem_size)
elif operand in ["c", "d"]:
tensor_coord = cutlass.conv.implicit_gemm_tensor_c_extent(
self.conv_kind, problem_size)
else:
raise ValueError("unknown operand: " + operand)
# Zero stride trick
if operand == "c" and self.bias:
tensor_coord = cutlass.Tensor4DCoord(0, 0, 0, 0)
layout = tensor_layout.packed(tensor_coord)
return TensorRef(tensor, dtype, layout).tensor_ref
def get_arguments(self, semaphore):
ref_A = TensorRef_(self.get_tensor_ref(
self.ptr_A, self.element_A, self.layout_A, self.problem_size, "a"))
ref_B = TensorRef_(self.get_tensor_ref(
self.ptr_B, self.element_B, self.layout_B, self.problem_size, "b"))
ref_C = TensorRef_(self.get_tensor_ref(
self.ptr_C, self.element_C, self.layout_C, self.problem_size, "c"))
ref_D = TensorRef_(self.get_tensor_ref(
self.ptr_D, self.element_C, self.layout_C, self.problem_size, "d"))
self.c_arguments = self.operation.argument_type(
Conv2DProblemSize(self.problem_size),
ref_A, ref_B, ref_C, ref_D, self.output_op, self.split_k_mode
)
self.semaphore = semaphore
def initialize(self):
"""
Initialize the kernel arguments handling following stuffs
1. get kernel launch configuration including grid, cta size,
and dynamic shared memory capacity
2. allocate and initialize device workspace
3. get kernel params as bytearray for NVRTC input
"""
# get launch configuration
self.launch_config = self.operation.rt_module.plan(self)
# allocate and initialize device workspace
device_workspace_size = \
self.operation.rt_module.get_device_workspace_size(self)
if device_workspace_size > 0:
self.workspace_buffer = device_mem_alloc(device_workspace_size)
workspace_ptr = self.workspace_buffer.ptr
err, = cuda.cuMemsetD32(
workspace_ptr, 0, device_workspace_size // 4)
else:
workspace_ptr = None
# get kernel params as bytearray
semaphore = 0
if workspace_ptr is not None and \
self.split_k_mode == cutlass.conv.SplitKMode.Parallel:
self.ptr_D = workspace_ptr
elif workspace_ptr is not None and \
self.split_k_mode == cutlass.conv.SplitKMode.Serial:
semaphore = workspace_ptr
self.get_arguments(semaphore)
params_ = self.operation.rt_module.get_args(ctypes.byref(
self.c_arguments), ctypes.c_void_p(int(self.semaphore)))
self.host_workspace = bytearray(params_.contents)
self.device_workspace = None
def sync(self):
"""
Synchronize the arguments. If the input tensor is in host,
copy it from device to host.
"""
return super().sync()
# @typechecked
class Conv2dRT(ExecutableOperation):
"""
Conv2dRT manages the CUTLASS runtime components
"""
KernelTemplate = r'''
extern "C"
__global__ void
${operation_name}(${operation_name}${operation_suffix}::Params params) {
// Dynamic shared memory base pointer
extern __shared__ int SharedStorageBase[];
// Declare pointer to dynamic shared memory.
${operation_name}${operation_suffix}::SharedStorage *shared_storage =
reinterpret_cast<${operation_name}${operation_suffix}::SharedStorage *>(SharedStorageBase);
${operation_name}${operation_suffix} op;
op(params, *shared_storage);
}
'''
HostTemplate = r'''
extern "C" {
// Get the size of params in bytes
int ${operation_name}_get_param_size(){
return sizeof(${operation_name}${operation_suffix}::Params);
}
// Get the size of dynamic shared memory in bytes
int ${operation_name}_shared_memory_size() {
return int(sizeof(${operation_name}${operation_suffix}::SharedStorage));
}
// Get the params as byte array
char* ${operation_name}_get_params(${operation_name}${operation_suffix}::Arguments* arguments, int *semaphore=nullptr){
typename ${operation_name}${operation_suffix}::Params* params;
params = new ${operation_name}${operation_suffix}::Params(*arguments, semaphore);
char *bytes = ((char*)(params));
char *output = new char[sizeof(${operation_name}${operation_suffix}::Params)];
for (unsigned int i = 0; i < sizeof(${operation_name}${operation_suffix}::Params); i ++)
output[i] = bytes[i];
return output;
}
}
'''
def __init__(self, operation: 'Conv2dOperation'):
super().__init__(operation)
self.argument_type, self.epilogue_type = get_conv2d_arguments(operation.epilogue_functor)
self.argtype = [ctypes.POINTER(self.argument_type), ctypes.c_void_p]
self.conv_kind = operation.conv_kind
self.operation: Conv2dOperation = operation
self.emitter = EmitConv2dInstance('_type')
self.threads: int = operation.tile_description.num_threads
self.swizzle_functor = operation.swizzling_functor
def emit(self):
return self.emitter.emit(self.operation)
# @typechecked
def get_device_workspace_size(self, arguments: Conv2dArguments):
workspace_bytes = 0
launch_config = arguments.launch_config
self.conv_kind = self.operation.conv_kind
if arguments.split_k_mode == cutlass.conv.SplitKMode.Parallel:
problem_size = arguments.problem_size
workspace_bytes = DataTypeSize[self.operation.C.element] \
* launch_config.grid[2] * cutlass.conv.implicit_gemm_tensor_c_size(
self.conv_kind, problem_size
) // 8
elif arguments.split_k_mode == cutlass.conv.SplitKMode.Serial and \
arguments.split_k_slices > 1:
workspace_bytes = launch_config.grid[0] * launch_config.grid[1] * 4
return workspace_bytes
# @typechecked
def plan(self, arguments: Conv2dArguments):
tile_size = cutlass.gemm.GemmCoord(
self.operation.tile_description.threadblock_shape[0],
self.operation.tile_description.threadblock_shape[1],
self.operation.tile_description.threadblock_shape[2]
)
grid = self.swizzle_functor.get_grid_shape(
self.swizzle_functor.get_tiled_shape(
self.conv_kind, arguments.problem_size,
tile_size, arguments.split_k_slices
)
)
return LaunchConfiguration(
[grid.x, grid.y, grid.z], [self.threads, 1, 1],
self.shared_memory_capacity)
def initialize(self):
err, = cuda.cuFuncSetAttribute(
self.kernel,
attrib=cuda.CUfunction_attribute.CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES,
value=self.shared_memory_capacity)
if err != cuda.CUresult.CUDA_SUCCESS:
raise RuntimeError('Cuda Error: {}'.format(err))
#
class Conv2dOperation:
"""
CUTLASS Conv2d operation description.
:param conv_kind: convolution operator
:type conv_kind: :class:`cutlass.conv.Operator`
:param iterator_algorithm: Selects among several implementation
variants trading off performance with simplicity
:type iterator_algorithm: :class:`cutlass.conv.IteratorAlgorithm`
:param arch: GPU compute capability (sm_xx)
:type arch: int
:param tile_description: tile description
:type tile_description: :class:`pycutlass.TileDescription`
:param A: tensor A description
:type A: :class:`pycutlass.TensorDescription`
:param B: tensor B description
:type B: :class:`pycutlass.TensorDescription`
:param C: tensor C description
:type C: :class:`pycutlass.TensorDescription`
:param D: tensor D description
:type D: :class:`pycutlass.TensorDescription`
:param element_epilogue: element type for computation in epilogue \
:type element_epilogue: cutlass.int8 | cutlass.int32 | cutlass.float16 | \
cutlass.bfloat16 | cutlass.float32 | cutlass.float64
:param stride_support: distinguish among partial specializations that \
accelerate certain problems where convolution stride is unit \
:type stride_support: :class:`cutlass.conv.StrideSupport`
:param epilogue_functor: convolution epilogue functor
:type epilogue_functor: :class:`EpilogueFunctor`
:param swizzling_functor: threadblock swizzling functor
"""
#
def __init__(self,
conv_kind: cutlass.conv.Operator,
iterator_algorithm: cutlass.conv.IteratorAlgorithm,
arch: int, tile_description: TileDescription,
A: TensorDescription, B: TensorDescription, C: TensorDescription,
stride_support, epilogue_functor,
swizzling_functor=cutlass.IdentitySwizzle1):
self.operation_kind: OperationKind = OperationKind.Conv2d
self.arch: int = arch
self.tile_description: TileDescription = tile_description
self.conv_kind = conv_kind
self.A: TensorDescription = A
self.B: TensorDescription = B
self.C: TensorDescription = C
self.epilogue_functor = epilogue_functor
self.iterator_algorithm = iterator_algorithm
self.stride_support = stride_support
self.swizzling_functor = swizzling_functor()
self.rt_module: Conv2dRT = Conv2dRT(self)
self.argument_type = self.rt_module.argument_type
self.epilogue_type = self.rt_module.epilogue_type
def run(self, arguments: Conv2dArguments) -> cuda.CUresult:
"""
Launch the cuda kernel with input arguments
:param arguments: conv2d arguments
:type arguments: :class:`pycutlass.Conv2dArguments`
"""
# launch the kernel
err = self.rt_module.run(
arguments.host_workspace,
arguments.device_workspace,
arguments.launch_config)
if err != cuda.CUresult.CUDA_SUCCESS:
raise RuntimeError('CUDA Error %s' % str(err))
return err
#
# Get function name
#
def procedural_name(self):
''' The full procedural name indicates architecture, extended name, tile size, and layout. '''
return self.configuration_name()
#
def configuration_name(self):
''' The full procedural name indicates architecture, extended name, tile size, and layout. '''
opcode_class_name = OpcodeClassNames[self.tile_description.math_instruction.opcode_class]
threadblock = "%dx%d_%dx%d" % (
self.tile_description.threadblock_shape[0],
self.tile_description.threadblock_shape[1],
self.tile_description.threadblock_shape[2],
self.tile_description.stages
)
if self.stride_support == StrideSupport.Unity:
configuration_name = "cutlass_${opcode_class}_${extended_name}_${threadblock}_${layout}_unity_stride_align${alignment}"
else:
configuration_name = "cutlass_${opcode_class}_${extended_name}_${threadblock}_${layout}_align${alignment}"
return SubstituteTemplate(
configuration_name,
{
'opcode_class': opcode_class_name,
'extended_name': self.extended_name(),
'threadblock': threadblock,
'layout': self.layout_name(),
'alignment': "%d" % self.A.alignment,
}
)
#
def extended_name(self):
''' Append data types if they differ from compute type. '''
if self.C.element != self.tile_description.math_instruction.element_accumulator and \
self.A.element != self.tile_description.math_instruction.element_accumulator:
extended_name = "${element_c}_${core_name}_${element_a}"
elif self.C.element == self.tile_description.math_instruction.element_accumulator and \
self.A.element != self.tile_description.math_instruction.element_accumulator:
extended_name = "${core_name}_${element_a}"
else:
extended_name = "${core_name}"
extended_name = SubstituteTemplate(extended_name, {
'element_a': DataTypeNames[self.A.element],
'element_c': DataTypeNames[self.C.element],
'core_name': self.core_name()
})
return extended_name
#
def layout_name(self):
return "%s" % (ShortLayoutTypeNames[self.A.layout])
#
def core_name(self):
''' The basic operation kind is prefixed with a letter indicating the accumulation type. '''
intermediate_type = ''
if self.tile_description.math_instruction.opcode_class == cutlass.OpClass.TensorOp:
inst_shape = "%d%d%d" % tuple(
self.tile_description.math_instruction.instruction_shape)
if self.tile_description.math_instruction.element_a != self.A.element and \
self.tile_description.math_instruction.element_a != self.accumulator_type():
intermediate_type = DataTypeNames[self.tile_description.math_instruction.element_a]
else:
inst_shape = ''
return "%s%s%s%s_%s" % (ShortDataTypeNames[self.accumulator_type()],
inst_shape, intermediate_type, ConvKindNames[self.conv_kind], IteratorAlgorithmNames[self.iterator_algorithm])
#
def is_complex(self):
complex_operators = [
MathOperation.multiply_add_complex,
MathOperation.multiply_add_complex_gaussian
]
return self.tile_description.math_instruction.math_operation in complex_operators
#
def accumulator_type(self):
accum = self.tile_description.math_instruction.element_accumulator
if self.is_complex():
return get_complex_from_real(accum)
return accum
###################################################################################################
#
# Emits single instances of a CUTLASS device-wide operator
#
###################################################################################################
class EmitConv2dInstance:
def __init__(self, operation_suffix=''):
self.operation_suffix = operation_suffix
self.includes = [
"cutlass/cutlass.h",
"cutlass/conv/kernel/default_conv2d_fprop.h",
"cutlass/conv/kernel/default_conv2d_dgrad.h",
"cutlass/conv/kernel/default_conv2d_wgrad.h"
]
self.template = """
// Conv2d${conv_kind_name} ${iterator_algorithm_name} kernel instance "${operation_name}"
using ${operation_name}_base =
typename cutlass::conv::kernel::DefaultConv2d${conv_kind_name}<
${element_a},
${layout_a},
${element_b},
${layout_b},
${element_c},
${layout_c},
${element_accumulator},
${opcode_class},
${arch},
cutlass::gemm::GemmShape<${threadblock_shape_m}, ${threadblock_shape_n}, ${threadblock_shape_k}>,
cutlass::gemm::GemmShape<${warp_shape_m}, ${warp_shape_n}, ${warp_shape_k} >,
cutlass::gemm::GemmShape<${instruction_shape_m}, ${instruction_shape_n}, ${instruction_shape_k}>,
${epilogue_functor},
${swizzling_functor}, // cutlass::gemm::threadblock::GemmSplitKIdentityThreadblockSwizzle<>,
${stages},
${math_operator},
${iterator_algorithm},
${stride_support},
${align_a},
${align_b}
>::Kernel;
struct ${operation_name}${operation_suffix}:
public ${operation_name}_base { };
"""
def emit(self, operation):
warp_shape = [int(operation.tile_description.threadblock_shape[idx] /
operation.tile_description.warp_count[idx]) for idx in range(3)]
epilogue_vector_length = int(min(
operation.C.alignment * DataTypeSize[operation.C.element], 128) / DataTypeSize[operation.C.element])
values = {
'operation_name': operation.procedural_name(),
'operation_suffix': self.operation_suffix,
'conv_kind': ConvKindTag[operation.conv_kind],
'conv_kind_name': ConvKindNames[operation.conv_kind].capitalize(),
'element_a': DataTypeTag[operation.A.element],
'layout_a': LayoutTag[operation.A.layout],
'element_b': DataTypeTag[operation.B.element],
'layout_b': LayoutTag[operation.B.layout],
'element_c': DataTypeTag[operation.C.element],
'layout_c': LayoutTag[operation.C.layout],
'element_accumulator': DataTypeTag[operation.accumulator_type()],
'opcode_class': OpcodeClassTag[operation.tile_description.math_instruction.opcode_class],
'arch': "cutlass::arch::Sm%d" % operation.arch,
'threadblock_shape_m': str(operation.tile_description.threadblock_shape[0]),
'threadblock_shape_n': str(operation.tile_description.threadblock_shape[1]),
'threadblock_shape_k': str(operation.tile_description.threadblock_shape[2]),
'warp_shape_m': str(warp_shape[0]),
'warp_shape_n': str(warp_shape[1]),
'warp_shape_k': str(warp_shape[2]),
'instruction_shape_m': str(operation.tile_description.math_instruction.instruction_shape[0]),
'instruction_shape_n': str(operation.tile_description.math_instruction.instruction_shape[1]),
'instruction_shape_k': str(operation.tile_description.math_instruction.instruction_shape[2]),
'epilogue_vector_length': str(epilogue_vector_length),
'epilogue_functor': operation.epilogue_functor.emit(),
'swizzling_functor': operation.swizzling_functor.tag(),
'stages': str(operation.tile_description.stages),
'iterator_algorithm': IteratorAlgorithmTag[operation.iterator_algorithm],
'iterator_algorithm_name': IteratorAlgorithmNames[operation.iterator_algorithm].capitalize(),
'stride_support': StrideSupportTag[operation.stride_support],
'math_operator': 'cutlass::arch::OpMultiplyAddComplex' if operation.is_complex() else
MathOperationTag[operation.tile_description.math_instruction.math_operation],
'align_a': str(operation.A.alignment),
'align_b': str(operation.B.alignment),
}
return SubstituteTemplate(self.template, values)
| warp-main | warp/native/cutlass/tools/library/scripts/pycutlass/src/pycutlass/conv2d_operation.py |
################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
################################################################################
from typeguard import typechecked
import numpy as np
try:
import torch
torch_available = True
except ImportError:
torch_available = False
from cuda import cuda
try:
import cupy as cp
cupy_available = True
except ImportError:
cupy_available = False
import cutlass
# @typechecked
class TensorRef:
"""
Python Wrapper for cutlass.TensorRef
"""
def __init__(self, tensor, dtype, layout) -> None:
if isinstance(tensor, np.ndarray):
ptr = cuda.CUdeviceptr(tensor.__array_interface__['data'][0])
elif torch_available and isinstance(tensor, torch.Tensor):
ptr = cuda.CUdeviceptr(tensor.data_ptr())
elif cupy_available and isinstance(tensor, cp.ndarray):
ptr = cuda.CUdeviceptr(int(tensor.data.ptr))
elif isinstance(tensor, cuda.CUdeviceptr):
ptr = tensor
elif isinstance(tensor, int):
ptr = cuda.CUdeviceptr(tensor)
else:
raise NotImplementedError(tensor)
# the dtype(0) is used to overload between different data types
# with the same layout
self.tensor_ref = cutlass.get_tensor_ref(int(ptr), dtype(0), layout)
| warp-main | warp/native/cutlass/tools/library/scripts/pycutlass/src/pycutlass/tensor_ref.py |
################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
################################################################################
import ctypes
from cuda import cuda
################################################################################
#
# Launch configuration
#
################################################################################
class LaunchConfiguration:
def __init__(self, grid=[1, 1, 1], block=[1, 1, 1], smem=0):
self.grid = grid
self.block = block
self.shared_memory_capacity = smem
################################################################################
#
# Base class for an executable operation
#
# ##############################################################################
class ExecutableOperation:
'''
'''
def __init__(self, operation):
self.operation = operation
self.module = None
self.kernel = None
#
def name(self):
return self.operation.procedural_name()
#
def emit(self):
return ''
#
def can_implement(self, configuration, arguments):
raise NotImplementedError()
#
def get_host_workspace_size(self, arguments):
raise NotImplementedError()
#
def get_device_workspace_size(self, arguments):
raise NotImplementedError()
#
def plan(self, arguments):
raise NotImplementedError()
#
def initialize(self, host_workspace, device_workspace, launch_config, arguments, stream=cuda.CUstream(0)):
raise NotImplementedError()
#
def run(self, host_workspace, device_workspace, launch_config, stream=cuda.CUstream(0)):
cArg = (ctypes.c_char * len(host_workspace)
).from_buffer(host_workspace)
packed = (ctypes.c_void_p * 1)()
packed[0] = ctypes.addressof(cArg)
err, = cuda.cuLaunchKernel(
self.kernel,
launch_config.grid[0], launch_config.grid[1], launch_config.grid[2],
launch_config.block[0], launch_config.block[1], launch_config.block[2],
launch_config.shared_memory_capacity,
stream,
packed,
0)
return err
| warp-main | warp/native/cutlass/tools/library/scripts/pycutlass/src/pycutlass/operation.py |
################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
################################################################################
from typing import Generic, TypeVar
from treelib import Tree
import numpy as np
from pycutlass import *
import pycutlass
import ast
import textwrap
import inspect
################################################################################
# Type annotation for input arguments
################################################################################
Ttype = TypeVar("Ttype")
Dtype = TypeVar("Dtype")
class NDArray(np.ndarray, Generic[Ttype, Dtype]):
pass
################################################################################
# Operations
################################################################################
operators = {
ast.Add: "Add",
ast.Div: "Div",
ast.Eq: "Equal",
ast.Mult: "Mult"
}
################################################################################
# AST Node abstractions
################################################################################
class UnaryNode:
cnt = 0
# Concept: this is created by the BinOp Node in python ast
def __init__(self,
element_accumulator, element_compute, elements_per_access,
node, args) -> None:
if isinstance(node, BinOpNode):
self.op = node.op
elif isinstance(node, ast.Call):
if isinstance(node.func, ast.Name):
self.op = node.func.id
elif isinstance(node.func, ast.Attribute):
self.op = node.func.value.id
else:
raise TypeError
else:
raise TypeError
self.tag = "Unary" + self.op + str(UnaryNode.cnt)
self.id = self.op + str(UnaryNode.cnt)
self.args = args
UnaryNode.cnt += 1
self.type = "tensor"
self.epilogue_op = getattr(pycutlass, self.op)(element_compute)
# data types
self.element_accumulator = element_accumulator
self.element_compute = element_compute
self.elements_per_access = elements_per_access
def get_epilogue_node(self, visitors):
self.epilogue_node = UnaryOp(
self.element_accumulator, self.element_compute,
self.elements_per_access, *visitors, self.epilogue_op)
def get_argument(self, visitor_args, kwargs):
epilogue_ops = []
for arg in self.args:
try:
epilogue_ops.append(kwargs[arg])
except:
epilogue_ops.append(arg) # direct arguments like constant
self.argument = self.epilogue_node.argument_type(self.epilogue_op.argument_type(*epilogue_ops), *visitor_args)
class BinOpNode:
cnt = 0
# Concept: this is created by the BinOp Node in python ast
def __init__(self,
element_accumulator, element_compute, elements_per_access,
node) -> None:
self.op = operators[type(node.op)]
self.tag = "Binary" + self.op + str(BinOpNode.cnt)
self.id = self.op + str(BinOpNode.cnt)
self.args = None
BinOpNode.cnt += 1
self.type = "tensor"
self.epilogue_op = getattr(pycutlass, "Vector"+self.op)(element_compute)
# data types
self.element_accumulator = element_accumulator
self.element_compute = element_compute
self.elements_per_access = elements_per_access
def get_epilogue_node(self, visitors):
self.epilogue_node = BinaryOp(
self.element_accumulator, self.element_compute,
self.elements_per_access, *visitors, self.epilogue_op)
def get_argument(self, visitor_args, kwargs):
self.argument = self.epilogue_node.argument_type(self.epilogue_op.argument_type(self.args), *visitor_args)
class NameNode:
# Concept: this is created by the Name Node in python ast
def __init__(self, node) -> None:
try:
self.id = node.id
except:
self.id = node.targets[0].id
self.tag = self.id
class ScalarInputNode(NameNode):
# Concept: scalar
def __init__(self, node) -> None:
super().__init__(node)
self.tag = "Scalar:" + self.tag
self.type = "scalar"
class AccumulatorNode(NameNode):
# Concept: VisitorOpAccumulator
def __init__(self,
element_accumulator, elements_per_access, node) -> None:
super().__init__(node)
self.tag = "Accum:" + self.tag
self.type = "tensor"
self.element_accumulator = element_accumulator
self.elements_per_access = elements_per_access
def get_epilogue_node(self, visitors):
self.epilogue_node = AccumulatorOp(
self.element_accumulator, self.elements_per_access)
def get_argument(self, visitor_args, kwargs):
self.argument = self.epilogue_node.argument_type()
class TensorInputNode(NameNode):
# Concept: VisitorOpTensorInput
def __init__(self, element_accumulator, node) -> None:
super().__init__(node)
self.tag = "TensorInput:" + self.tag
self.type = "tensor"
self.element_accumulator = element_accumulator
def get_epilogue_node(self, *args):
self.epilogue_node = TensorInputOp(self.element_accumulator)
def get_argument(self, visitor_args, kwargs):
self.argument = self.epilogue_node.argument_type(
kwargs[self.id + "_ptr"], kwargs["problem_size"][1],
kwargs["problem_size"][0] * kwargs["problem_size"][1])
class RowBroadcastNode(NameNode):
# Concept: VisitorOpRowBroadcast
def __init__(self, element_accumulator, element_fragment, node) -> None:
super().__init__(node)
#
self.tag = "RowBroadcast:" + self.tag
self.type = "tensor"
self.element_accumulator = element_accumulator
self.element_fragment = element_fragment
def get_epilogue_node(self, *args):
self.epilogue_node = RowBroadcastOp(
self.element_accumulator, self.element_fragment)
def get_argument(self, visitor_args, kwargs):
self.argument = self.epilogue_node.argument_type(kwargs[self.id + "_ptr"], kwargs["problem_size"][1])
class ColumnBroadcastNode(NameNode):
# Concept: VisitorOpColumnBroadcast
def __init__(self, element_accumulator, element_fragment, node) -> None:
super().__init__(node)
self.tag = "ColumnBroadcast:" + self.tag
self.type = "tensor"
self.element_accumulator = element_accumulator
self.element_fragment = element_fragment
def get_epilogue_node(self, *args):
self.epilogue_node = ColumnBroadcastOp(
self.element_accumulator, self.element_fragment)
def get_argument(self, visitor_args, kwargs):
self.argument = self.epilogue_node.argument_type(kwargs[self.id + "_ptr"], kwargs["problem_size"][0])
class TensorOutputNode(NameNode):
# Concept: VisitorOpTensorOutput
def __init__(self, element_accumulator, node) -> None:
super().__init__(node)
self.tag = "TensorOutput:" + self.tag
self.type = "tensor"
self.element_accumulator = element_accumulator
def get_epilogue_node(self, visitors):
self.epilogue_node = TensorOutputOp(self.element_accumulator, *visitors)
def get_argument(self, visitor_args, kwargs):
self.argument = self.epilogue_node.argument_type(kwargs[self.id + "_ptr"], kwargs["problem_size"][1], *visitor_args, kwargs["problem_size"][0] * kwargs["problem_size"][1])
class RowReductionNode:
# Concept: RowReductionOp
def __init__(self, element_accumulator, element_reduction,
element_reduction_accumulator, id, factor) -> None:
#
self.id = id
self.tag = "RowReduction:" + self.id
self.type = "tensor"
self.element_accumulator = element_accumulator
self.element_reduction = element_reduction
self.element_reduction_accumulator = element_reduction_accumulator
self.factor = factor
def get_epilogue_node(self, visitors):
self.epilogue_node = RowReductionOp(
self.element_accumulator, self.element_reduction,
self.element_reduction_accumulator, *visitors)
def get_batch_stride(self, problem_size):
return problem_size[0] * ((problem_size[1] + self.factor - 1) // self.factor)
def get_argument(self, visitor_args, kwargs):
self.argument = self.epilogue_node.argument_type(kwargs[self.id + "_ptr"], *visitor_args, self.get_batch_stride(kwargs["problem_size"]))
class ColumnReductionNode:
# Concept: ColumnReductionOp
def __init__(self, element_accumulator, element_reduction,
element_reduction_accumulator, id, factor) -> None:
#
self.id = id
self.tag = "ColumnReduction:" + self.id
self.type = "tensor"
self.element_accumulator = element_accumulator
self.element_reduction = element_reduction
self.element_reduction_accumulator = element_reduction_accumulator
self.factor = factor
def get_epilogue_node(self, visitors):
self.epilogue_node = ColumnReductionOp(
self.element_accumulator, self.element_reduction,
self.element_reduction_accumulator, *visitors)
def get_batch_stride(self, problem_size):
return problem_size[1] * ((problem_size[0] + self.factor - 1) // self.factor)
def get_argument(self, visitor_args, kwargs):
self.argument = self.epilogue_node.argument_type(kwargs[self.id + '_ptr'], *visitor_args, self.get_batch_stride(kwargs["problem_size"]))
################################################################################
# Epilogue parser function
################################################################################
class EpilogueAST(ast.NodeVisitor):
def __init__(self, epilogue,
tile_description,
element_accumulator, elements_per_access,
element_compute, element_output) -> None:
#
self.tile_description = tile_description
self.element_accumulator = element_accumulator
self.elements_per_access = elements_per_access
self.element_compute = element_compute
self.element_output = element_output
self.epilogue = epilogue
self.source = textwrap.dedent(inspect.getsource(epilogue.__call__))
self.ast_tree = ast.parse(self.source)
self.epilogue_tree = Tree()
# print(ast.dump(self.ast_tree, indent=4)) # For Debug purpose
# input arguments
self.input_args = {}
# return nodes
self.returns = []
# reduction source nodes
self.reduction_source = {}
# stack used to keep the parent node id
self.stack = []
# visit the AST
self.visit(self.ast_tree)
# visit the name node
def visit_Name(self, node):
# append the return ids into self.returns
if self.stack[-1] == "return":
self.returns.append(node.id)
else:
# accum is produced from accumulator node
if node.id == "accum":
name_node = AccumulatorNode(
self.element_accumulator, self.elements_per_access, node)
else:
# for input nodes
if node.id in self.input_args.keys():
type = self.input_args[node.id][0]
if type == "tensor":
name_node = TensorInputNode(self.element_accumulator, node)
elif type == "row":
name_node = RowBroadcastNode(self.element_accumulator, self.element_compute, node)
elif type == "column":
name_node = ColumnBroadcastNode(self.element_accumulator, self.element_compute, node)
elif type == "scalar":
name_node = ScalarInputNode(node)
else:
raise ValueError(type)
# for output nodes
else:
name_node = TensorOutputNode(self.element_accumulator, node)
self.epilogue_tree.create_node(name_node.tag, name_node.id, data=name_node, parent=self.stack[-1])
def visit_Assign(self, node):
pre_assign_node = self.epilogue_tree.get_node(node.targets[0].id)
if pre_assign_node is None:
# The assign is to a root node
# skip the reduction nodes
if isinstance(node.value, ast.Call):
if isinstance(node.value.func, ast.Name):
func_type = node.value.func.id
elif isinstance(node.value.func, ast.Attribute):
func_type = node.value.func.value.id
else:
raise TypeError
if func_type == 'reduction_op':
self.reduction_source[node.value.args[0].id] = [node.value.args[1].value, node.value.args[2].value, node.targets[0].id]
return
name_node = TensorOutputNode(self.element_accumulator, node)
self.epilogue_tree.create_node(name_node.tag, name_node.id, data=name_node)
self.stack.append(name_node.id)
else:
if node.targets[0].id in self.returns or node.targets[0].id in self.reduction_source.keys():
self.stack.append(node.targets[0].id)
else:
self.stack.append(pre_assign_node.predecessor(self.epilogue_tree.identifier))
self.epilogue_tree.remove_node(node.targets[0].id)
# get child tag
self.visit(node.value)
self.stack.pop()
def visit_Call(self, node):
if isinstance(node.func, ast.Name):
func_type = node.func.id
elif isinstance(node.func, ast.Attribute):
func_type = node.func.value.id
else:
raise TypeError
if func_type == "reduction_op":
self.visit(node.args[0])
else:
arg_list = []
for idx, arg in enumerate(node.args):
if idx == 0: continue
if isinstance(arg, ast.Constant):
arg_list.append(arg.value)
elif isinstance(arg, ast.Name):
arg_list.append(arg.id)
else:
raise TypeError
unary_node = UnaryNode(self.element_accumulator, self.element_compute, self.elements_per_access, node, arg_list)
self.epilogue_tree.create_node(unary_node.tag, unary_node.id, parent=self.stack[-1], data=unary_node)
self.stack.append(unary_node.id)
self.visit(node.args[0])
self.stack.pop()
def visit_BinOp(self, node):
binop = BinOpNode(self.element_accumulator, self.element_compute,
self.elements_per_access, node)
self.epilogue_tree.create_node(binop.tag, binop.id, data=binop, parent=self.stack[-1])
self.stack.append(binop.id)
self.visit(node.left)
self.visit(node.right)
self.stack.pop()
def visit_Return(self, node):
self.stack.append("return")
self.visit(node.value)
self.stack.pop()
# # A function definition
def visit_FunctionDef(self, node: ast.FunctionDef):
# visit args
for arg in node.args.args:
if arg.arg == "self": continue
if isinstance(arg.annotation, ast.Constant):
self.input_args[arg.arg] = [arg.annotation.value, ]
# visit the assign in the reverse order
for idx in range(len(node.body)):
self.visit(node.body[-1-idx])
#
# Tree optimization pass
#
# pass 1: lower Binary to Unary
def pass_binary_2_unary(self, tree, nid):
node = tree.get_node(nid)
if isinstance(node.data, BinOpNode):
lhs_node = tree.get_node(node.successors(tree.identifier)[0])
left_type = lhs_node.data.type
rhs_node = tree.get_node(node.successors(tree.identifier)[1])
right_type = rhs_node.data.type
if left_type == "scalar" and right_type == "tensor":
node.data = UnaryNode(
self.element_accumulator, self.element_compute,
self.elements_per_access,
node.data, [lhs_node.data.id,])
node.tag = node.data.tag
tree.remove_node(lhs_node.data.id)
self.pass_binary_2_unary(tree, rhs_node.data.id)
elif left_type == "tensor" and right_type == "scalar":
node.data = UnaryNode(
self.element_accumulator, self.element_compute,
self.elements_per_access,
node.data, [rhs_node.id,])
node.tag = node.data.tag
tree.remove_node(rhs_node.data.id)
self.pass_binary_2_unary(tree, lhs_node.data.id)
else:
self.pass_binary_2_unary(tree, lhs_node.data.id)
self.pass_binary_2_unary(tree, rhs_node.data.id)
else:
for child in node.successors(tree.identifier):
self.pass_binary_2_unary(tree, child)
# pass 2: inject reduction nodes
def pass_inject_reduction(self, tree, nid):
node = tree.get_node(nid)
if isinstance(node.data, TensorOutputNode):
if node.data.id in self.reduction_source.keys():
direction = self.reduction_source[node.data.id][0]
target = self.reduction_source[node.data.id][-1]
if direction == 'row':
reduction_node = RowReductionNode(
self.element_accumulator, self.element_output,
self.element_accumulator, target, self.tile_description.threadblock_shape[1])
elif direction == "column":
reduction_node = ColumnReductionNode(
self.element_accumulator, self.element_output,
self.element_accumulator, target, self.tile_description.threadblock_shape[0])
else:
raise ValueError(direction)
child_nid = node.successors(tree.identifier)[0]
# if this output node is injected only for reduction
if node.data.id not in self.returns:
# get reduction config from disc
node.data = reduction_node
node.tag = reduction_node.tag
self.pass_inject_reduction(tree, child_nid)
# if this output node is also a tensor output, inject reduction as its children
else:
# get child node
tree.create_node(reduction_node.tag, reduction_node.id, data=reduction_node, parent=node.data.id)
tree.move_node(child_nid, reduction_node.id)
child = tree.get_node(child_nid)
for grand_child in child.successors(tree.identifier):
self.pass_inject_reduction(tree, grand_child)
else:
for child in node.successors(tree.identifier):
self.pass_inject_reduction(tree, child)
else:
for child in node.successors(tree.identifier):
self.pass_inject_reduction(tree, child)
def pass_inject_epilogue_op(self, tree, nid):
node = tree.get_node(nid)
visitors = []
for child in node.successors(tree.identifier):
visitors.append(self.pass_inject_epilogue_op(tree, child))
node.data.get_epilogue_node(visitors)
return node.data.epilogue_node
def get_arguments(self, tree, nid, kwargs):
node = tree.get_node(nid)
visitor_args = []
for child in node.successors(tree.identifier):
visitor_args.append(self.get_arguments(tree, child, kwargs))
node.data.get_argument(visitor_args, kwargs)
return node.data.argument
class EpilogueVisitTree:
KernelTemplate = """
${visitor}
using ${operation_name}_EpilogueVisitor = cutlass::epilogue::threadblock::EpilogueVisitorGeneric<${visitor_name}>;
"""
def __init__(self, elementwise_functor, tile_description,
element_accumulator, elements_per_access,
element_compute, element_output) -> None:
#
# data types
self.tile_description = tile_description
self.element_accumulator = element_accumulator
self.elements_per_access = elements_per_access
self.element_compute = element_compute
self.element_output = element_output
# TODO: deprecate this
self.elementwise_functor = elementwise_functor
pass
def initialize(self):
function = EpilogueAST(self, self.tile_description,
self.element_accumulator, self.elements_per_access,
self.element_compute, self.element_output)
#
tree = function.epilogue_tree
self.tree = tree
# self.tree.show() # for debug
function.pass_binary_2_unary(self.tree, self.tree.root)
# self.tree.show() # for debug
function.pass_inject_reduction(self.tree, self.tree.root)
# self.tree.show() # for debug
function.pass_inject_epilogue_op(self.tree,self.tree.root)
visitor = self.tree.get_node(self.tree.root).data.epilogue_node
self.visitor = visitor
class _Argument(ctypes.Structure):
_fields_ = [
("visitor_arg", visitor.argument_type)
]
def __init__(self, **kwargs) -> None:
# process input args
_kwargs = {}
for input_key in function.input_args.keys():
if input_key == "accum":
continue
if function.input_args[input_key][0] == "scalar":
# _kwargs[input_key] = kwargs[input_key]
continue
# tensor input
else:
setattr(self, "buffer_tensor_" + input_key, NumpyFrontend.argument(kwargs[input_key], False))
setattr(self, input_key + "_ptr", int(getattr(self, "buffer_tensor_" + input_key).ptr))
_kwargs[input_key+"_ptr"] = getattr(self, input_key + "_ptr")
# process the return args
for ret in function.returns:
setattr(self, "buffer_tensor_" + ret, NumpyFrontend.argument(kwargs[ret], True))
setattr(self, ret + "_ptr", int(getattr(self, "buffer_tensor_" + ret).ptr))
_kwargs[ret+"_ptr"] = getattr(self, ret + "_ptr")
setattr(self, "host_tensor_" + ret, kwargs[ret])
_kwargs.update(kwargs)
function.get_arguments(tree, tree.root, _kwargs)
self.visitor_arg = tree.get_node(tree.root).data.argument
def sync(self, stream_sync=True):
if stream_sync:
err, = cudart.cudaDeviceSynchronize()
if err != cuda.CUresult.CUDA_SUCCESS:
raise RuntimeError("CUDA Error %s" % str(err))
for ret in function.returns:
err, = cuda.cuMemcpyDtoH(
getattr(self, "host_tensor_" + ret), cuda.CUdeviceptr(getattr(self, ret + "_ptr")),
getattr(self, "host_tensor_" + ret).size * getattr(self, "host_tensor_" + ret).itemsize
)
if err != cuda.CUresult.CUDA_SUCCESS:
raise RuntimeError("CUDA Error %s" % str(err))
pass
self.epilogue_type = _Argument
def emit(self, operation):
values = {
'visitor': self.visitor.emit(operation),
'operation_name': operation.procedural_name(),
'visitor_name': self.visitor.instance_name
}
return SubstituteTemplate(self.KernelTemplate, values)
| warp-main | warp/native/cutlass/tools/library/scripts/pycutlass/src/pycutlass/parser.py |
################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
################################################################################
from ast import Num
from audioop import mul
from pipes import Template
import struct
from pycutlass.library import DataTypeTag
from pycutlass import *
import cutlass
from scipy.special import erf
from pycutlass.c_types import MatrixCoord_
from pycutlass.frontend import NumpyFrontend
from cuda import cuda
from cuda import cudart
dtype2ctype = {
cutlass.float16: ctypes.c_uint16,
cutlass.float32: ctypes.c_float,
cutlass.float64: ctypes.c_double,
cutlass.int32: ctypes.c_int32
}
#################################################################################################
#
# Epilogue Functors
#
#################################################################################################
class EpilogueFunctorBase:
"""
Base class for thread-level epilogue functors
"""
def __init__(self) -> None:
pass
def emit(self, tag, template_argument):
template = """${tag}<${arguments}>"""
arguments = ""
for idx, arg in enumerate(template_argument):
arguments += arg
if idx < len(template_argument) - 1:
arguments += ", "
values = {
"tag": tag,
"arguments": arguments
}
return SubstituteTemplate(template, values)
class LinearCombination(EpilogueFunctorBase):
"""
Apply a linear combination operator to an array of elements
D = alpha * accumulator + beta * source
:param element_output: data type used to load and store tensors
:param epilogue_vector_length: number of elements computed per operation.
Usually it is 128/sizeof_bits<ElementOutput_>, but we use 64 and 32 sometimes
when there are not enough data to store
:param element_accumulator: Accumulator data type
:param element_epilogue: data type used to compute linear combination
"""
tag = "cutlass::epilogue::thread::LinearCombination"
def __init__(
self, element_output, epilogue_vector_length,
element_accumulator=None, element_epilogue=None) -> None: # TODO bind ScaleType
super().__init__()
if element_accumulator is None:
element_accumulator = element_output
if element_epilogue is None:
element_epilogue = element_output
self.element_output = element_output
self.element_accumulator = element_accumulator
self.element_epilogue = element_epilogue
self.template_arguments = [
DataTypeTag[element_output], str(epilogue_vector_length),
DataTypeTag[element_accumulator], DataTypeTag[element_epilogue]
]
# get epilogue output op type
c_element_epilogue = dtype2ctype[self.element_epilogue]
element_epilogue = self.element_epilogue
class _EpilogueOutputOpParams(ctypes.Structure):
_fields_ = [
("alpha_data", ctypes.c_longlong*2),
("beta_data", ctypes.c_longlong*2),
("alpha", c_element_epilogue),
("beta", c_element_epilogue),
("alpha_ptr", ctypes.c_void_p),
("beta_ptr", ctypes.c_void_p),
]
def __init__(self, alpha, beta, *args) -> None:
self.alpha = element_epilogue(alpha).storage
self.beta = element_epilogue(beta).storage
self.epilogue_type = _EpilogueOutputOpParams
def emit(self):
return super().emit(self.tag, self.template_arguments)
class LinearCombinationClamp(LinearCombination):
"""
Applies a linear combination operator to an array of elements then clamps
the output before converting to the output element type.
D = alpha * accumulator + beta * source + uniform
:param element_output: data type used to load and store tensors
:param epilogue_vector_length: number of elements computed per operation.
Usually it is 128/sizeof_bits<ElementOutput_>, but we use 64 and 32 sometimes
when there are not enough data to store
:param element_accumulator: Accumulator data type
:param element_epilogue: data type used to compute linear combination
"""
tag = "cutlass::epilogue::thread::LinearCombinationClamp"
def __init__(
self, element_output, epilogue_vector_length,
element_accumulator=None, element_epilogue=None) -> None:
# Base constructor
super().__init__(
element_output, epilogue_vector_length,
element_accumulator, element_epilogue)
c_element_epilogue = dtype2ctype[self.element_epilogue]
element_epilogue = self.element_epilogue
class _EpilogueOutputOpParams(ctypes.Structure):
_fields_ = [
("alpha", c_element_epilogue),
("beta", c_element_epilogue),
("alpha_ptr", ctypes.c_void_p),
("beta_ptr", ctypes.c_void_p),
]
def __init__(self, alpha, beta, *args) -> None:
self.alpha = element_epilogue(alpha).storage
self.beta = element_epilogue(beta).storage
self.epilogue_type = _EpilogueOutputOpParams
class FastLinearCombinationClamp(EpilogueFunctorBase):
"""
Applies a linear combination operator to an array of elements then clamps
the output before converting to the output element type.
D = alpha * accumulator + beta * source
Note: The below method only when problem_size_K <= 256 for signed int8 gemm
or problem_size_K <= 128 for unsigned int8 gemm. The default approach is
above.
:param element_output: data type used to load and store tensors
:param epilogue_vector_length: number of elements computed per operation.
Usually it is 128/sizeof_bits<ElementOutput_>, but we use 64 and 32 sometimes
when there are not enough data to store
"""
tag = "cutlass::epilogue::thread::FastLinearCombinationClamp"
def __init__(self, element_output, epilogue_vector_length, *args) -> None:
super().__init__()
self.template_arguments = [
DataTypeTag[element_output], str(epilogue_vector_length)
]
self.element_accumulator = cutlass.int32
self.element_epilogue = cutlass.float32
# get epilogue output op
c_element_epilogue = dtype2ctype[self.element_epilogue]
element_epilogue = self.element_epilogue
class _EpilogueOutputOpParams(ctypes.Structure):
_fields_ = [
("alpha", c_element_epilogue),
("beta", c_element_epilogue),
("alpha_ptr", ctypes.c_void_p),
("beta_ptr", ctypes.c_void_p),
]
def __init__(self, alpha, beta, *args) -> None:
self.alpha = element_epilogue(alpha).storage
self.beta = element_epilogue(beta).storage
self.epilogue_type = _EpilogueOutputOpParams
def emit(self):
return super().emit(self.tag, self.template_arguments)
class LinearCombinationGeneric(LinearCombination):
"""
Applies a linear combination operator followed by an activation function
to an array of elements.
D = activation(alpha * accumulator + beta * source)
:param activation_functor: input activation functor
:param element_output: data type used to load and store tensors
:param epilogue_vector_length: number of elements computed per operation.
Usually it is 128/sizeof_bits<ElementOutput_>, but we use 64 and 32 sometimes
when there are not enough data to store
:param element_accumulator: Accumulator data type
:param element_epilogue: data type used to compute linear combination
"""
tag = "cutlass::epilogue::thread::LinearCombinationGeneric"
def __init__(
self, activation_functor,
element_output, epilogue_vector_length,
element_accumulator=None, element_epilogue=None) -> None:
super().__init__(
element_output, epilogue_vector_length,
element_accumulator, element_epilogue)
self.template_arguments = [
activation_functor.emit(),] + self.template_arguments
self.activation_functor = activation_functor
self.element_epilogue = element_epilogue
# get epilogue output op
self.epilogue_type = self.activation_functor.epilogue_output_op(self.element_epilogue)
class ActivationFunctor:
"""
Base class for frequently used activation functions
"""
def __init__(self, element_compute) -> None:
pass
@staticmethod
def numpy(x: np.ndarray):
raise NotImplementedError()
def emit(self):
return self.tag
@staticmethod
def epilogue_output_op(element_epilogue):
c_element_epilogue = dtype2ctype[element_epilogue]
class _EpilogueOutputOpParams(ctypes.Structure):
_fields_ = [
("alpha", c_element_epilogue),
("beta", c_element_epilogue),
("alpha_ptr", ctypes.c_void_p),
("beta_ptr", ctypes.c_void_p),
]
def __init__(self, alpha, beta, *args) -> None:
self.alpha = element_epilogue(alpha).storage
self.beta = element_epilogue(beta).storage
return _EpilogueOutputOpParams
# identity operator
class identity(ActivationFunctor):
def numpy(x: np.ndarray):
return x
# ReLu operator,
class relu(ActivationFunctor):
tag = "cutlass::epilogue::thread::ReLu"
def __init__(self, element_compute):
super().__init__(element_compute)
class _Arguments(ctypes.Structure):
_fields_ = [
("threshold", dtype2ctype[element_compute])
]
def __init__(self, threshold=0.) -> None:
self.threshold = element_compute(threshold).storage
self.argument_type = _Arguments
def emit_visitor(self):
return "cutlass::ReLUVisitor"
@staticmethod
def numpy(x: np.ndarray):
return np.maximum(x, 0)
# Leaky ReLu operator
class leaky_relu(ActivationFunctor):
tag = "cutlass::epilogue::thread::LeakyReLU"
def __init__(self, element_compute) -> None:
super().__init__(element_compute)
class _Arguments(ctypes.Structure):
_fields_ = [
("leaky_alpha", dtype2ctype[element_compute])
]
def __init__(self, leaky_alpha) -> None:
self.leaky_alpha = element_compute(leaky_alpha).storage
self.argument_type = _Arguments
def emit_visitor(self):
return "cutlass::LeakyReLUVisitor"
@staticmethod
def numpy(x: np.ndarray, leaky_alpha):
return np.maximum(x, 0) + np.minimum(x, 0) * leaky_alpha
def epilogue_output_op(self, element_epilogue):
c_element_epilogue = dtype2ctype[element_epilogue]
class _EpilogueOutputOpParams(ctypes.Structure):
_fields_ = [
("alpha", c_element_epilogue),
("beta", c_element_epilogue),
("alpha_ptr", ctypes.c_void_p),
("beta_ptr", ctypes.c_void_p),
("leaky_alpha", c_element_epilogue)
]
def __init__(self, alpha, beta, leaky_alpha=0.2, *args) -> None:
self.alpha = element_epilogue(alpha).storage
self.beta = element_epilogue(beta).storage
self.alpha_ptr = 0
self.beta_ptr = 0
self.leaky_alpha = element_epilogue(leaky_alpha).storage
return _EpilogueOutputOpParams
# Tanh operator
class tanh(ActivationFunctor):
tag = "cutlass::epilogue::thread::Tanh"
def __init__(self, element_compute) -> None:
super().__init__(element_compute)
class _Arguments(ctypes.Structure):
_fields_ = [
("tmp", ctypes.c_int)
]
def __init__(self, *args) -> None:
self.tmp = 0
self.argument_type = _Arguments
def emit_visitor(self):
return "cutlass::TanhVisitor"
@staticmethod
def numpy(x: np.ndarray):
return np.tanh(x)
def sigmoid_op(x: np.ndarray):
return 1. / (1. + np.exp(-x))
# Sigmoid operator
class sigmoid(ActivationFunctor):
tag = "cutlass::epilogue::thread::Sigmoid"
@staticmethod
def numpy(x: np.ndarray):
return sigmoid_op(x)
# SiLu operator
class silu(ActivationFunctor):
tag = "cutlass::epilogue::thread::SiLu"
@staticmethod
def numpy(x: np.ndarray):
return x * sigmoid_op(x)
# Hardswish operator
class hardswish(ActivationFunctor):
tag = "cutlass::epilogue::thread::HardSwish"
@staticmethod
def numpy(x: np.ndarray):
relu6 = np.minimum(np.maximum(x + 3., 0), 6.)
return x * relu6 / 6.
# GELU operator
class gelu(ActivationFunctor):
tag = "cutlass::epilogue::thread::GELU"
@staticmethod
def numpy(x: np.ndarray):
return 0.5 * x * (1 + erf(x / np.sqrt(2.)))
# reduction operator
def reduction_op(tensor, direction, math, factor):
batch, m, n = tensor.shape
if math == "Add":
if direction == "row":
num_cta_n = (n + factor - 1) // factor
reduction = np.transpose(
np.sum(tensor.reshape(batch, m, num_cta_n, factor), axis=-1),
axes=[0, 2, 1]).flatten()
elif direction == "column":
num_cta_m = (m + factor - 1) // factor
reduction = np.sum(
tensor.reshape(batch, num_cta_m, factor, n), axis=-2).flatten()
else:
raise NotImplementedError
return reduction
else:
raise NotImplementedError
# # GELU operator implemented using the taylor series approximation
# class GELU_taylor(ActivationFunctor):
# tag = "cutlass::epilogue::thread::GELU_taylor"
# # Computes backwards pass for GELU operator
# class dGELU(ActivationFunctor):
# tag = "cutlass::epilogue::thread::dGELU"
################################################################################
# Epilogue Visitor
################################################################################
class LayerNorm(EpilogueFunctorBase):
"""
Apply a linear combination operator to an array of elements
D = alpha * accumulator + beta * source
:param element_output: data type used to load and store tensors
:param epilogue_vector_length: number of elements computed per operation.
Usually it is 128/sizeof_bits<ElementOutput_>, but we use 64 and 32 sometimes
when there are not enough data to store
:param element_accumulator: Accumulator data type
:param element_epilogue: data type used to compute linear combination
"""
KernelTemplate = """
cutlass::epilogue::threadblock::EpilogueVisitorLayerNorm<
cutlass::gemm::GemmShape<${threadblock_shape_m}, ${threadblock_shape_n}, ${threadblock_shape_k}>,
${operation_name}_default::kThreadCount,
${operation_name}_default::Epilogue::OutputTileIterator,
${operation_name}_default::Epilogue::AccumulatorFragmentIterator::AccumulatorTile,
${element_compute}, // element_compute
${element_variance}, // element_variance
${element_mean}, // element_mean
${element_layer_norm_compute}, // element_layer_norm_compute
${epilogue_functor},
${shifted_k}>;
"""
headers = ["gemm/gemm_universal_with_visitor.h",
"epilogue/epilogue_visitor_with_layernorm.h"]
def __init__(
self, elementwise_functor,
element_variance=None, element_mean=None,
element_layer_norm_compute=None, shifted_k=True) -> None: # TODO bind ScaleType
super().__init__()
self.elementwise_functor = elementwise_functor
self.element_compute = elementwise_functor.element_epilogue
self.element_output = elementwise_functor.element_output
if element_variance is None:
self.element_variance = self.element_output
if element_mean is None:
self.element_mean = self.element_output
if element_layer_norm_compute is None:
self.element_layer_norm_compute = self.element_compute
if shifted_k:
self.shifted_k = "true"
else:
self.shifted_k = "false"
# get epilogue output op
elementwise_params_type = self.elementwise_functor.epilogue_type
class _EpilogueVisitorParams(ctypes.Structure):
_fields_ = [
("element_wise", elementwise_params_type),
("ptr_Variance", ctypes.c_void_p),
("ptr_Mean_", ctypes.c_void_p),
("ptr_Shifted_K_", ctypes.c_void_p),
("extent", MatrixCoord_)
]
def __init__(self, elementwise_params, variance, mean, shift_k, extent) -> None:
self.element_wise = elementwise_params
if isinstance(variance, np.ndarray):
self.buffer_variance = NumpyFrontend.argument(variance, False)
self.buffer_mean = NumpyFrontend.argument(mean, False)
self.buffer_shift_k = NumpyFrontend.argument(shift_k, False)
self.ptr_Variance = int(self.buffer_variance.ptr)
self.ptr_Mean_ = int(self.buffer_mean.ptr)
self.ptr_Shifted_K_ = int(self.buffer_shift_k.ptr)
self.extent = MatrixCoord_(extent[0], extent[1])
self.host_variance = variance
self.host_mean = mean
self.host_shift_k = shift_k
def sync(self, stream_sync=True):
if stream_sync:
err, = cudart.cudaDeviceSynchronize()
if err != cuda.CUresult.CUDA_SUCCESS:
raise RuntimeError("CUDA Error %s" % str(err))
# if hasattr(self, "host_variance"):
err, = cuda.cuMemcpyDtoH(
self.host_variance, cuda.CUdeviceptr(self.ptr_Variance),
self.host_variance.size * self.host_variance.itemsize)
err, = cuda.cuMemcpyDtoH(
self.host_mean, cuda.CUdeviceptr(self.ptr_Mean_),
self.host_mean.size * self.host_mean.itemsize)
err, = cuda.cuMemcpyDtoH(
self.host_shift_k, cuda.CUdeviceptr(self.ptr_Shifted_K_),
self.host_shift_k.size * self.host_shift_k.itemsize)
if err != cuda.CUresult.CUDA_SUCCESS:
raise RuntimeError("CUDA Error %s" % str(err))
self.epilogue_type = _EpilogueVisitorParams
def emit(self, operation):
values = {
'threadblock_shape_m': str(operation.tile_description.threadblock_shape[0]),
'threadblock_shape_n': str(operation.tile_description.threadblock_shape[1]),
'threadblock_shape_k': str(operation.tile_description.threadblock_shape[2]),
'operation_name': operation.procedural_name(),
'element_compute': DataTypeTag[self.element_compute],
'element_variance': DataTypeTag[self.element_variance],
'element_mean': DataTypeTag[self.element_mean],
'element_layer_norm_compute': DataTypeTag[self.element_layer_norm_compute],
'epilogue_functor': self.elementwise_functor.emit(),
'shifted_k': self.shifted_k
}
return SubstituteTemplate(self.KernelTemplate, values)
class AccumulatorOp:
Template = """
using ${instance_name} = cutlass::epilogue::threadblock::VisitorOpAccumulator<${element_accumulator}, ${elements_per_access}>;
"""
counter = 0
def __init__(self, element_accumulator, elements_per_access) -> None:
self.element_accumulator = element_accumulator
self.elements_per_access = elements_per_access
self.instance_name = "AccumulatorOp%d" % AccumulatorOp.counter
AccumulatorOp.counter += 1
class _Arguments(ctypes.Structure):
_fields_ = [
("tmp", ctypes.c_int)
]
def __init__(self):
self.tmp = 0
self.argument_type = _Arguments
def emit(self, *args):
values = {
"instance_name": self.instance_name,
"element_accumulator": DataTypeTag[self.element_accumulator],
"elements_per_access": str(self.elements_per_access)
}
return SubstituteTemplate(self.Template, values)
class LinearCombinationOp:
Template = """
${visitor_a}
${visitor_b}
using ${instance_name} = cutlass::epilogue::threadblock::VisitorOpLinearCombination<
${element_accumulator}, ${element_compute},
${elements_per_access}, ${visitor_a_name}, ${visitor_b_name}>;
"""
counter = 0
def __init__(self, element_accumulator, element_compute,
elements_per_access, visitor_a, visitor_b) -> None:
#
self.element_accumulator = element_accumulator
self.element_compute = element_compute
self.elements_per_access = elements_per_access
self.visitor_a = visitor_a
self.visitor_b = visitor_b
self.instance_name = "LinearCombinationOp%d" % LinearCombinationOp.counter
LinearCombinationOp.counter += 1
class _Arguments(ctypes.Structure):
_fields_ = [
("alpha", dtype2ctype[self.element_compute]),
("beta", dtype2ctype[self.element_compute]),
("visitor_a", self.visitor_a.argument_type),
("visitor_b", self.visitor_b.argument_type)
]
def __init__(self, alpha, beta, visitor_a_arg, visitor_b_arg) -> None:
self.alpha = element_compute(alpha).storage
self.beta = element_compute(beta).storage
self.visitor_a = visitor_a_arg
self.visitor_b = visitor_b_arg
self.argument_type = _Arguments
def emit(self, operation):
values = {
"instance_name": self.instance_name,
"element_accumulator": DataTypeTag[self.element_accumulator],
"element_compute": DataTypeTag[self.element_compute],
"elements_per_access": str(self.elements_per_access),
"visitor_a_name": self.visitor_a.instance_name,
"visitor_b_name": self.visitor_b.instance_name,
"visitor_a": self.visitor_a.emit(operation),
"visitor_b": self.visitor_b.emit(operation)
}
return SubstituteTemplate(self.Template, values)
class VectorAdd:
def __init__(self, *args) -> None:
class _Arguments(ctypes.Structure):
_fields_ = [
("tmp", ctypes.c_int)
]
def __init__(self, *args) -> None:
self.tmp = 0
self.argument_type = _Arguments
def emit(self):
return "cutlass::VectorAdd"
class VectorMult:
def __init__(self, *args) -> None:
class _Arguments(ctypes.Structure):
_fields_ = [
("tmp", ctypes.c_int)
]
def __init__(self, *args) -> None:
self.tmp = 0
self.argument_type = _Arguments
def emit(self):
return "cutlass::VectorMult"
class BinaryOp:
Template = """
${visitor_a}
${visitor_b}
using ${instance_name} = cutlass::epilogue::threadblock::VisitorOpBinary<
${element_accumulator}, ${element_compute},
${elements_per_access}, ${visitor_a_name}, ${visitor_b_name}, ${binary_op}>;
"""
counter = 0
def __init__(self, element_accumulator, element_compute,
elements_per_access, visitor_a, visitor_b, binary_op) -> None:
#
self.element_accumulator = element_accumulator
self.element_compute = element_compute
self.elements_per_access = elements_per_access
self.visitor_a = visitor_a
self.visitor_b = visitor_b
self.binary_op = binary_op
self.instance_name = "BinaryOp%d" % BinaryOp.counter
BinaryOp.counter += 1
class _Arguments(ctypes.Structure):
_fields_ = [
("binary_param", binary_op.argument_type),
("visitor_a", self.visitor_a.argument_type),
("visitor_b", self.visitor_b.argument_type)
]
def __init__(self, binary_param, visitor_a_arg, visitor_b_arg) -> None:
self.binary_param = binary_param
self.visitor_a = visitor_a_arg
self.visitor_b = visitor_b_arg
self.argument_type = _Arguments
def emit(self, operation):
values = {
"instance_name": self.instance_name,
"element_accumulator": DataTypeTag[self.element_accumulator],
"element_compute": DataTypeTag[self.element_compute],
"elements_per_access": str(self.elements_per_access),
"visitor_a_name": self.visitor_a.instance_name,
"visitor_b_name": self.visitor_b.instance_name,
"visitor_a": self.visitor_a.emit(operation),
"visitor_b": self.visitor_b.emit(operation),
"binary_op": self.binary_op.emit()
}
return SubstituteTemplate(self.Template, values)
class Mult:
def __init__(self, element_compute) -> None:
class _Arguments(ctypes.Structure):
_fields_ = [
("alpha", dtype2ctype[element_compute])
]
def __init__(self, alpha) -> None:
self.alpha = element_compute(alpha).storage
self.argument_type = _Arguments
def emit_visitor(self):
return "cutlass::Mult"
class UnaryOp:
Template = """
${visitor}
using ${instance_name} = cutlass::epilogue::threadblock::VisitorOpUnary<
${element_accumulator}, ${element_compute},
${elements_per_access}, ${visitor_name}, ${unary_op}>;
"""
counter = 0
def __init__(self, element_accumulator, element_compute,
elements_per_access, visitor, unary_op) -> None:
#
self.element_accumulator = element_accumulator
self.element_compute = element_compute
self.elements_per_access = elements_per_access
self.visitor = visitor
self.unary_op = unary_op
self.instance_name = "UnaryOp%d" % UnaryOp.counter
UnaryOp.counter += 1
class _Arguments(ctypes.Structure):
_fields_ = [
("unary_param", unary_op.argument_type),
("visitor_arg", self.visitor.argument_type)
]
def __init__(self, unary_param, visitor_arg) -> None:
self.unary_param = unary_param
self.visitor_arg = visitor_arg
self.argument_type = _Arguments
def emit(self, operation):
values = {
"instance_name": self.instance_name,
"element_accumulator": DataTypeTag[self.element_accumulator],
"element_compute": DataTypeTag[self.element_compute],
"elements_per_access": str(self.elements_per_access),
"visitor_name": self.visitor.instance_name,
"unary_op": self.unary_op.emit_visitor(),
"visitor": self.visitor.emit(operation)
}
return SubstituteTemplate(self.Template, values)
class RowBroadcastOp:
Template = """
using ${instance_name} = cutlass::epilogue::threadblock::VisitorOpRowBroadcast<
${element_accumulator}, ${element_fragment}, ${input_tile_iterator}>;
"""
counter = 0
def __init__(self, element_accumulator, element_fragment) -> None:
self.element_accumulator = element_accumulator
self.element_fragment = element_fragment
self.instance_name = "RowBroadcastOp%d" % RowBroadcastOp.counter
RowBroadcastOp.counter += 1
class _Arguments(ctypes.Structure):
_fields_ = [
("broadcast_ptr", ctypes.c_void_p),
("batch_stride", ctypes.c_longlong)
]
def __init__(self, broadcast_ptr, batch_stride=0):
self.broadcast_ptr = int(broadcast_ptr)
self.batch_stride = batch_stride
self.argument_type = _Arguments
def emit(self, operation):
values = {
"instance_name": self.instance_name,
"element_accumulator": DataTypeTag[self.element_accumulator],
"element_fragment": DataTypeTag[self.element_fragment],
"input_tile_iterator": operation.procedural_name() + "_default::Epilogue::OutputTileIterator"
}
return SubstituteTemplate(self.Template, values)
class ColumnBroadcastOp:
Template = """
using ${instance_name} = cutlass::epilogue::threadblock::VisitorOpColumnBroadcast<
${element_accumulator}, ${element_fragment}, ${input_tile_iterator}>;
"""
counter = 0
def __init__(self, element_accumulator, element_fragment) -> None:
self.element_accumulator = element_accumulator
self.element_fragment = element_fragment
self.instance_name = "ColumnBroadcastOp%d" % ColumnBroadcastOp.counter
ColumnBroadcastOp.counter += 1
class _Arguments(ctypes.Structure):
_fields_ = [
("broadcast_ptr", ctypes.c_void_p),
("batch_stride", ctypes.c_longlong)
]
def __init__(self, broadcast_ptr, batch_stride=0):
self.broadcast_ptr = int(broadcast_ptr)
self.batch_stride = batch_stride
self.argument_type = _Arguments
def emit(self, operation):
values = {
"instance_name": self.instance_name,
"element_accumulator": DataTypeTag[self.element_accumulator],
"element_fragment": DataTypeTag[self.element_fragment],
"input_tile_iterator": operation.procedural_name() + "_default::Epilogue::OutputTileIterator"
}
return SubstituteTemplate(self.Template, values)
class TensorInputOp:
Template = """
using ${instance_name} = cutlass::epilogue::threadblock::VisitorOpTensorInput<
${element_accumulator}, ${input_tile_iterator}>;
"""
counter = 0
def __init__(self, element_accumulator) -> None:
self.element_accumulator = element_accumulator
self.instance_name = "TensorInputOp%d" % TensorInputOp.counter
TensorInputOp.counter += 1
class _Arguments(ctypes.Structure):
_fields_ = [
("input_ptr", ctypes.c_void_p),
("ldt", ctypes.c_int),
("batch_stride", ctypes.c_longlong)
]
def __init__(self, input_ptr, ldt, batch_stride=0) -> None:
self.input_ptr = int(input_ptr)
self.ldt = ldt
self.batch_stride = batch_stride
self.argument_type = _Arguments
def emit(self, operation):
values = {
"instance_name": self.instance_name,
"element_accumulator": DataTypeTag[self.element_accumulator],
"input_tile_iterator": operation.procedural_name() + "_default::Epilogue::OutputTileIterator"
}
return SubstituteTemplate(self.Template, values)
class TensorOutputOp:
Template = """
${visitor}
using ${instance_name} = cutlass::epilogue::threadblock::VisitorOpTensorOutput<
${element_accumulator}, ${output_tile_iterator}, ${visitor_name}>;
"""
counter = 0
def __init__(self, element_accumulator, visitor) -> None:
self.element_accumulator = element_accumulator
self.visitor = visitor
self.instance_name = "TensorOutputOp%d" % TensorOutputOp.counter
TensorOutputOp.counter += 1
class _Arguments(ctypes.Structure):
_fields_ = [
("output_ptr", ctypes.c_void_p),
("ldt", ctypes.c_int),
("batch_stride", ctypes.c_longlong),
("visitor_arg", self.visitor.argument_type)
]
def __init__(self, output_ptr, ldt, visitor_arg, batch_stride=0) -> None:
self.output_ptr = int(output_ptr)
self.ldt = int(ldt)
self.visitor_arg = visitor_arg
self.batch_stride = batch_stride
self.argument_type = _Arguments
def emit(self, operation):
values = {
"instance_name": self.instance_name,
"element_accumulator": DataTypeTag[self.element_accumulator],
"output_tile_iterator": operation.procedural_name() + "_default::Epilogue::OutputTileIterator",
"visitor_name": self.visitor.instance_name,
"visitor": self.visitor.emit(operation)
}
return SubstituteTemplate(self.Template, values)
class ColumnReductionOp:
Template = """
${visitor}
using ${instance_name} = cutlass::epilogue::threadblock::VisitorOpColumnReduction<
cutlass::gemm::GemmShape<${threadblock_shape_m}, ${threadblock_shape_n}, ${threadblock_shape_k}>,
${element_accumulator}, ${element_reduction}, ${element_reduction_accumulator},
${output_tile_iterator}, ${visitor_name}>;
"""
counter = 0
def __init__(self, element_accumulator, element_reduction,
element_reduction_accumulator, visitor) -> None:
self.element_accumulator = element_accumulator
self.element_reduction = element_reduction
self.element_reduction_accumulator = element_reduction_accumulator
self.visitor = visitor
self.instance_name = "ColumnReductionOp%d" % ColumnReductionOp.counter
ColumnReductionOp.counter += 1
class _Arguments(ctypes.Structure):
_fields_ = [
("reduction_ptr", ctypes.c_void_p),
("batch_stride", ctypes.c_longlong),
("visitor_arg", self.visitor.argument_type)
]
def __init__(self, reduction_ptr, visitor_arg, batch_stride=0) -> None:
self.reduction_ptr = reduction_ptr
self.batch_stride = batch_stride
self.visitor_arg = visitor_arg
self.argument_type = _Arguments
def emit(self, operation):
values = {
"instance_name": self.instance_name,
'threadblock_shape_m': str(operation.tile_description.threadblock_shape[0]),
'threadblock_shape_n': str(operation.tile_description.threadblock_shape[1]),
'threadblock_shape_k': str(operation.tile_description.threadblock_shape[2]),
"element_accumulator": DataTypeTag[self.element_accumulator],
"element_reduction": DataTypeTag[self.element_reduction],
"element_reduction_accumulator": DataTypeTag[self.element_reduction_accumulator],
"output_tile_iterator": operation.procedural_name() + "_default::Epilogue::OutputTileIterator",
"visitor_name": self.visitor.instance_name,
"visitor": self.visitor.emit(operation)
}
return SubstituteTemplate(self.Template, values)
class RowReductionOp:
Template = """
${visitor}
using ${instance_name} = cutlass::epilogue::threadblock::VisitorOpRowReduction<
cutlass::gemm::GemmShape<${threadblock_shape_m}, ${threadblock_shape_n}, ${threadblock_shape_k}>,
${element_accumulator}, ${element_reduction}, ${element_reduction_accumulator},
${output_tile_iterator}, ${visitor_name}>;
"""
counter = 0
def __init__(self, element_accumulator, element_reduction,
element_reduction_accumulator, visitor) -> None:
self.element_accumulator = element_accumulator
self.element_reduction = element_reduction
self.element_reduction_accumulator = element_reduction_accumulator
self.visitor = visitor
self.instance_name = "RowReductionOp%d" % RowReductionOp.counter
RowReductionOp.counter += 1
class _Arguments(ctypes.Structure):
_fields_ = [
("reduction_ptr", ctypes.c_void_p),
("batch_stride", ctypes.c_longlong),
("visitor_arg", self.visitor.argument_type)
]
def __init__(self, reduction_ptr, visitor_arg, batch_stride=0) -> None:
self.reduction_ptr = reduction_ptr
self.visitor_arg = visitor_arg
self.batch_stride = batch_stride
self.argument_type = _Arguments
def emit(self, operation):
values = {
"instance_name": self.instance_name,
'threadblock_shape_m': str(operation.tile_description.threadblock_shape[0]),
'threadblock_shape_n': str(operation.tile_description.threadblock_shape[1]),
'threadblock_shape_k': str(operation.tile_description.threadblock_shape[2]),
"element_accumulator": DataTypeTag[self.element_accumulator],
"element_reduction": DataTypeTag[self.element_reduction],
"element_reduction_accumulator": DataTypeTag[self.element_reduction_accumulator],
"output_tile_iterator": operation.procedural_name() + "_default::Epilogue::OutputTileIterator",
"visitor_name": self.visitor.instance_name,
"visitor": self.visitor.emit(operation)
}
return SubstituteTemplate(self.Template, values)
| warp-main | warp/native/cutlass/tools/library/scripts/pycutlass/src/pycutlass/epilogue.py |
#################################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#################################################################################################
import pycutlass
from pycutlass.test.gemm_testbed import getTensorRef, getTensorView, transpose
from pycutlass import *
import numpy as np
import cutlass
from bfloat16 import bfloat16
class TestbedGrouped:
def __init__(self, operation: GemmOperationGrouped, seed: int = 2080) -> None:
pycutlass.compiler.add_module([operation])
self.seed = seed
self.operation = operation
element_size = DataTypeSize[operation.A.element]
self.dtype_A = self.numpy_type(operation.A.element)
self.dtype_B = self.numpy_type(operation.B.element)
self.dtype_C = self.numpy_type(operation.C.element)
self.dtype_D = self.numpy_type(operation.C.element)
if element_size == 1:
self.scope_max = 1
self.scope_min = 0
elif element_size <= 8:
self.scope_max = 1
self.scope_min = -1
elif element_size == 16:
self.scope_max = 4
self.scope_min = -4
else:
self.scope_max = 8
self.scope_min = -8
#: compute type
self.compute_type = operation.epilogue_functor.element_epilogue
self.accumulator_type = operation.tile_description.math_instruction.element_accumulator
@staticmethod
def numpy_type(type):
if type == cutlass.float64:
return np.float64
elif type == cutlass.float32:
return np.float32
elif type == cutlass.float16:
return np.float16
elif type == cutlass.bfloat16:
return bfloat16
elif type == cutlass.int32:
return np.int32
elif type == cutlass.int8:
return np.int8
else:
raise ValueError("unsupported type: %s" % ShortDataTypeNames[type])
def uniform_init(self, size, dtype):
if dtype in [np.float32, np.float16, bfloat16, np.float64]:
return np.ceil(
np.random.uniform(
low=self.scope_min - 0.5, high=self.scope_max - 0.5,
size=size).astype(dtype)
)
else:
return np.random.uniform(
low=self.scope_min - 1, high=self.scope_max + 1,
size=size).astype(dtype)
def print_problem_size(self, p):
problem_size = "problem: %d, %d, %d\n" % (p.m(), p.n(), p.k())
print(problem_size)
def run(self, problem_count: int, alpha: float = 1.0, beta: float = 0.0) -> bool:
assert get_allocated_size(
) == 0, "%d byte of pool memory is not released in previous run" % get_allocated_size()
# initialize
np.random.seed(self.seed)
# generate the problem sizes
problem_sizes = []
tensor_As = []
tensor_Bs = []
tensor_Cs = []
tensor_Ds = []
tensor_D_refs = []
for i in range(problem_count):
if self.dtype_A == np.int8:
if i == 0:
problem_size = cutlass.gemm.GemmCoord(48, 16, 32)
else:
problem_size = cutlass.gemm.GemmCoord(
16 * np.random.randint(0, 64) + 48,
16 * np.random.randint(0, 64) + 48,
16 * np.random.randint(0, 64) + 48
)
else:
if i == 0:
problem_size = cutlass.gemm.GemmCoord(48, 16, 8)
else:
problem_size = cutlass.gemm.GemmCoord(
8 * np.random.randint(0, 64) + 24,
8 * np.random.randint(0, 64) + 24,
8 * np.random.randint(0, 64) + 24
)
tensor_As.append(
self.uniform_init(
size=(problem_size.m() * problem_size.k(),),
dtype=self.dtype_A)
)
tensor_Bs.append(
self.uniform_init(
size=(problem_size.n() * problem_size.k(),),
dtype=self.dtype_B)
)
tensor_Cs.append(
self.uniform_init(
size=(problem_size.m() * problem_size.n(),),
dtype=self.dtype_C)
)
tensor_Ds.append(
np.zeros(
shape=(problem_size.m() * problem_size.n(),),
dtype=self.dtype_D
)
)
tensor_D_refs.append(
np.ones(
shape=(problem_size.m() * problem_size.n(),),
dtype=self.dtype_D
)
)
problem_sizes.append(problem_size)
arguments = GemmGroupedArguments(
operation=self.operation, problem_sizes=problem_sizes,
A=tensor_As, B=tensor_Bs, C=tensor_Cs, D=tensor_Ds,
output_op=self.operation.epilogue_type(alpha, beta)
)
self.operation.run(arguments)
arguments.sync()
#
# Reference check - TODO: support caching results
#
alpha = self.compute_type(alpha).value()
beta = self.compute_type(beta).value()
init_acc = self.accumulator_type(0).value()
for idx, problem_size in enumerate(problem_sizes):
if self.operation.switched:
tensor_ref_A = getTensorRef(
tensor_As[idx], problem_size, "a", transpose(self.operation.B.layout))
tensor_ref_B = getTensorRef(
tensor_Bs[idx], problem_size, "b", transpose(self.operation.A.layout))
tensor_ref_C = getTensorRef(
tensor_Cs[idx], problem_size, "c", transpose(self.operation.C.layout))
tensor_ref_D_ref = getTensorRef(
tensor_D_refs[idx], problem_size, "d", transpose(self.operation.C.layout))
else:
tensor_ref_A = getTensorRef(
tensor_As[idx], problem_size, "a", self.operation.A.layout)
tensor_ref_B = getTensorRef(
tensor_Bs[idx], problem_size, "b", self.operation.B.layout)
tensor_ref_C = getTensorRef(
tensor_Cs[idx], problem_size, "c", self.operation.C.layout)
tensor_ref_D_ref = getTensorRef(
tensor_D_refs[idx], problem_size, "d", self.operation.C.layout)
tensor_view_D_ref = getTensorView(
tensor_D_refs[idx], problem_size, "d", self.operation.C.layout)
cutlass.test.gemm.host.gemm(problem_size, alpha, tensor_ref_A,
tensor_ref_B, beta, tensor_ref_C, tensor_ref_D_ref, init_acc)
tensor_view_D = getTensorView(
tensor_Ds[idx], problem_size, "d", self.operation.C.layout)
passed = cutlass.test.gemm.host.equals(
tensor_view_D, tensor_view_D_ref)
try:
assert passed
except AssertionError:
self.print_problem_size(problem_size)
del arguments
assert get_allocated_size(
) == 0, "%d byte of pool memory is not released after current run" % get_allocated_size()
return passed
| warp-main | warp/native/cutlass/tools/library/scripts/pycutlass/src/pycutlass/test/gemm_grouped_testbed.py |
#################################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#################################################################################################
import pycutlass
from pycutlass import *
from pycutlass.test import *
from time import sleep
from bfloat16 import bfloat16
import subprocess
from typeguard import typechecked
import re
def getTensorRef(tensor, tensor_layout, conv_kind, problem_size, operand):
ptr = tensor.__array_interface__['data'][0]
if operand == "a":
tensor_coord = cutlass.conv.implicit_gemm_tensor_a_extent(conv_kind, problem_size)
elif operand == "b":
tensor_coord = cutlass.conv.implicit_gemm_tensor_b_extent(conv_kind, problem_size)
elif operand in ["c", "d"]:
tensor_coord = cutlass.conv.implicit_gemm_tensor_c_extent(conv_kind, problem_size)
else:
raise ValueError("unknown operand: " + operand)
layout = tensor_layout.packed(tensor_coord)
if tensor.dtype == np.float64:
return cutlass.TensorRefF64NHWC(ptr, layout)
elif tensor.dtype == np.float32:
return cutlass.TensorRefF32NHWC(ptr, layout)
elif tensor.dtype == np.float16:
return cutlass.TensorRefF16NHWC(ptr, layout)
if tensor.dtype == bfloat16:
return cutlass.TensorRefBF16NHWC(ptr, layout)
elif tensor.dtype == np.int32:
return cutlass.TensorRefS32NHWC(ptr, layout)
elif tensor.dtype == np.int8:
if tensor_layout == cutlass.TensorNC32HW32:
return cutlass.TensorRefS8NC32HW32(ptr, layout)
elif tensor_layout == cutlass.TensorC32RSK32:
return cutlass.TensorRefS8C32RSK32(ptr, layout)
else:
return cutlass.TensorRefS8NHWC(ptr, layout)
else:
raise ValueError("unsupported data type")
def getTensorView(tensor, tensor_layout, conv_kind, problem_size, operand):
tensor_ref = getTensorRef(tensor, tensor_layout, conv_kind, problem_size, operand)
if operand == "a":
tensor_coord = cutlass.conv.implicit_gemm_tensor_a_extent(conv_kind, problem_size)
elif operand == "b":
tensor_coord = cutlass.conv.implicit_gemm_tensor_b_extent(conv_kind, problem_size)
elif operand in ["c", "d"]:
tensor_coord = cutlass.conv.implicit_gemm_tensor_c_extent(conv_kind, problem_size)
else:
raise ValueError("unknown operand: " + operand)
if tensor.dtype == np.float64:
return cutlass.TensorViewF64NHWC(tensor_ref, tensor_coord)
elif tensor.dtype == np.float32:
return cutlass.TensorViewF32NHWC(tensor_ref, tensor_coord)
elif tensor.dtype == np.float16:
return cutlass.TensorViewF16NHWC(tensor_ref, tensor_coord)
elif tensor.dtype == bfloat16:
return cutlass.TensorViewBF16NHWC(tensor_ref, tensor_coord)
elif tensor.dtype == np.int32:
return cutlass.TensorViewS32NHWC(tensor_ref, tensor_coord)
elif tensor.dtype == np.int8:
if tensor_layout == cutlass.TensorNC32HW32:
return cutlass.TensorViewS8NC32HW32(tensor_ref, tensor_coord)
elif tensor_layout == cutlass.TensorC32RSK32:
return cutlass.TensorViewS8C32RSK32(tensor_ref, tensor_coord)
else:
return cutlass.TensorViewS8NHWC(tensor_ref, tensor_coord)
else:
raise ValueError("unsupported data type")
# @typechecked
class Conv2dLauncher:
"""
Launcher that runs the operation on given problem size
"""
def __init__(self, operation: 'Conv2dOperation', seed: int=2080, interleaved=False,
verification=True, profiling=False, warmup_iterations=500, iterations=500, **kwargs) -> None:
self.enable_cached_results = True
self.interleaved = interleaved
# create the reduction kernel
self.reduction_operation = ReductionOperation(
shape=cutlass.MatrixCoord(4, 32 * operation.C.alignment),
C=operation.C, element_accumulator=operation.tile_description.math_instruction.element_accumulator,
element_compute=operation.epilogue_functor.element_epilogue, epilogue_functor=operation.epilogue_functor,
count=operation.C.alignment
)
#: verify the output result
self.verification = verification
#: profile the kernel's runtime
self.profiling = profiling
self.timer = GpuTimer()
self.warmup_iterations = warmup_iterations
self.iterations = iterations
if "sleep" in kwargs.keys():
self.sleep_time = kwargs["sleep"]
else:
self.sleep_time = 0
#
# Compile the operator
#
pycutlass.compiler.add_module([operation, self.reduction_operation])
self.operation = operation
self.dtype_A = Conv2dLauncher.numpy_type(operation.A.element)
self.layout_A = operation.A.layout
self.dtype_B = Conv2dLauncher.numpy_type(operation.B.element)
self.layout_B = operation.B.layout
self.dtype_C = Conv2dLauncher.numpy_type(operation.C.element)
self.layout_C = operation.C.layout
self.dtype_D = Conv2dLauncher.numpy_type(operation.C.element)
self.layout_D = operation.C.layout
accumulator_size = DataTypeSize[operation.tile_description.math_instruction.element_accumulator]
element_size = DataTypeSize[operation.A.element]
if element_size <= 8:
self.scope = 1
elif element_size == 16:
if accumulator_size <= 16:
self.scope = 2
else:
self.scope = 4
else:
self.scope = 7
# Seed
self.seed = seed
self.conv_kind = operation.conv_kind
#
# Get the host reference function
#
self.element_compute = operation.epilogue_functor.element_epilogue
self.host_conv2d = cutlass.test.conv.host.conv2d
self.timer = GpuTimer()
@staticmethod
def numpy_type(type):
if type == cutlass.float64:
return np.float64
elif type == cutlass.float32:
return np.float32
elif type == cutlass.float16:
return np.float16
elif type == cutlass.bfloat16:
return bfloat16
elif type == cutlass.int32:
return np.int32
elif type == cutlass.int8:
return np.int8
else:
raise ValueError("unsupported type: %s" % ShortDataTypeNames[type])
def print_problem_size(self, p, split_k_mode=1):
print("nhwc_%dx%dx%dx%d_krsc_%dx%dx%dx%d_padding_%dx%d_stride_%dx%d_dilation_%dx%d_splitkslices_%d_splitkmode_%d"
% (p.N, p.H, p.W, p.C, p.K, p.R, p.S, p.C, p.pad_h,
p.pad_w, p.stride_h, p.stride_w, p.dilation_h, p.dilation_w, p.split_k_slices, split_k_mode))
def uniform_init(self, size, dtype):
if dtype in [np.float32, np.float16, bfloat16, np.float64]:
return np.ceil(
np.random.uniform(
low=-self.scope - 0.5, high=self.scope - 0.5,
size=size).astype(dtype)
)
else:
return np.random.uniform(
low=-self.scope - 1, high=self.scope + 1,
size=size).astype(dtype)
def eq_gemm_size(self, problem_size):
n = problem_size.N
p = problem_size.P
q = problem_size.Q
k = problem_size.K
r = problem_size.R
s = problem_size.S
c = problem_size.C
h = problem_size.H
w = problem_size.W
if self.conv_kind == cutlass.conv.Operator.fprop:
return cutlass.gemm.GemmCoord(n * p * q, k, r * s * c)
elif self.conv_kind == cutlass.conv.Operator.dgrad:
return cutlass.gemm.GemmCoord(n * h * w, c, k * r * s)
else:
return cutlass.gemm.GemmCoord(k, r * s * c, n * p * q)
def bytes(self, problem_size, alpha, beta):
mnk = self.eq_gemm_size(problem_size)
bytes_ = \
(DataTypeSize[self.operation.A.element] * mnk.m() // 8) * mnk.k() + \
(DataTypeSize[self.operation.B.element] * mnk.n() // 8) * mnk.k() + \
(DataTypeSize[self.operation.C.element] * mnk.m() // 8) * mnk.n()
if beta != 0:
bytes_ += (DataTypeSize[self.operation.C.element] * mnk.m() // 8) * mnk.n()
return bytes_
def flops(self, problem_size):
mnk = self.eq_gemm_size(problem_size)
flops_mainloop_ = mnk.m() * mnk.n() * mnk.k() * 2
flops_epilogue_ = mnk.m() * mnk.n() * 2
# Adjust mainloop flop for dgrad stride
if self.conv_kind == cutlass.conv.Operator.dgrad:
flops_mainloop_ = flops_mainloop_ // (problem_size.stride_h * problem_size.stride_w)
flops_total_ = flops_mainloop_ + flops_epilogue_
# TODO complex-value support
# switch (operation_desc.tile_description.math_instruction.math_operation) {
# case library::MathOperationID::kMultiplyAddComplex:
# flops_total_ *=4;
# break;
# default: break;
# }
return flops_total_
def host_reference(self, problem_size, tensor_A, tensor_B, tensor_C, alpha, beta):
if self.element_compute == cutlass.float16:
alpha = cutlass.float16(alpha)
beta = cutlass.float16(beta)
elif self.element_compute == cutlass.int32:
alpha = int(alpha)
beta = int(beta)
else:
alpha = alpha
beta = beta
# if cached result is loaded
cached_result_loaded = False
if self.enable_cached_results:
# get problem key
cached_test_key = cutlass.test.conv.host.CreateCachedConv2dTestKey(
self.conv_kind, problem_size, alpha, beta,
getTensorView(tensor_A, self.layout_A, self.conv_kind, problem_size, "a"),
getTensorView(tensor_B, self.layout_B, self.conv_kind, problem_size, "b"),
getTensorView(tensor_C, self.layout_C, self.conv_kind, problem_size, "c"),
)
cached_test_result = cutlass.test.conv.host.CachedTestResult()
conv2d_result_cache_name = "cached_results_SM%d_%d.txt" % (self.operation.arch, self.seed)
cached_results = cutlass.test.conv.host.CachedTestResultListing(conv2d_result_cache_name)
# CachedTestResultListing cached_results(conv2d_result_cache_name);
cached = cached_results.find(cached_test_key)
cached_result_loaded = cached[0]
if cached_result_loaded :
cached_test_result = cached[1]
if not cached_result_loaded:
# compute the conv2d on host
tensor_D_ref = np.ones_like(tensor_C)
tensor_ref_A = getTensorRef(tensor_A, self.layout_A, self.conv_kind, problem_size, "a")
tensor_ref_B = getTensorRef(tensor_B, self.layout_B, self.conv_kind, problem_size, "b")
tensor_ref_C = getTensorRef(tensor_C, self.layout_C, self.conv_kind, problem_size, "c")
tensor_ref_D_ref = getTensorRef(tensor_D_ref, self.layout_D, self.conv_kind, problem_size, "d")
self.host_conv2d(
self.conv_kind, problem_size,
tensor_ref_A, tensor_ref_B, tensor_ref_C, tensor_ref_D_ref,
alpha, beta
)
tensor_view_D_ref = getTensorView(tensor_D_ref, self.layout_D, self.conv_kind, problem_size, "d")
if self.enable_cached_results:
cached_test_result.D = cutlass.test.conv.host.TensorHash(tensor_view_D_ref)
cached_results = cutlass.test.conv.host.CachedTestResultListing(conv2d_result_cache_name)
cached_results.append(cached_test_key, cached_test_result)
cached_results.write(conv2d_result_cache_name)
else:
return tensor_D_ref
return cached_test_result.D
def equal(self, tensor_D, tensor_D_ref, problem_size):
if self.enable_cached_results:
tensor_view_D = getTensorView(tensor_D, self.layout_D, self.conv_kind, problem_size, "d")
tensor_D_hash = cutlass.test.conv.host.TensorHash(tensor_view_D)
return tensor_D_hash == tensor_D_ref
else:
tensor_view_D = getTensorView(tensor_D, self.layout_D, self.conv_kind, problem_size, "d")
tensor_view_D_ref = getTensorView(tensor_D_ref, self.layout_D, self.conv_kind, problem_size, "d")
return cutlass.test.conv.host.equals(tensor_view_D, tensor_view_D_ref)
def run_cutlass_profiler(self, problem_size, split_k_mode=cutlass.conv.SplitKMode.Serial, alpha=1.0, beta=0.0):
if split_k_mode == cutlass.conv.SplitKMode.Serial:
split_k_mode_ = "serial"
else:
split_k_mode_ = "parallel"
cutlass_path = os.getenv('CUTLASS_PATH')
assert cutlass_path is not None, "Environment variable 'CUTLASS_PATH' is not defined."
values = {
"profiler_path": cutlass_path + "/build/tools/profiler/cutlass_profiler",
"kernel_name": self.operation.procedural_name(),
"verification_providers": "device",
"provider": "cutlass",
'n': str(problem_size.N),
'h': str(problem_size.H),
'w': str(problem_size.W),
'c': str(problem_size.C),
'k': str(problem_size.K),
'r': str(problem_size.R),
's': str(problem_size.S),
'p': str(problem_size.P),
'q': str(problem_size.Q),
'pad_h': str(problem_size.pad_h),
'pad_w': str(problem_size.pad_w),
'stride_h': str(problem_size.stride_h),
'stride_w': str(problem_size.stride_w),
'dilation_h': str(problem_size.dilation_h),
'dilation_w': str(problem_size.dilation_w),
'split_k_slices': str(problem_size.split_k_slices),
'split_k_mode': split_k_mode_,
'alpha': str(alpha),
'beta': str(beta),
'warmup': str(self.warmup_iterations),
'profile': str(self.iterations)
}
cmd_template = \
"${profiler_path} --kernels=${kernel_name} --verification-providers=${verification_providers}" \
" --providers=${provider} --n=${n} --h=${h} --w=${w} --c=${c} --k=${k} --r=${r} --s=${s} --p=${p}" \
" --q=${q} --pad_h=${pad_h} --pad_w=${pad_w} --stride_h={stride_h} --stride_w=${stride_w}" \
" --dilation_h=${dilation_h} --dilation_w=${dilation_w} --warmup-iterations=${warmup} --profiling-iterations=${profile}" \
" --split_k_slices=${split_k_slices} --alpha=${alpha} --beta=${beta} --split_k_mode=${split_k_mode}"
cmd = SubstituteTemplate(cmd_template, values)
result = subprocess.getoutput(cmd)
m = re.search(r"Runtime:\s+(?P<runtime>\d+.\d+)", result)
runtime = float(m.group('runtime'))
m = re.search(r"Bytes:\s+(?P<bytes>\d+)", result)
bytes = int(m.group('bytes'))
m = re.search(r"FLOPs:\s+(?P<flops>\d+)", result)
flops = int(m.group('flops'))
# check if the problem size matches
assert bytes == self.bytes(problem_size, alpha, beta)
assert flops == self.flops(problem_size)
return runtime
def run(self, problem_size, split_k_mode=cutlass.conv.SplitKMode.Serial,
alpha=1.0, beta=0.0):
assert get_allocated_size() == 0, "%d byte of pool memory is not released in previous run" % get_allocated_size()
#
# Initialize input and output tensors
#
tensor_A_size = cutlass.conv.implicit_gemm_tensor_a_size(self.conv_kind, problem_size)
tensor_B_size = cutlass.conv.implicit_gemm_tensor_b_size(self.conv_kind, problem_size)
tensor_C_size = cutlass.conv.implicit_gemm_tensor_c_size(self.conv_kind, problem_size)
np.random.seed(self.seed)
tensor_A = self.uniform_init(size=(tensor_A_size,), dtype=self.dtype_A)
tensor_B = self.uniform_init(size=(tensor_B_size,), dtype=self.dtype_B)
tensor_C = self.uniform_init(size=(tensor_C_size,), dtype=self.dtype_C)
tensor_D = np.zeros(shape=(tensor_C_size,), dtype=self.dtype_D)
#
# Launch kernel
#
arguments = Conv2dArguments(
operation=self.operation, problem_size=problem_size, A=tensor_A,
B=tensor_B, C=tensor_C, D=tensor_D,
output_op = self.operation.epilogue_type(alpha, beta),
split_k_slices=problem_size.split_k_slices,
split_k_mode=split_k_mode
)
if split_k_mode == cutlass.conv.SplitKMode.Parallel:
implicit_gemm_size = cutlass.conv.implicit_gemm_problem_size(self.operation.conv_kind, arguments.problem_size)
reduction_arguments = ReductionArguments(
self.reduction_operation,
problem_size=[implicit_gemm_size.m(), implicit_gemm_size.n()], partitions=problem_size.split_k_slices,
workspace=arguments.ptr_D,
destination=tensor_D,
source=tensor_C,
output_op = self.reduction_operation.epilogue_type(alpha, beta)
)
self.operation.run(arguments)
if split_k_mode == cutlass.conv.SplitKMode.Parallel:
self.reduction_operation.run(reduction_arguments)
passed = True
if self.verification:
if split_k_mode == cutlass.conv.SplitKMode.Parallel:
reduction_arguments.sync()
else:
arguments.sync()
tensor_D_ref = self.host_reference(problem_size, tensor_A, tensor_B, tensor_C, alpha, beta)
passed = self.equal(tensor_D, tensor_D_ref, problem_size)
try:
assert passed
except AssertionError:
self.print_problem_size(problem_size, split_k_mode)
if self.profiling:
sleep(self.sleep_time)
for _ in range(self.warmup_iterations):
self.operation.run(arguments)
if split_k_mode == cutlass.conv.SplitKMode.Parallel:
self.reduction_operation.run(reduction_arguments)
self.timer.start()
for _ in range(self.warmup_iterations):
self.operation.run(arguments)
if split_k_mode == cutlass.conv.SplitKMode.Parallel:
self.reduction_operation.run(reduction_arguments)
self.timer.stop_and_wait()
runtime = self.timer.duration(self.iterations)
# free memory
del arguments
if split_k_mode == cutlass.conv.SplitKMode.Parallel:
del reduction_arguments
assert get_allocated_size() == 0, "%d byte of pool memory is not released after current run" % get_allocated_size()
if self.profiling:
return runtime
return passed
########################################################################################################
# TestAllConv: Runs cutlass::conv::device::ImplicitGemmConvolution operator and compares it with reference
# TestAllConv runs conv operator on default conv problem sizes from test::conv::device::TestbedConv2dProblemSizes
# Additionaly, each conv2d test can provide conv problem sizes (conv_test_sizes) and blacklist of sizes
# (conv_blacklist_sizes)
############################################################################################################
def test_all_conv2d(operation: Conv2dOperation, conv_test_sizes = [], interleaved=False): # TODO: conv_test_sizes and conv_blacklist_sizes
passed = True
#
# Testbed object
#
testbed = Conv2dLauncher(operation, interleaved=interleaved)
#
# Get conv problem sizes to run conv operator
#
conv_problems = cutlass.test.conv.TestbedConv2dProblemSizes(64)
# Vector of conv2d problem sizes to avoid duplicate runs
conv_tested_sizes = []
# TODO: include resnet 50 sizes, user sepecified sizes, and rigorous sizes
# Flatten 2D problem_vectors into a 1D problem sizes
problem_sizes = conv_problems.conv2d_default_sizes
problem_sizes = [conv_problem for conv_problem in problem_sizes] + conv_test_sizes
# Sweep conv2d problem sizes (split-k-mode=kSerial, split-k-slices=1, alpha=1.0, beta=0.0)
for conv_problem in problem_sizes:
# TODO: skip blacklist problem sizes
if conv_problem in conv_tested_sizes:
continue
# skip channel dimension % 32 != 0 for interleaved case
if interleaved:
if conv_problem.K % 32 != 0 or conv_problem.C % 32 != 0:
continue
#
# Procedurally disable certain cases
#
# CUTLASS DGRAD's *unity* stride specialization only support stride {1, 1}
if operation.conv_kind == cutlass.conv.Operator.dgrad and operation.stride_support == StrideSupport.Unity:
if not ((conv_problem.stride_h == 1) and (conv_problem.stride_w == 1)):
continue
if not interleaved:
# Fixed channels algorithm requires channel count to match access size
if operation.iterator_algorithm == cutlass.conv.IteratorAlgorithm.fixed_channels:
if conv_problem.C != operation.A.alignment:
continue
# Few channels algorithm requires channel count to match access size
if operation.iterator_algorithm == cutlass.conv.IteratorAlgorithm.few_channels:
if conv_problem.C % operation.A.alignment:
continue
# CUTLASS DGRAD's *strided* stride specialization supports all stride {stride_h, stride_w}
# Although strided dgrad works for all stride combinations, we are only going
# to run strided dgrad for non-unity strides
if operation.conv_kind == cutlass.conv.Operator.dgrad and operation.stride_support == StrideSupport.Strided:
if (conv_problem.stride_h == 1) and (conv_problem.stride_w == 1):
continue
#
# Test
#
# push back tested problem size to avoid re-running duplicates
conv_tested_sizes.append(conv_problem)
passed = testbed.run(conv_problem)
# if not passed: return False
# TODO: If CUTLASS_UNIT_TEST_PROBLEM_COUNT is set reduce the the number of tested problem counts
if interleaved:
return True
#
# filter the cases for split K
#
# Small-channels convolution can't run here.
if operation.iterator_algorithm in [cutlass.conv.IteratorAlgorithm.fixed_channels, cutlass.conv.IteratorAlgorithm.few_channels]:
return True
# CUTLASS DGRAD's *stride* specialization does not support split-k mode
if operation.conv_kind == cutlass.conv.Operator.dgrad and operation.stride_support == StrideSupport.Strided:
conv_problem = cutlass.conv.Conv2dProblemSize(
cutlass.Tensor4DCoord(1, 56, 56, 8),
cutlass.Tensor4DCoord(8, 1, 1, 8),
cutlass.Tensor4DCoord(0, 0, 0, 0),
cutlass.MatrixCoord(2, 2),
cutlass.MatrixCoord(1, 1),
cutlass.conv.Mode.cross_correlation,
1, 1
)
passed = testbed.run(conv_problem)
return passed
# Sweep split-k-slice using serial and prallel reduction with non-unity alpha and non-zero beta for
# a single conv2d problem size. Convolution unit tests take a long time to run so only sweep parameters
# which are abolutely neccessary to catch functional bugs. The below code does provide option to sweep
# alpha and beta for local testing, but only runs one value for alpha and beta.
conv2d_split_k_test_size = cutlass.conv.Conv2dProblemSize(
cutlass.Tensor4DCoord(1, 17, 11, 288),
cutlass.Tensor4DCoord(160, 3, 3, 288),
cutlass.Tensor4DCoord(1, 1, 1, 1),
cutlass.MatrixCoord(1, 1),
cutlass.MatrixCoord(1, 1),
cutlass.conv.Mode.cross_correlation,
1, 1
)
split_k_modes = [cutlass.conv.SplitKMode.Parallel, cutlass.conv.SplitKMode.Serial]
split_k_slices = [1, 2, 3, 4, 201]
problem_alpha = [2.0,]
problem_beta = [2.0,]
for split_k_mode in split_k_modes:
for split_k_slice in split_k_slices:
for alpha in problem_alpha:
for beta in problem_beta:
passed = testbed.run(conv2d_split_k_test_size.reset_split_k_slices(split_k_slice),
split_k_mode,
alpha, beta)
return passed
| warp-main | warp/native/cutlass/tools/library/scripts/pycutlass/src/pycutlass/test/conv2d_testbed.py |
from pycutlass.test.profiler import *
from pycutlass.test.conv2d_testbed import *
from pycutlass.test.gemm_testbed import *
from pycutlass.test.gemm_grouped_testbed import *
| warp-main | warp/native/cutlass/tools/library/scripts/pycutlass/src/pycutlass/test/__init__.py |
#################################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#################################################################################################
from time import sleep
import pycutlass
from pycutlass import *
import cutlass
from cuda import cudart
from cuda import cuda
from bfloat16 import bfloat16
from .profiler import GpuTimer
import subprocess
def transpose(layout):
if layout == cutlass.RowMajor:
return cutlass.ColumnMajor
elif layout == cutlass.ColumnMajor:
return cutlass.RowMajor
elif layout == cutlass.ColumnMajorInterleaved32:
return cutlass.RowMajorInterleaved32
elif layout == cutlass.RowMajorInterleaved32:
return cutlass.ColumnMajorInterleaved32
def getTensorRef(tensor: np.ndarray, problem_size: cutlass.gemm.GemmCoord, operand: str, layout: cutlass.layout):
ptr = tensor.__array_interface__['data'][0]
if operand == "a":
tensor_coord = problem_size.mk()
elif operand == "b":
tensor_coord = problem_size.kn()
elif operand in ["c", "d"]:
tensor_coord = problem_size.mn()
else:
raise ValueError("unknonw operand: " + operand)
if layout == cutlass.RowMajor:
layout = cutlass.RowMajor.packed(tensor_coord)
layout_tag = "RowMajor"
elif layout == cutlass.ColumnMajor:
layout = cutlass.ColumnMajor.packed(tensor_coord)
layout_tag = "ColumnMajor"
elif layout == cutlass.ColumnMajorInterleaved32:
layout = cutlass.ColumnMajorInterleaved32.packed(tensor_coord)
layout_tag = "ColumnMajorInterleaved32"
elif layout == cutlass.RowMajorInterleaved32:
layout = cutlass.RowMajorInterleaved32.packed(tensor_coord)
layout_tag = "RowMajorInterleaved32"
else:
raise ValueError("unsupported layout")
if tensor.dtype == np.float32:
ref_name = "TensorRefF32" + layout_tag
elif tensor.dtype == np.float64:
ref_name = "TensorRefF64" + layout_tag
elif tensor.dtype == np.float16:
ref_name = "TensorRefF16" + layout_tag
elif tensor.dtype == bfloat16:
ref_name = "TensorRefBF16" + layout_tag
elif tensor.dtype == np.int8:
ref_name = "TensorRefS8" + layout_tag
elif tensor.dtype == np.int32:
ref_name = "TensorRefS32" + layout_tag
else:
raise ValueError("unsupported datatype %s" %
ShortDataTypeNames[tensor.dtype])
return getattr(cutlass, ref_name)(ptr, layout)
def getTensorView(tensor: np.ndarray, problem_size: cutlass.gemm.GemmCoord, operand: str, layout: str):
tensor_ref = getTensorRef(tensor, problem_size, operand, layout)
if operand == "a":
tensor_coord = problem_size.mk()
elif operand == "b":
tensor_coord = problem_size.kn()
elif operand in ["c", "d"]:
tensor_coord = problem_size.mn()
else:
raise ValueError("unknonw operand: " + operand)
if layout == cutlass.RowMajor:
layout_tag = "RowMajor"
elif layout == cutlass.ColumnMajor:
layout_tag = "ColumnMajor"
elif layout == cutlass.ColumnMajorInterleaved32:
layout_tag = "ColumnMajorInterleaved32"
elif layout == cutlass.RowMajorInterleaved32:
layout_tag = "RowMajorInterleaved32"
else:
raise ValueError("unsupported layout")
if tensor.dtype == np.float32:
ref_name = "TensorViewF32" + layout_tag
elif tensor.dtype == np.float64:
ref_name = "TensorViewF64" + layout_tag
elif tensor.dtype == np.float16:
ref_name = "TensorViewF16" + layout_tag
elif tensor.dtype == bfloat16:
ref_name = "TensorViewBF16" + layout_tag
elif tensor.dtype == np.int32:
ref_name = "TensorViewS32" + layout_tag
elif tensor.dtype == np.int8:
ref_name = "TensorViewS8" + layout_tag
else:
raise ValueError("unsupported datatype")
return getattr(cutlass, ref_name)(tensor_ref, tensor_coord)
class GemmUniversalLauncher:
def __init__(self, operation: 'GemmOperationUniversal', seed: int = 2080, interleaved=False,
verification=True, profiling=False, warmup_iterations=500, iterations=500, **kwargs) -> None:
# create the reduction kernel
self.reduction_operation: ReductionOperation = ReductionOperation(
shape=cutlass.MatrixCoord(4, 32 * operation.C.alignment),
C=operation.C, element_accumulator=operation.tile_description.math_instruction.element_accumulator,
element_compute=operation.epilogue_functor.element_epilogue, epilogue_functor=operation.epilogue_functor,
count=operation.C.alignment
)
self.math_operation = operation.tile_description.math_instruction.math_operation
#: verify the output result
self.verification = verification
#: profile the kernel's runtime
self.profiling = profiling
self.timer = GpuTimer()
self.warmup_iterations = warmup_iterations
self.iterations = iterations
if "sleep" in kwargs.keys():
self.sleep_time = kwargs["sleep"]
else:
self.sleep_time = 0
#
# Compile the operator
#
pycutlass.compiler.add_module([operation, self.reduction_operation])
self.operation = operation
self.dtype_A = GemmUniversalLauncher.numpy_type(operation.A.element)
self.dtype_B = GemmUniversalLauncher.numpy_type(operation.B.element)
self.dtype_C = GemmUniversalLauncher.numpy_type(operation.C.element)
self.dtype_D = GemmUniversalLauncher.numpy_type(operation.C.element)
accumulator_size = DataTypeSize[operation.tile_description.math_instruction.element_accumulator]
element_size = DataTypeSize[operation.A.element]
if element_size == 1:
self.scope_max = 1
self.scope_min = 0
elif element_size <= 8:
self.scope_max = 1
self.scope_min = -1
elif element_size == 16:
self.scope_max = 4
self.scope_min = -4
else:
self.scope_max = 8
self.scope_min = -8
#: seed
self.seed: int = seed
#: whether the layout is interleaved
self.interleaved = interleaved
#: compute type
self.compute_type = operation.epilogue_functor.element_epilogue
self.accumulator_type = operation.tile_description.math_instruction.element_accumulator
def print_problem_size(self, p, mode, batch_count):
if mode == cutlass.gemm.Mode.Gemm:
mode = "Gemm"
elif mode == cutlass.gemm.Mode.GemmSplitKParallel:
mode = "GemmSplitKParalel"
problem_size = "problem: %d, %d, %d\n batch_count: %d\n mode: %s" % (
p.m(), p.n(), p.k(), batch_count, mode)
print(problem_size)
@staticmethod
def numpy_type(type):
if type == cutlass.float64:
return np.float64
elif type == cutlass.float32:
return np.float32
elif type == cutlass.float16:
return np.float16
elif type == cutlass.bfloat16:
return bfloat16
elif type == cutlass.int32:
return np.int32
elif type == cutlass.int8:
return np.int8
else:
raise ValueError("unsupported type: %s" % ShortDataTypeNames[type])
def uniform_init(self, size, dtype):
if dtype in [np.float32, np.float16, bfloat16, np.float64]:
return np.ceil(
np.random.uniform(
low=self.scope_min - 0.5, high=self.scope_max - 0.5,
size=size).astype(dtype)
)
else:
return np.random.uniform(
low=self.scope_min - 1, high=self.scope_max + 1,
size=size).astype(dtype)
def reorder_tensor_B(self, tensor_B, problem_size):
reordered_tensor_B = np.empty_like(tensor_B)
tensor_ref_B = getTensorRef(
tensor_B, problem_size, "b", self.operation.B.layout)
reordered_tensor_ref_B = getTensorRef(
reordered_tensor_B, problem_size, "b", self.operation.B.layout)
cutlass.gemm.host.reorder_column(
tensor_ref_B, reordered_tensor_ref_B, problem_size)
return reordered_tensor_B
def host_reference(self, problem_size, tensor_A, tensor_B, tensor_C, alpha, beta):
# TODO
tensor_D_ref = np.ones_like(tensor_C)
alpha = self.numpy_type(self.compute_type)(alpha)
beta = self.numpy_type(self.compute_type)(beta)
init_acc = 0
alpha = self.compute_type(alpha).value()
beta = self.compute_type(beta).value()
init_acc = self.accumulator_type(init_acc).value()
if self.operation.switched:
tensor_ref_A = getTensorRef(
tensor_A, problem_size, "a", transpose(self.operation.B.layout))
tensor_ref_B = getTensorRef(
tensor_B, problem_size, "b", transpose(self.operation.A.layout))
tensor_ref_C = getTensorRef(
tensor_C, problem_size, "c", transpose(self.operation.C.layout))
tensor_ref_D_ref = getTensorRef(
tensor_D_ref, problem_size, "d", transpose(self.operation.C.layout))
else:
tensor_ref_A = getTensorRef(
tensor_A, problem_size, "a", self.operation.A.layout)
tensor_ref_B = getTensorRef(
tensor_B, problem_size, "b", self.operation.B.layout)
tensor_ref_C = getTensorRef(
tensor_C, problem_size, "c", self.operation.C.layout)
tensor_ref_D_ref = getTensorRef(
tensor_D_ref, problem_size, "d", self.operation.C.layout)
if self.math_operation in [MathOperation.multiply_add_saturate]:
cutlass.test.gemm.host.gemm_saturate(
problem_size, alpha, tensor_ref_A, tensor_ref_B, beta, tensor_ref_C, tensor_ref_D_ref, init_acc)
else:
cutlass.test.gemm.host.gemm(problem_size, alpha, tensor_ref_A,
tensor_ref_B, beta, tensor_ref_C, tensor_ref_D_ref, init_acc)
return tensor_D_ref
def equal(self, tensor_D, tensor_D_ref, problem_size):
tensor_view_D = getTensorView(
tensor_D, problem_size, "d", self.operation.C.layout)
tensor_view_D_ref = getTensorView(
tensor_D_ref, problem_size, "d", self.operation.C.layout)
return cutlass.test.gemm.host.equals(tensor_view_D, tensor_view_D_ref)
def bytes(self, problem_size, batch_count=1, alpha=1.0, beta=0.0):
m = problem_size.m()
n = problem_size.n()
k = problem_size.k()
bytes = \
(DataTypeSize[self.operation.A.element] * m // 8) * k + \
(DataTypeSize[self.operation.B.element] * n // 8) * k + \
(DataTypeSize[self.operation.C.element] * m // 8) * n
if beta != 0:
bytes += (DataTypeSize[self.operation.C.element] * m // 8) * n
bytes *= batch_count
return bytes
def flops(self, problem_size, batch_count=1):
m = problem_size.m()
n = problem_size.n()
k = problem_size.k()
flops_ = (m * n * k + m * n) * 2 * batch_count
# TODO: complex
return flops_
def run_cutlass_profiler(self, mode, problem_size, batch_count=1, alpha=1.0, beta=0.0):
cutlass_path = os.getenv('CUTLASS_PATH')
assert cutlass_path is not None, "Environment variable 'CUTLASS_PATH' is not defined."
values = {
"profiler_path": cutlass_path + "/build/tools/profiler/cutlass_profiler",
"kernel_name": self.operation.procedural_name(),
"verification_providers": "device",
"provider": "cutlass",
"m": str(problem_size.m()),
"n": str(problem_size.n()),
"k": str(problem_size.k()),
'split_k_slices': str(batch_count),
'alpha': str(alpha),
'beta': str(beta),
'warmup': str(self.warmup_iterations),
'profile': str(self.iterations)
}
cmd_template = \
"${profiler_path} --kernels=${kernel_name} --verification-providers=${verification_providers}" \
" --providers=${provider} --m=${m} --n=${n} --k=${k}"
cmd = SubstituteTemplate(cmd_template, values)
result = subprocess.getoutput(cmd)
m = re.search(r"Runtime:\s+(?P<runtime>\d+.\d+)", result)
runtime = float(m.group('runtime'))
m = re.search(r"Bytes:\s+(?P<bytes>\d+)", result)
bytes = int(m.group('bytes'))
m = re.search(r"FLOPs:\s+(?P<flops>\d+)", result)
flops = int(m.group('flops'))
# check if the problem size matches
assert bytes == self.bytes(problem_size, alpha, beta)
assert flops == self.flops(problem_size)
return runtime
def run(self, mode, problem_size, batch_count=1, alpha=1.0, beta=0.0):
assert get_allocated_size(
) == 0, "%d byte of pool memory is not released in previous run" % get_allocated_size()
np.random.seed(self.seed)
tensor_A = self.uniform_init(
size=(problem_size.m() * problem_size.k(),), dtype=self.dtype_A)
tensor_B = self.uniform_init(
size=(problem_size.n() * problem_size.k(),), dtype=self.dtype_B)
tensor_C = self.uniform_init(
size=(problem_size.m() * problem_size.n(),), dtype=self.dtype_C)
tensor_D = np.zeros(
shape=(problem_size.m() * problem_size.n(),), dtype=self.dtype_D)
#
# Launch kernel
#
arguments = GemmArguments(
operation=self.operation, problem_size=problem_size,
A=tensor_A, B=tensor_B, C=tensor_C, D=tensor_D,
output_op=self.operation.epilogue_type(alpha, beta),
gemm_mode=mode, split_k_slices=batch_count
)
if mode == cutlass.gemm.Mode.GemmSplitKParallel:
reduction_arguments = ReductionArguments(
self.reduction_operation, problem_size=[
problem_size.m(), problem_size.n()],
partitions=batch_count,
workspace=arguments.ptr_D,
destination=tensor_D,
source=tensor_C,
output_op=self.reduction_operation.epilogue_type(alpha, beta)
)
self.operation.run(arguments)
if mode == cutlass.gemm.Mode.GemmSplitKParallel:
self.reduction_operation.run(reduction_arguments)
passed = True
if self.verification:
if mode == cutlass.gemm.Mode.GemmSplitKParallel:
reduction_arguments.sync()
else:
arguments.sync()
tensor_D_ref = self.host_reference(
problem_size, tensor_A, tensor_B, tensor_C, alpha, beta)
passed = self.equal(tensor_D, tensor_D_ref, problem_size)
try:
assert passed
except AssertionError:
self.print_problem_size(problem_size, mode, batch_count)
if self.profiling:
sleep(self.sleep_time)
for _ in range(self.warmup_iterations):
self.operation.run(arguments)
if mode == cutlass.gemm.Mode.GemmSplitKParallel:
self.reduction_operation.run(reduction_arguments)
self.timer.start()
for _ in range(self.iterations):
self.operation.run(arguments)
if mode == cutlass.gemm.Mode.GemmSplitKParallel:
self.reduction_operation.run(reduction_arguments)
self.timer.stop_and_wait()
runtime = self.timer.duration(self.iterations)
# free memory and clear buffers
del arguments
if mode == cutlass.gemm.Mode.GemmSplitKParallel:
del reduction_arguments
assert get_allocated_size(
) == 0, "%d byte of pool memory is not released after current run" % get_allocated_size()
if self.profiling:
return runtime
return passed
def test_all_gemm(operation: 'GemmOperationUniversal', testcase="universal"):
passed = True
minimum_operand_element_size = min(
DataTypeSize[operation.A.element], DataTypeSize[operation.B.element])
opcode_class = operation.tile_description.math_instruction.opcode_class
if opcode_class == cutlass.OpClass.Simt:
alignment = 1
else:
alignment = 128 // minimum_operand_element_size
# int8_t gemm alignment constrainst
if opcode_class == cutlass.OpClass.Simt and operation.A.element == cutlass.int8 and operation.A.layout == cutlass.ColumnMajor:
alignment_m = 4
else:
alignment_m = alignment
if opcode_class == cutlass.OpClass.Simt and operation.B.element == cutlass.int8 and operation.A.layout == cutlass.RowMajor:
alignment_n = 4
else:
alignment_n = alignment
if opcode_class == cutlass.OpClass.Simt and operation.A.element == cutlass.int8 \
and operation.B.element == cutlass.int8 \
and (operation.A.layout == cutlass.RowMajor or operation.B.layout == cutlass.ColumnMajor):
alignment_k = 4
else:
alignment_k = alignment
threadblock_k = operation.tile_description.threadblock_shape[2]
if testcase == "interleaved":
if operation.A.layout in [cutlass.ColumnMajorInterleaved32, cutlass.RowMajorInterleaved32]:
interleavedk = 32
else:
raise ValueError("unknonw layout")
if testcase == "interleaved":
modes = [cutlass.gemm.Mode.Gemm, ]
problem_size_m = [interleavedk, 512+interleavedk]
problem_size_n = [interleavedk, 512+interleavedk]
problem_size_k = [interleavedk, threadblock_k *
operation.tile_description.stages + interleavedk]
problem_alpha = [1.0]
problem_beta = [0.0]
batch_counts = [1, ]
elif testcase == "multistage":
modes = [cutlass.gemm.Mode.Gemm, ]
problem_size_m = [16, 528]
problem_size_n = [16, 528]
problem_size_k = [threadblock_k, threadblock_k * operation.tile_description.stages +
operation.tile_description.math_instruction.instruction_shape[2]]
problem_alpha = [1.0]
problem_beta = [0.0]
batch_counts = [1, ]
else: # universal
modes = [cutlass.gemm.Mode.Gemm, cutlass.gemm.Mode.GemmSplitKParallel]
problem_size_m = [alignment_m, 512 - 3 * alignment_m]
problem_size_n = [alignment_n, 512 - 2 * alignment_n]
problem_size_k = [
alignment_k,
threadblock_k * operation.tile_description.stages - alignment_k,
threadblock_k * operation.tile_description.stages * 3 - alignment_k]
batch_counts = [1, 2, 3, 5, 7]
problem_alpha = [1.0]
problem_beta = [2.0]
testbed = GemmUniversalLauncher(
operation, interleaved=(testcase == "interleaved"))
for mode in modes:
for m in problem_size_m:
for n in problem_size_n:
for k in problem_size_k:
for batch_count in batch_counts:
for alpha in problem_alpha:
for beta in problem_beta:
# skip very small K problems
if testcase == "universal":
if (k // batch_count < 2 * threadblock_k):
continue
problem_size = cutlass.gemm.GemmCoord(m, n, k)
passed = testbed.run(
mode, problem_size, batch_count, alpha, beta)
err, = cudart.cudaDeviceSynchronize()
if err != cuda.CUresult.CUDA_SUCCESS:
raise RuntimeError(
"CUDA Error %s" % str(err))
if not passed:
return False
return passed
| warp-main | warp/native/cutlass/tools/library/scripts/pycutlass/src/pycutlass/test/gemm_testbed.py |
#################################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#################################################################################################
from cuda import cuda
from cuda import cudart
class GpuTimer:
def __init__(self) -> None:
self.events = [
cuda.cuEventCreate(cuda.CUevent_flags.CU_EVENT_DEFAULT)[1],
cuda.cuEventCreate(cuda.CUevent_flags.CU_EVENT_DEFAULT)[1]
]
def start(self, stream=cuda.CUstream(0)):
err, = cuda.cuEventRecord(self.events[0], stream)
if err != cuda.CUresult.CUDA_SUCCESS:
raise RuntimeError("CUDA Error %s" % str(err))
def stop(self, stream=cuda.CUstream(0)):
err, = cuda.cuEventRecord(self.events[1], stream)
if err != cuda.CUresult.CUDA_SUCCESS:
raise RuntimeError("CUDA Error %s" % str(err))
pass
def stop_and_wait(self, stream=cuda.CUstream(0)):
self.stop(stream)
if stream:
err, = cuda.cuStreamSynchronize(stream)
if err != cuda.CUresult.CUDA_SUCCESS:
raise RuntimeError("CUDA Error %s" % str(err))
else:
err, = cudart.cudaDeviceSynchronize()
if err != cuda.CUresult.CUDA_SUCCESS:
raise RuntimeError("CUDA Error %s" % str(err))
def duration(self, iterations=1):
err, duration = cuda.cuEventElapsedTime(self.events[0], self.events[1])
if err != cuda.CUresult.CUDA_SUCCESS:
raise RuntimeError("CUDA Error %s" % str(err))
return duration / float(iterations)
| warp-main | warp/native/cutlass/tools/library/scripts/pycutlass/src/pycutlass/test/profiler.py |
#################################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#################################################################################################
"""
Utility functions for interacting with the device
"""
from cuda import cudart
def check_cuda_errors(result: list):
"""
Checks whether `result` contains a CUDA error raises the error as an exception, if so. Otherwise,
returns the result contained in the remaining fields of `result`.
:param result: the results of the `cudart` method, consisting of an error code and any method results
:type result: list
:return: non-error-code results from the `results` parameter
"""
# `result` is of the format : (cudaError_t, result...)
err = result[0]
if err.value:
raise RuntimeError("CUDA error: {}".format(cudart.cudaGetErrorName(err)))
if len(result) == 1:
return None
elif len(result) == 2:
return result[1]
else:
return result[1:]
def device_cc(device: int = 0) -> int:
"""
Returns the compute capability of the device with ID `device`.
:param device: ID of the device to query
:type device: int
:return: compute capability of the queried device (e.g., 80 for SM80)
:rtype: int
"""
deviceProp = check_cuda_errors(cudart.cudaGetDeviceProperties(device))
major = str(deviceProp.major)
minor = str(deviceProp.minor)
return int(major + minor) | warp-main | warp/native/cutlass/tools/library/scripts/pycutlass/src/pycutlass/utils/device.py |
#################################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#################################################################################################
import numpy as np
import cutlass
from pycutlass.library import TensorDescription
from typing import Union
from bfloat16 import bfloat16
try:
import torch
torch_available = True
except ImportError:
torch_available = False
class ReferenceModule:
def __init__(self, A: TensorDescription, B: TensorDescription, C: TensorDescription) -> None:
self.layout_A = A.layout
self.layout_B = B.layout
self.layout_C = C.layout
def run(self, A: np.ndarray, B: np.ndarray, C: np.ndarray, problem_size: cutlass.gemm.GemmCoord, alpha: float=1.0, beta: float=0.0, bias=False, batch=1):
"""
Compute the reference result on CPU
Args:
A: dense operator with shape (M, K) in row-major and (K, M) in column-major
B: dense operator with shape (K, N) in row-major and (N, K) in column-major
C: dense operator with shape (M, N) in row-major and (N, M) in column-major
"""
M, N, K = problem_size.m(), problem_size.n(), problem_size.k()
if isinstance(A, np.ndarray):
if self.layout_A == cutlass.RowMajor:
A_row = np.reshape(A, newshape=(batch, M, K))
else:
A_col = np.reshape(A, newshape=(batch, K, M))
A_row = np.transpose(A_col, axes=(0, 2, 1))
if self.layout_B == cutlass.RowMajor:
B_row = np.reshape(B, newshape=(batch, K, N))
else:
B_col = np.reshape(B, newshape=(batch, N, K))
B_row = np.transpose(B_col, axes=(0, 2, 1))
if self.layout_C == cutlass.RowMajor:
if bias:
C_row = np.reshape(C, newshape=(batch, 1, N))
else:
C_row = np.reshape(C, newshape=(batch, M, N))
else:
if bias:
C_row = np.reshape(C, newshape=(batch, M, 1))
else:
C_col = np.reshape(C, newshape=(batch, N, M))
C_row = np.transpose(C_col, axes=(0, 2, 1))
if A_row.dtype == bfloat16:
# numpy's einsum doesn't support bfloat16
out_row = np.einsum("bik,bkj->bij", A_row.astype(np.float32), B_row.astype(np.float32)) * alpha + C_row * beta
out_row = out_row.astype(C_row.dtype)
else:
out_row = np.einsum("bik,bkj->bij", A_row, B_row) * alpha + C_row * beta
if self.layout_C == cutlass.ColumnMajor:
out = np.transpose(out_row, axes=(0, 2, 1))
else:
out = out_row
return out.ravel()
elif isinstance(A, torch.Tensor):
if self.layout_A == cutlass.RowMajor:
A_row = A.view((M, K))
else:
A_col = A.view((K, M))
A_row = torch.permute(A_col, (1, 0))
if self.layout_B == cutlass.RowMajor:
B_row = B.view((K, N))
else:
B_col = B.view((N, K))
B_row = torch.permute(B_col, (1, 0))
if self.layout_C == cutlass.RowMajor:
C_row = C.view((M, N))
else:
C_col = C.view((N, M))
C_row = torch.permute(C_col, (1, 0))
out_row = torch.matmul(A_row, B_row) * alpha + C_row * beta
if self.layout_C == cutlass.ColumnMajor:
out = torch.permute(out_row, (1, 0))
else:
out = out_row
return torch.flatten(out)
#####################################################################################################
# Conv2d
#####################################################################################################
if torch_available:
class Conv2dReferenceModule:
def __init__(self, A: TensorDescription, B: TensorDescription, C: TensorDescription, kind: cutlass.conv.Operator.fprop) -> None:
self.layout_A = A.layout
self.layout_B = B.layout
self.layout_C = C.layout
self.kind = kind
def run(self,
A: Union[np.ndarray, torch.Tensor],
B: Union[np.ndarray, torch.Tensor],
C: Union[np.ndarray, torch.Tensor], problem_size, alpha=1.0, beta=0.0, bias=False) -> np.ndarray:
"""
Compute the reference result on CPU
"""
n = problem_size.N
h = problem_size.H
w = problem_size.W
c = problem_size.C
k = problem_size.K
r = problem_size.R
s = problem_size.S
p = problem_size.P
q = problem_size.Q
stride_h = problem_size.stride_h
stride_w = problem_size.stride_w
pad_h = problem_size.pad_h
pad_w = problem_size.pad_w
dilation_h = problem_size.dilation_h
dilation_w = problem_size.dilation_w
groups = problem_size.groups
if isinstance(A, np.ndarray):
# the pytorch activation layout is NCHW
# weight layout is Cout Cin Kh Kw (also NCHW)
if self.layout_A == cutlass.TensorNHWC:
A_nhwc = np.reshape(A, newshape=(n, h, w, c))
A_torch_nhwc = torch.from_numpy(A_nhwc).to("cuda")
A_torch_nchw = torch.permute(A_torch_nhwc, (0, 3, 1, 2))
if self.layout_B == cutlass.TensorNHWC:
B_nhwc = np.reshape(B, newshape=(k, r, s, c))
B_torch_nhwc = torch.from_numpy(B_nhwc).to("cuda")
B_torch_nchw = torch.permute(B_torch_nhwc, (0, 3, 1, 2))
if self.layout_C == cutlass.TensorNHWC:
C_nhwc = np.reshape(C, newshape=(n, p, q, k))
C_torch_nhwc = torch.from_numpy(C_nhwc).to("cuda")
C_torch_nchw = torch.permute(C_torch_nhwc, (0, 3, 1, 2))
elif isinstance(A, torch.Tensor):
if self.kind == cutlass.conv.Operator.wgrad:
if self.layout_A == cutlass.TensorNHWC:
A_nhwc = A.view((n, p, q, k))
A_torch_nchw = torch.permute(A_nhwc, (0, 3, 1, 2))
if self.layout_B == cutlass.TensorNHWC:
B_nhwc = B.view((n, h, w, c))
B_torch_nchw = torch.permute(B_nhwc, (0, 3, 1, 2))
if self.layout_C == cutlass.TensorNHWC:
if bias:
C_nhwc = C.view((1, 1, 1, c))
else:
C_nhwc = C.view((k, r, s, c))
C_torch_nchw = torch.permute(C_nhwc, (0, 3, 1, 2))
elif self.kind == cutlass.conv.Operator.dgrad:
if self.layout_A == cutlass.TensorNHWC:
A_nhwc = A.view((n, p, q, k))
A_torch_nchw = torch.permute(A_nhwc, (0, 3, 1, 2))
if self.layout_B == cutlass.TensorNHWC:
B_nhwc = B.view((k, r, s, c))
B_torch_nchw = torch.permute(B_nhwc, (0, 3, 1, 2))
if self.layout_C == cutlass.TensorNHWC:
if bias:
C_nhwc = C.view((1, 1, 1, c))
else:
C_nhwc = C.view((n, h, w, c))
C_torch_nchw = torch.permute(C_nhwc, (0, 3, 1, 2))
else:
if self.layout_A == cutlass.TensorNHWC:
A_nhwc = A.view((n, h, w, c))
A_torch_nchw = torch.permute(A_nhwc, (0, 3, 1, 2))
if self.layout_B == cutlass.TensorNHWC:
B_nhwc = B.view((k, r, s, c))
B_torch_nchw = torch.permute(B_nhwc, (0, 3, 1, 2))
if self.layout_C == cutlass.TensorNHWC:
if bias:
C_nhwc = C.view((1, 1, 1, k))
else:
C_nhwc = C.view((n, p, q, k))
C_torch_nchw = torch.permute(C_nhwc, (0, 3, 1, 2))
if self.kind == cutlass.conv.Operator.fprop:
D_torch_nchw = alpha * torch.nn.functional.conv2d(
A_torch_nchw, B_torch_nchw, stride=(stride_h, stride_w),
padding=(pad_h, pad_w), dilation=(dilation_h, dilation_w), groups=groups) + beta * C_torch_nchw
elif self.kind == cutlass.conv.Operator.dgrad:
D_torch_nchw = alpha * torch.nn.grad.conv2d_input(
(n, c, h, w), B_torch_nchw, A_torch_nchw, padding=(pad_h, pad_w), stride=(stride_h, stride_w)
).to(torch.float32) + beta * C_torch_nchw
elif self.kind == cutlass.conv.Operator.wgrad:
D_torch_nchw = alpha * torch.nn.grad.conv2d_weight(
B_torch_nchw, (k, c, r, s), A_torch_nchw, padding=(pad_h, pad_w), stride=(stride_h, stride_w)
).to(torch.float32) + beta * C_torch_nchw
if self.layout_C == cutlass.TensorNHWC:
if isinstance(A, np.ndarray):
D_torch_out = torch.permute(D_torch_nchw, (0, 2, 3, 1)).detach().cpu().numpy()
elif isinstance(A, torch.Tensor):
D_torch_out = torch.permute(D_torch_nchw, (0, 2, 3, 1))
return D_torch_out.flatten()
| warp-main | warp/native/cutlass/tools/library/scripts/pycutlass/src/pycutlass/utils/reference_model.py |
from pycutlass.utils.reference_model import *
| warp-main | warp/native/cutlass/tools/library/scripts/pycutlass/src/pycutlass/utils/__init__.py |
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# this file creates the test/unit/gemm/device simt tests
outputDir = ""
################################################################################
# parameters
# Edge - for tiles, the edges represent the length of one side
# Ratio - the maximum ratio between 2 edges, limits the skinnyness of tiles
# MaxEdge - maximum length of each edge
# Min/Max - minimum/maximum of the product of edge lengths
################################################################################
warpsPerThreadblockEdge = [1, 2, 4, 8, 16]
warpsPerThreadblockRatio = 2
warpsPerThreadblockMax = 16
# NOTE 1x32 and 2x16 warp tile shapes fail validation for ~10% of cases
warpShapeEdges = [8, 16, 32, 64, 128, 256]
warpShapeRatio = 4
warpShapeMax = 64*64
warpShapeMin = 8*8
threadblockEdgeMax = 256
# char, type bits/elem, max tile, L0 threadblock tiles
precisions = [
["c", "cutlass::complex<float>", 64, 64*128, [ [ 64, 128], [ 64, 32] ] ],
["q", "cutlass::Quaternion<float>", 64, 64*128, [ [ 64, 128], [ 64, 32] ] ],
["d", "double", 64, 64*64, [ [ 64, 64], [ 32, 32] ] ],
["h", "cutlass::half_t", 16, 128*256, [ [256, 128], [ 64, 128], [ 64, 32] ] ],
["i", "int", 32, 128*128, [ [128, 64], [ 16, 32] ] ],
["s", "float", 32, 128*128, [ [128, 256], [128, 128], [ 64, 64] ] ],
["z", "cutlass::complex<double>", 128, 64*64, [ [ 32, 64], [ 16, 32] ] ],
]
# L1 will have a single kernel for every unique shape
# L2 will have everything else
transposes = [
[False, False],
[False, True],
[True, False],
[True, True]
]
################################################################################
# warps per threadblock
################################################################################
warpsPerThreadblocks = []
for warpsPerThreadblock0 in warpsPerThreadblockEdge:
for warpsPerThreadblock1 in warpsPerThreadblockEdge:
if warpsPerThreadblock0 / warpsPerThreadblock1 <= warpsPerThreadblockRatio and warpsPerThreadblock1 / warpsPerThreadblock0 <= warpsPerThreadblockRatio and warpsPerThreadblock0 * warpsPerThreadblock1 <= warpsPerThreadblockMax:
warpsPerThreadblocks.append([warpsPerThreadblock0,
warpsPerThreadblock1])
print("WarpsPerThreadblocks",warpsPerThreadblocks)
################################################################################
# warp shapes
################################################################################
warpNumThreads = 32
warpShapes = []
for warp0 in warpShapeEdges:
for warp1 in warpShapeEdges:
if warp0 / warp1 <= warpShapeRatio and warp1 / warp0 <= warpShapeRatio and warp0*warp1 <= warpShapeMax and warp0*warp1 > warpShapeMin:
warpShapes.append([warp0, warp1])
print("WarpShapes", warpShapes)
numL0 = 0
numL1 = 0
numL2 = 0
################################################################################
# create kernels
# create a file for each precision/transpose
# each file contains many tile sizes
################################################################################
# precisions
for precision in precisions:
# get precision char
precisionChar = precision[0]
precisionType = precision[1]
precisionBits = precision[2]
threadblockMaxElements = precision[3]
threadblockTilesL0 = precision[4]
# transposes
for transpose in transposes:
# get transpose char
columnMajorA = transpose[0]
columnMajorB = transpose[1]
transCharA = "n" if columnMajorA else "t"
transCharB = "n" if columnMajorB else "t"
# open file
fileName="simt_%sgemm_%s%s_sm50.cu" % (precisionChar, transCharA, transCharB)
print("\n", fileName)
filePath = "%s%s" % (outputDir, fileName)
out = open(filePath, "w+")
# write file header
out.write("/***************************************************************************************************\n"
" * Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. \n"
" * SPDX-License-Identifier: BSD-3-Clause \n"
" * \n"
" * Redistribution and use in source and binary forms, with or without \n"
" * modification, are permitted provided that the following conditions are met: \n"
" * \n"
" * 1. Redistributions of source code must retain the above copyright notice, this \n"
" * list of conditions and the following disclaimer. \n"
" * \n"
" * 2. Redistributions in binary form must reproduce the above copyright notice, \n"
" * this list of conditions and the following disclaimer in the documentation \n"
" * and/or other materials provided with the distribution. \n"
" * \n"
" * 3. Neither the name of the copyright holder nor the names of its \n"
" * contributors may be used to endorse or promote products derived from \n"
" * this software without specific prior written permission. \n"
" * \n"
" * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" \n"
" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \n"
" * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE \n"
" * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE \n"
" * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL \n"
" * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR \n"
" * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER \n"
" * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, \n"
" * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \n"
" * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \n"
" *\n"
" **************************************************************************************************/\n"
"/*! \\file\n"
" \\brief Tests for device-wide GEMM interface\n"
"*/\n"
"\n"
"#include <iostream>\n"
"\n"
"#include \"cutlass/cutlass.h\"\n"
"#include \"cutlass/gemm/device/gemm.h\"\n"
"#include \"cutlass/numeric_types.h\"\n"
"\n"
"#include \"../../common/cutlass_unit_test.h\"\n"
"\n"
"#include \"cutlass/util/host_tensor.h\"\n"
"#include \"cutlass/util/tensor_view_io.h\"\n"
"#include \"cutlass/util/reference/host/tensor_fill.h\"\n"
"#include \"cutlass/util/reference/host/tensor_copy.h\"\n"
"#include \"cutlass/util/reference/host/tensor_compare.h\"\n"
"#include \"cutlass/util/reference/host/gemm.h\"\n"
"\n"
"#include \"testbed.h\"\n"
"\n")
foundThreadblockTilesL0 = {}
foundThreadblockTilesL1 = {}
########################################################################
# for each combination of tile sizes
########################################################################
for warpsPerThreadblock in warpsPerThreadblocks:
for warpShape in warpShapes:
warpThreadsM = 0
if warpShape[0] > warpShape[1]:
warpThreadsM = 8
else:
warpThreadsM = 4
warpThreadsN = warpNumThreads / warpThreadsM
# skip shapes with conflicting rectangularity
# they are unlikely to be fastest
blockG = warpsPerThreadblock[0] > warpsPerThreadblock[1]
blockL = warpsPerThreadblock[0] < warpsPerThreadblock[1]
warpG = warpShape[0] > warpShape[1]
warpL = warpShape[0] < warpShape[1]
blockG2 = warpsPerThreadblock[0] > warpsPerThreadblock[1]*2
blockL2 = warpsPerThreadblock[0]*2 < warpsPerThreadblock[1]
warpG2 = warpShape[0] > warpShape[1]*2
warpL2 = warpShape[0]*2 < warpShape[1]
if blockG2 and warpL: continue
if blockL2 and warpG: continue
if warpG2 and blockL: continue
if warpL2 and blockG: continue
# check threadblock ratios and max
threadblockTile = [warpShape[0]*warpsPerThreadblock[0],
warpShape[1]*warpsPerThreadblock[1]]
if threadblockTile[0] * threadblockTile[1] > threadblockMaxElements: continue
if threadblockTile[0] > threadblockEdgeMax: continue
if threadblockTile[1] > threadblockEdgeMax: continue
totalThreads = warpNumThreads*warpsPerThreadblock[0]*warpsPerThreadblock[1]
# calculate unroll
# ensure that every iteration at least a full load of A,B are done
unrollMin = 8
unrollMin0 = totalThreads / threadblockTile[0]
unrollMin1 = totalThreads / threadblockTile[1]
unroll = max(unrollMin, unrollMin0, unrollMin1)
threadTileM = warpShape[0] / warpThreadsM
threadTileN = warpShape[1] / warpThreadsN
if threadTileM < 2 or threadTileN < 2: continue
if threadTileM*threadTileN*precisionBits > 8*8*32: continue
# epilogue currently only supports N < WarpNumThreads
if threadblockTile[1] < warpNumThreads: continue
# limit smem
smemBitsA = threadblockTile[0]*unroll*2*precisionBits
smemBitsB = threadblockTile[1]*unroll*2*precisionBits
smemKBytes = (smemBitsA+smemBitsB)/8/1024
if (smemKBytes > 48): continue
# test level 0
testLevel = -1
for tileId in range(0, len(threadblockTilesL0)):
tbTile = threadblockTilesL0[tileId]
if tbTile[0] == threadblockTile[0] and tbTile[1] == threadblockTile[1]:
if tuple(tbTile) not in foundThreadblockTilesL0:
testLevel = 0
numL0 += 1
foundThreadblockTilesL0[tuple(tbTile)] = True
# test level 1
if testLevel < 0:
threadblockTileAlreadyUsed = False
if tuple(threadblockTile) not in foundThreadblockTilesL1:
testLevel = 1
numL1 += 1
foundThreadblockTilesL1[tuple(threadblockTile)] = True
# test level 2
if testLevel < 0:
testLevel = 2
numL2 += 1
################################################################
# write this tile to file
################################################################
print("%ix%ix%i__%ix%i_%ix%i_%ix%i L%i" % (
threadblockTile[0], threadblockTile[1], unroll,
threadTileM, threadTileN,
warpThreadsM, warpThreadsN,
warpsPerThreadblock[0], warpsPerThreadblock[1], testLevel))
out.write("////////////////////////////////////////////////////////////////////////////////\n"
"// Elements / Thread: %3i x %3i\n"
"// Threads / Warp: %3i x %3i\n"
"// Warps / Block: %3i x %3i\n"
"// Threadblock: %3i x %3i x %2i\n"
% ( threadTileM, threadTileN,
warpThreadsM, warpThreadsN,
warpsPerThreadblock[0], warpsPerThreadblock[1],
threadblockTile[0], threadblockTile[1], unroll
)
)
out.write("CUTLASS_TEST_L%i(SM50_device_%sgemm_%s%s, %ix%ix%i_%ix%ix1_%ix%i_%ix%i_%ix%i, {\n" % (
testLevel,
precisionChar,
transCharA,
transCharB,
threadblockTile[0],
threadblockTile[1],
unroll,
warpShape[0],
warpShape[1],
threadTileM,
threadTileN,
warpThreadsM,
warpThreadsN,
warpsPerThreadblock[0],
warpsPerThreadblock[1]
))
out.write(" using precision = %s;\n" % precisionType)
out.write(" using ThreadblockShape = cutlass::gemm::GemmShape<%i, %i, %i>;\n" % (
threadblockTile[0],
threadblockTile[1],
unroll))
out.write(" using WarpShape = cutlass::gemm::GemmShape<%i, %i, %i>;\n\n" % (
warpShape[0],
warpShape[1],
unroll))
out.write(" static int const kEpilogueElementsPerAccess = 1;\n"
" using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>;\n"
" using EpilogueOutputOp = cutlass::epilogue::thread::LinearCombination<\n"
" precision, kEpilogueElementsPerAccess, precision, precision>;\n\n")
out.write(" using Gemm = cutlass::gemm::device::Gemm<\n"
" precision, cutlass::layout::%sMajor,\n"
" precision, cutlass::layout::%sMajor,\n"
" precision, cutlass::layout::RowMajor,\n"
" precision,\n"
" cutlass::arch::OpClassSimt,\n"
" cutlass::arch::Sm50,\n"
" ThreadblockShape, WarpShape, InstructionShape,\n"
" EpilogueOutputOp,\n"
" cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>,\n"
" 2 // Stages\n"
" >;\n" % (
"Column" if columnMajorA else "Row",
"Column" if columnMajorB else "Row",
))
out.write(" EXPECT_TRUE(test::gemm::device::TestAllGemm<Gemm>());\n"
"} )\n\n")
out.close()
print("NumKernels:", numL0, numL1, numL2)
| warp-main | warp/native/cutlass/test/unit/gemm/device/simt_sm50.py |
#################################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#################################################################################################
import gen_turing_and_volta as api_generator
import gen_sample as sample_creater
import gen_cmake as cmake_creater
import gen_verify as verify_creater
import gen_device as b2b_fused_generator
import replace_fix_impl_header
import argparse
import os
import json
parser = argparse.ArgumentParser(description="Generates Fused Multi-GEMM CUTLASS Kernels")
parser.add_argument("--config-file", default="config.json", help="JSON file containing configuration to generate")
parser.add_argument("--gen-name", default="FusedMultiGemmForward", help="Specific the output name")
parser.add_argument("--output-dir", default="", help="Specifies the output dir")
parser.add_argument("--cutlass-dir", default="", help="Specifies the dependent CUTLASS repo dir")
parser.add_argument("--gen-include-cutlass-dir", default="", help="Specifies the generated CUTLASS code include dir, if needed.")
args = parser.parse_args()
gen_name = args.gen_name
cutlass_deps_dir = args.cutlass_dir
output_dir = args.output_dir
output_dir += "/"
cutlass_deps_root = args.gen_include_cutlass_dir
if cutlass_deps_root == '':
cutlass_deps_root = cutlass_deps_dir + "/include/"
cutlass_deps_root +='/'
if not os.path.exists(output_dir):
os.makedirs(output_dir)
if not os.path.exists(output_dir + "/" + "auto_gen"):
os.mkdir(output_dir + "/" + "auto_gen")
if not os.path.exists(output_dir + "/" + "fixed_impl"):
os.mkdir(output_dir + "/" + "fixed_impl" )
if not os.path.exists(output_dir + "/" + "sample"):
os.mkdir(output_dir + "/" + "sample" )
if not os.path.exists(output_dir + "/" + "auto_gen" + "/" + "device"):
os.mkdir(output_dir + "/" + "auto_gen" + "/" + "device")
if not os.path.exists(output_dir + "/" + "auto_gen" + "/" + "kernel"):
os.mkdir(output_dir + "/" + "auto_gen" + "/" + "kernel")
if not os.path.exists(output_dir + "/" + "auto_gen" + "/" + "threadblock"):
os.mkdir(output_dir + "/" + "auto_gen" + "/" + "threadblock")
with open(args.config_file, 'r') as infile:
gemm_info_dict = json.load(infile)
keys = sorted(gemm_info_dict.keys())
fuse_gemm_info = [gemm_info_dict[k] for k in keys]
for_cutlass_gen_user_include_header_file = [
cutlass_deps_root + "cutlass/epilogue/thread/linear_combination_leaky_relu.h",
cutlass_deps_root + "cutlass/epilogue/thread/linear_combination.h",
]
for_fused_wrapper = [
cutlass_deps_root + "cutlass/epilogue/thread/linear_combination_leaky_relu.h",
cutlass_deps_root + "cutlass/epilogue/thread/linear_combination.h",
"auto_gen/device/" + gen_name + ".h",
cutlass_deps_root + "cutlass/gemm/device/gemm_batched.h",
cutlass_deps_root + "cutlass/cutlass.h",
]
# Copy fixed implementation to the output directory
fix_impl = replace_fix_impl_header.replace_fix_impl("../fixed_impl/", output_dir +"/fixed_impl/", cutlass_deps_root)
fix_impl.gen_code()
auto_gen_output_dir = output_dir + "/auto_gen/"
project_root = ""
turing_plus = b2b_fused_generator.gen_device(fuse_gemm_info, gen_name, for_cutlass_gen_user_include_header_file, cutlass_deps_root, project_root, auto_gen_output_dir)
turing_plus.gen_code(75, 'hmma1688', False)
api = api_generator.gen_one_API(fuse_gemm_info, gen_name, for_fused_wrapper, output_dir)
api.gen_code()
# Generate C++ sample
os.system("cp ../leaky_bias.h " + output_dir + "/sample/")
os.system("cp ../utils.h " + output_dir + "/sample/")
sample_dir = output_dir + "/sample/"
sample = sample_creater.gen_test(fuse_gemm_info, gen_name, for_cutlass_gen_user_include_header_file, sample_dir)
sample.gen_cpp_sample()
cmake_gen = cmake_creater.gen_build_sys(cutlass_deps_dir, output_dir)
cmake_gen.gen_code()
verify = verify_creater.gen_verify(fuse_gemm_info, gen_name, for_fused_wrapper, output_dir)
verify.gen_code()
| warp-main | warp/native/cutlass/examples/44_multi_gemm_ir_and_codegen/ir_gen/gen_all_code.py |
#################################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#################################################################################################
from typing import *
import helper
import gen_ir
import gen_kernel as gen_ker
class gen_device:
def __init__(self, fuse_gemm_info, gen_class_name, user_header_file, cutlass_deps_root, project_root, output_dir = "../"):
self.fuse_gemm_info = fuse_gemm_info
self.raw_gemm_info = fuse_gemm_info
self.b2b_num = len(fuse_gemm_info)
self.user_header_file = user_header_file
self.args = {}
# device arg struct memebr
self.arg_member = []
self.gen_class_name = gen_class_name
self.gen_kernel_name = gen_class_name + "Kernel"
self.tempalte_args = []
self.__tempalate_arg_list = {'Stages': int, 'SplitKSerial': bool, 'IsBetaZero': bool, 'AlignmentA': int, 'AlignmentB': int}
self.file_name = output_dir + "/device/" +gen_class_name +".h"
self.sample_dir = output_dir
self.cutlass_deps_root = cutlass_deps_root
self.project_root = project_root
self.this_file_root = output_dir + "/device/"
self.first_use_1stage = False
## gen kernel
self.gen_kernel = gen_ker.gen_kernel(self.tempalte_args, self.gen_class_name, self.b2b_num, output_dir, cutlass_deps_root, project_root)
def __check_arg_type(self, temp_arg):
if temp_arg in self.__tempalate_arg_list.keys():
return self.__tempalate_arg_list[temp_arg]
find_sub = False
for candidate_arg in self.__tempalate_arg_list.keys():
if (temp_arg.find(candidate_arg) != -1):
return self.__tempalate_arg_list[candidate_arg]
return 'typename'
# def gen_B2b2bGemm_class():
def set_arch(self, sm_cap, mma_tp):
if sm_cap == 75 or sm_cap == 80 or sm_cap == 86:
self.arch = "cutlass::arch::Sm" + str(sm_cap)
if mma_tp is 'hmma1688':
self.mma_shape = [16, 8, 8]
self.mma_tp = 'hmma'
elif mma_tp is 'imma8816':
self.mma_tp = 'imma'
self.mma_shape = [8, 8, 16]
else:
return 0
def gen_include_header(self):
code = '''\
/* Auto Generated code - Do not edit.*/
#pragma once
#include \"{cutlass_root}cutlass/cutlass.h\"
#include \"{cutlass_root}cutlass/numeric_types.h\"
#include \"{cutlass_root}cutlass/arch/arch.h\"
#include \"{cutlass_root}cutlass/device_kernel.h\"
#include \"{cutlass_root}cutlass/gemm/threadblock/threadblock_swizzle.h\"
#include \"{cutlass_root}cutlass/gemm/device/default_gemm_configuration.h\"
#include \"{cutlass_root}cutlass/epilogue/thread/linear_combination_relu.h\"
#include \"{cutlass_root}cutlass/epilogue/thread/linear_combination.h\"
#include \"{project_root}../kernel/b2b_gemm.h\"
#include \"{project_root}../kernel/default_b2b_gemm.h\"
'''.format(cutlass_root=self.cutlass_deps_root, project_root=self.project_root, this_file_root=self.this_file_root)
include_user_header = ""
for header in self.user_header_file:
include_user_header += "#include \"" + header + "\"\n"
return code + include_user_header
def gen_code(self, sm_cap, mma_tp, ifprint = True):
self.set_arch(sm_cap, mma_tp)
self.update_b2b_args()
print(self.fuse_gemm_info)
self.update_b2b_class_template_args()
func_code = self.gen_all_func()
member_var_code = "private:\n typename B2bGemmKernel::Params params_;\n"
gen_code = gen_ir.gen_template_class(self.gen_class_name, self.tempalte_args, func_code + member_var_code)
code = self.gen_include_header() + gen_ir.gen_namespace("cutlass", gen_ir.gen_namespace("gemm", gen_ir.gen_namespace("device", gen_code)))
if ifprint:
print(code)
print("[INFO]: Gen device code output Dir: is ", self.file_name)
with open(self.file_name, 'w+') as f:
f.write(code)
gen_kernel = self.gen_kernel.gen_code(self.first_use_1stage)
print(gen_kernel)
def update_b2b_class_template_args(self):
for arg in self.args.keys():
self.tempalte_args.append([self.__check_arg_type(arg), arg, self.args[arg]])
def update_b2b_args(self):
self.args['ElementA'] = helper.type_2_cutlass_type(self.fuse_gemm_info[0]['A_tp'])
self.args['LayoutA'] = helper.type_2_cutlass_type(self.fuse_gemm_info[0]['A_format'])
cnt = 0
warp_M_tile = 32
# Determine maxmimum N_tile
Max_Ntile = 0
for layer in self.fuse_gemm_info:
n_tile = layer['mnk'][1]
if n_tile > Max_Ntile:
Max_Ntile = n_tile
if Max_Ntile >= 256:
warp_M_tile = 16
stages_temp = []
for layer in self.fuse_gemm_info:
cnt_str = str(cnt)
B_tp_str= 'ElementB' + cnt_str
B_format_str = 'LayoutB' + cnt_str
C_tp_str= 'ElementC' + cnt_str
C_format_str = 'LayoutC' + cnt_str
Acc_str = 'ElementAccumulator' + cnt_str
self.args[B_tp_str] = helper.type_2_cutlass_type(layer['B_tp'])
self.args[B_format_str] = helper.type_2_cutlass_type(layer['B_format'])
self.args[C_tp_str] = helper.type_2_cutlass_type(layer['C_tp'])
self.args[C_format_str] = helper.type_2_cutlass_type(layer['C_format'])
self.args[Acc_str] = helper.type_2_cutlass_type(layer['Acc_tp'])
mnk = layer['mnk'][:]
tile_mnk = mnk[:]
tile_mnk[2] = 32 # force the ktile is 32
#N tile gen
if mnk[1] > 1024:
assert(0)
elif mnk[1] > 512:
tile_mnk[1] = 1024
elif mnk[1] > 256:
tile_mnk[1] = 512
elif mnk[1] > 128:
tile_mnk[1] = 256
elif mnk[1] > 64:
tile_mnk[1] = 128
elif mnk[1] > 32:
tile_mnk[1] = 64
else :
tile_mnk[1] = 32
if tile_mnk[1] == 512:
stages_temp.append(1)
else:
stages_temp.append(2)
tile_mnk[0] = 4 * warp_M_tile
epilogue_setted_type = helper.get_epilogue_tp(layer)
cutlass_epilogue_name = "LinearCombinationRelu"
if epilogue_setted_type.lower() == 'leakyrelu':
cutlass_epilogue_name = "LinearCombinationLeakyRelu"
elif epilogue_setted_type.lower() == 'identity':
cutlass_epilogue_name = "LinearCombination"
epilogue_str = 'EpilogueOutputOp' + cnt_str
if cnt != len(self.fuse_gemm_info) - 1:
n = layer['mnk'][1]
Fragments = tile_mnk[1] // 8 * 2
self.args[epilogue_str] = "cutlass::epilogue::thread::" + cutlass_epilogue_name + "<ElementC0_, " + str(Fragments) +", ElementAccumulator0_, ElementAccumulator0_>"
else:
n = layer['mnk'][1]
n_mod_8 = n % 4
N_align_elements = 1
if n_mod_8 == 0:
N_align_elements = 8
elif n_mod_8 == 4:
N_align_elements = 4
elif n_mod_8 == 2 or n_mod_8 == 6:
N_align_elements = 2
self.args[epilogue_str] = "cutlass::epilogue::thread::" + cutlass_epilogue_name+ "<ElementC0_, " + str(N_align_elements) + ", ElementAccumulator0_, ElementAccumulator0_>"
ThreadBlockShape_str = 'ThreadblockShape' + cnt_str
self.args[ThreadBlockShape_str] = helper.cvt_2_cutlass_shape(tile_mnk)
WarpShape_str = 'WarpShape' + cnt_str
tile_mnk[0] = warp_M_tile
self.args[WarpShape_str] = helper.cvt_2_cutlass_shape(tile_mnk)
cnt += 1
self.args['ElementD'] = helper.type_2_cutlass_type(self.fuse_gemm_info[self.b2b_num - 1]['C_tp'])
self.args['LayoutD'] = helper.type_2_cutlass_type(self.fuse_gemm_info[self.b2b_num - 1]['C_format'])
self.args['InstructionShape'] = helper.cvt_2_cutlass_shape(self.mma_shape)
self.args['OperatorClass'] = 'arch::OpClassTensorOp'
self.args['ArchTag'] = self.arch
self.args['ThreadblockSwizzle'] = 'threadblock::GemmBatchedIdentityThreadblockSwizzle'
for i in range(self.b2b_num):
self.args[helper.var_idx('Stages', i)] = "2"
self.args['AlignmentA'] = str(8)
self.args['AlignmentB'] = str(8)
self.args['SplitKSerial'] = 'false'
self.args['Operator'] = 'typename DefaultGemmConfiguration<OperatorClass_, ArchTag_, ElementA_, ElementB0_, ElementC0_, ElementAccumulator0_>::Operator'
self.args['IsBetaZero'] = 'false'
def gen_using_kernel(self):
code = "using B2bGemmKernel = typename kernel::DefaultB2bGemm<\n"
code += " " + "ElementA,\n"
code += " " + "LayoutA,\n"
for i in range(self.b2b_num):
code += " " + helper.var_idx("ElementB", i) + ",\n"
code += " " + helper.var_idx("LayoutB", i) + ",\n"
code += " " + helper.var_idx("ElementC", i) + ",\n"
code += " " + helper.var_idx("LayoutC", i) + ",\n"
code += " " + helper.var_idx("ElementAccumulator", i) + ",\n"
code += " " + helper.var_idx("EpilogueOutputOp", i) + ",\n"
code += " " + helper.var_idx("ThreadblockShape", i) + ",\n"
code += " " + helper.var_idx("WarpShape", i) + ",\n"
code += " " + "ElementD,\n"
code += " " + "LayoutD,\n"
code += " " + "InstructionShape,\n"
code += " " + "OperatorClass,\n"
code += " " + "ArchTag,\n"
code += " " + "ThreadblockSwizzle,\n"
for i in range(self.b2b_num):
code += " " + helper.var_idx("Stages", i) + ",\n"
code += " " + "AlignmentA,\n"
code += " " + "AlignmentB,\n"
code += " " + "SplitKSerial,\n"
code += " " + "Operator,\n"
code += " " + "IsBetaZero_\n"
code += ">::B2bGemmKernel;\n\n"
return code
def gen_args(self):
def gen_arg_member(b2b_num):
data_members = []
for i in range(b2b_num):
member_type = "GemmCoord"
member_name = "problem_size_" + str(i)
data_members.append((member_type, member_name))
member_type = "TensorRef<ElementA const, LayoutA>"
member_name = "ref_A0"
data_members.append((member_type, member_name))
for i in range(b2b_num):
member_type = "TensorRef<ElementB" + str(i) + " const, LayoutB" + str(i) +">"
member_name = "ref_B" + str(i)
data_members.append((member_type, member_name))
member_type = "TensorRef<ElementC" + str(i) + " const, LayoutC" + str(i) +">"
member_name = "ref_C" + str(i)
data_members.append((member_type, member_name))
member_type = "TensorRef<ElementD, LayoutD>"
member_name = helper.var_idx("ref_D", b2b_num - 1)
data_members.append((member_type, member_name))
for i in range(b2b_num):
member_type = "typename EpilogueOutputOp" + str(i) + "::Params"
member_name = "epilogue" + str(i)
data_members.append((member_type, member_name))
data_members.append(('int', 'batch_count'))
return data_members
def gen_arg_struct_default_ctor(struct_name, data_members, inital_param_num, inital_value):
constructs_code = gen_ir.indentation + "CUTLASS_HOST_DEVICE\n" + \
gen_ir.indentation + struct_name + " (): "
for i in range(inital_param_num):
final_param = ','
if i == inital_param_num - 1:
final_param = '{ }'
constructs_code += data_members[i][1] + inital_value + final_param
constructs_code += "\n"
return constructs_code
def gen_arg_struct_ctor(struct_name, data_members):
constructs_code = gen_ir.indentation + "CUTLASS_HOST_DEVICE\n" + \
gen_ir.indentation + struct_name + " (\n"
cnt = 0
param_num = len(data_members)
for param in data_members:
final = ',\n'
if cnt == param_num - 1:
final = '\n):\n'
constructs_code += gen_ir.indentation + param[0] + " " + param[1] + "_" + final
cnt += 1
cnt = 0
for param in data_members:
final = '),\n'
if cnt == param_num - 1:
final = ") { }\n"
constructs_code += gen_ir.indentation + param[1] + "(" + param[1] + "_" + final
cnt += 1
constructs_code += "\n"
return constructs_code
# (variable type, variable name)
struct_member = gen_arg_member(self.b2b_num)
self.arg_member = struct_member
codeBody = ""
for each_member in struct_member:
codeBody += gen_ir.indentation + each_member[0] + " " + each_member[1] + ";\n"
codeBody += gen_arg_struct_default_ctor("Arguments", struct_member, self.b2b_num, "(0,0,0)") + "\n"
codeBody += gen_arg_struct_ctor("Arguments", struct_member) + "\n"
struct_code = gen_ir.gen_struct("Arguments", codeBody)
return struct_code
def gen_func_constructs(self):
code = self.gen_class_name +"() {}"
return code
def gen_func_initialize(self):
code = "Status initialize(Arguments const &args, void *workspace = nullptr, cudaStream_t stream = nullptr) {\n" + \
"// Determine grid shape\n" + \
"ThreadblockSwizzle threadblock_swizzle;\n" + \
"cutlass::gemm::GemmCoord grid_shape = threadblock_swizzle.get_tiled_shape(\n" + \
" args.problem_size_0, \n" + \
" { ThreadblockShape0::kM, ThreadblockShape0::kN, ThreadblockShape0::kK },\n" + \
" args.batch_count);\n" + \
"// Initialize the Params structure\n" + \
"params_ = typename B2bGemmKernel::Params{\n"
for i in range(self.b2b_num):
code += helper.var_idx(" args.problem_size_", i) + ",\n"
code += " grid_shape,\n" + \
" args.ref_A0.non_const_ref(),\n"
for i in range(self.b2b_num):
code += helper.var_idx(" args.ref_B", i) + ".non_const_ref(),\n"
code += helper.var_idx(" args.ref_C", i) + ".non_const_ref(),\n"
code += helper.var_idx(" args.ref_D", self.b2b_num - 1) + ",\n"
for i in range(self.b2b_num):
code += helper.var_idx(" args.epilogue", i) + ",\n"
code += " args.batch_count\n"
code += "};\n" + \
"return Status::kSuccess;\n" + \
"}\n"
return code
def gen_func_run(self):
code = "Status run(cudaStream_t stream = nullptr) {\n" + \
"\n" + \
" ThreadblockSwizzle threadblock_swizzle;\n" + \
"\n" + \
" dim3 grid = threadblock_swizzle.get_grid_shape(params_.grid_tiled_shape);\n" + \
" dim3 block(B2bGemmKernel::kThreadCount, 1, 1);\n" + \
"\n" + \
" cudaError_t result;\n" + \
"\n" + \
" int smem_size = int(sizeof(typename B2bGemmKernel::SharedStorage));\n" + \
" if (smem_size >= (48 << 10)) {\n" + \
" result = cudaFuncSetAttribute(Kernel<B2bGemmKernel>, cudaFuncAttributeMaxDynamicSharedMemorySize, smem_size);\n" + \
"\n" + \
" if (result != cudaSuccess) {\n" + \
" return Status::kErrorInternal;\n" + \
" }\n" + \
"\n" + \
" result = cudaFuncSetAttribute(\n" + \
" Kernel<B2bGemmKernel>,\n" + \
" cudaFuncAttributePreferredSharedMemoryCarveout, 100);\n" + \
"\n" + \
" if (result != cudaSuccess) {\n" + \
" return Status::kErrorInternal;\n" + \
" }\n" + \
" }\n" + \
" cutlass::Kernel<B2bGemmKernel><<<grid, block, smem_size, stream>>>(params_);\n" + \
" result = cudaGetLastError();\n" + \
" return result == cudaSuccess ? Status::kSuccess : Status::kErrorInternal;\n" + \
" }\n"
return code
def gen_func_operator(self):
opeartor_with_arg_code = "Status operator()(\n" + \
" Arguments const &args,\n" + \
" void *workspace = nullptr,\n" + \
" cudaStream_t stream = nullptr) {\n" + \
" Status status = initialize(args, workspace);\n" + \
" \n" + \
" if (status == Status::kSuccess) {\n" + \
" status = run(stream);\n" + \
" }\n" + \
" return status;\n" + \
"}\n"
operator_code = "Status operator()(\n" + \
" cudaStream_t stream = nullptr) {\n" + \
" Status status = run(stream);\n" + \
" return status;\n" + \
"}\n"
return opeartor_with_arg_code + "\n" + operator_code
def gen_all_func(self):
return self.gen_using_kernel() + "\n" + \
self.gen_args() + "\n" + \
self.gen_func_constructs() + "\n" + \
self.gen_func_initialize() + "\n" + \
self.gen_func_run() + "\n" + \
self.gen_func_operator()
| warp-main | warp/native/cutlass/examples/44_multi_gemm_ir_and_codegen/ir_gen/gen_device.py |
#################################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#################################################################################################
import gen_ir
import helper
import gen_threadblock as gen_tb
class gen_default_Gemm:
def __init__(self, template_param, gen_class_name, b2b_num, cutlass_deps_root, project_root):
self.gen_class_name = "B2bGemm"
self.template_param = template_param
self.b2b_num = b2b_num
self.cutlass_deps_root = cutlass_deps_root
self.project_root = project_root
def gen_B2bMma(self, specialized_template_args):
code = "using B2bMma = typename cutlass::gemm::threadblock::DefaultB2bMma<\n"
code += specialized_template_args
code += ">::ThreadblockB2bMma;\n"
# print(code)
return code
def gen_epilogue(self):
epilogue_code = ""
epilogue_code += helper.var_idx("static const int kPartitionsK", self.b2b_num - 1) + helper.var_idx(" = ThreadblockShape", self.b2b_num - 1) + helper.var_idx("::kK / WarpShape", self.b2b_num - 1) + "::kK;\n"
epilogue_code += "using Epilogue = typename cutlass::epilogue::threadblock::DefaultEpilogueTensorOp<\n"
epilogue_code += " " + helper.var_idx("ThreadblockShape", self.b2b_num - 1) + ",\n"
epilogue_code += " " + helper.var_idx("typename B2bMma::Operator", self.b2b_num - 1) + ",\n"
epilogue_code += " " + helper.var_idx("kPartitionsK", self.b2b_num - 1) + ",\n"
epilogue_code += " " + helper.var_idx("EpilogueOutputOp", self.b2b_num - 1) + ",\n"
epilogue_code += " " + helper.var_idx("EpilogueOutputOp", self.b2b_num - 1) + "::kCount\n"
epilogue_code += ">::Epilogue;\n"
epilogue_code += "using B2bGemmKernel = kernel::B2bGemm<B2bMma, Epilogue, ThreadblockSwizzle, SplitKSerial>;\n\n"
return epilogue_code
def gen_include_header(self):
code = '''
/* Auto Generated code - Do not edit.*/
#pragma once
#include \"{cutlass_dir}cutlass/cutlass.h\"
#include \"{cutlass_dir}cutlass/layout/matrix.h\"
#include \"{cutlass_dir}cutlass/numeric_types.h\"
#include \"{cutlass_dir}cutlass/epilogue/threadblock/epilogue.h\"
#include \"{cutlass_dir}cutlass/epilogue/thread/linear_combination.h\"
#include \"{cutlass_dir}cutlass/gemm/gemm.h\"
#include \"{cutlass_dir}cutlass/gemm/kernel/gemm_pipelined.h\"
#include \"{cutlass_dir}cutlass/gemm/threadblock/default_mma_core_sm75.h\"
#include \"{cutlass_dir}cutlass/gemm/threadblock/default_mma_core_sm70.h\"
#include \"{cutlass_dir}cutlass/gemm/threadblock/default_mma_core_sm80.h\"
#include \"{cutlass_dir}cutlass/gemm/threadblock/default_mma_core_simt.h\"
#include \"{cutlass_dir}cutlass/gemm/threadblock/threadblock_swizzle.h\"
#include \"{cutlass_dir}cutlass/epilogue/threadblock/default_epilogue_tensor_op.h\"
#include \"{cutlass_dir}cutlass/epilogue/threadblock/default_epilogue_volta_tensor_op.h\"
#include \"{cutlass_dir}cutlass/epilogue/threadblock/default_epilogue_simt.h\"
#include \"{cutlass_dir}cutlass/transform/threadblock/predicated_tile_iterator.h\"
#include \"../kernel/b2b_gemm.h\"
#include \"../threadblock/default_b2b_mma.h\"
'''.format(cutlass_dir=self.cutlass_deps_root)
return code
def gen_code(self):
gen_using = ''
# Generate default template struct
gen_code = gen_ir.gen_template_struct("Default" + self.gen_class_name, self.template_param,"", speicalized = None, set_default=False)
filter_list = []
filter_list.append(('Stages', 2))
filter_list.append(("OperatorClass", "arch::OpClassTensorOp"))
filter_list.append(("ArchTag", "arch::Sm75"))
for i in range(self.b2b_num):
filter_list.append((helper.var_idx("LayoutC", i), "layout::RowMajor"))
rtn_template_args, speicalized_template_args = gen_ir.filtered_param(self.template_param, filter_list, keep_= True)
B2bMma_code = self.gen_B2bMma(speicalized_template_args)
epilogue_and_rest_code = self.gen_epilogue()
gen_special_code = gen_ir.gen_template_struct("Default" + self.gen_class_name, rtn_template_args, B2bMma_code + epilogue_and_rest_code, speicalized = speicalized_template_args, set_default=False)
code = gen_ir.gen_namespace("cutlass", gen_ir.gen_namespace("gemm", gen_ir.gen_namespace("kernel", gen_code + gen_special_code)))
return self.gen_include_header() + code
class gen_Kernel:
def __init__(self, template_param, gen_class_name, b2b_num, cutlass_deps_root, project_root):
self.gen_class_name = "B2bGemm"
self.template_param = template_param
self.b2bnum = b2b_num
self.cutlass_deps_root = cutlass_deps_root
self.project_root = project_root
def gen_include_header(self):
code = '''
#pragma once
#include \"{cutlass_dir}cutlass/cutlass.h\"
#include \"{cutlass_dir}cutlass/gemm/gemm.h\"
#include \"{cutlass_dir}cutlass/matrix_coord.h\"\n'''.format(cutlass_dir=self.cutlass_deps_root)
return code
def gen_Params(self):
gen_param = ""
for i in range(self.b2bnum):
gen_param += " " + helper.var_idx("cutlass::gemm::GemmCoord problem_size_", i) + ";\n"
gen_param += " " + "cutlass::gemm::GemmCoord grid_tiled_shape;\n"
gen_param += " " + "typename B2bMma::IteratorA0::Params params_A0;\n"
gen_param += " " + "typename B2bMma::IteratorA0::TensorRef ref_A0;\n"
for i in range(self.b2bnum):
gen_param += " " + helper.var_idx("typename B2bMma::IteratorB", i) + helper.var_idx("::Params params_B", i) + ";\n"
gen_param += " " + helper.var_idx("typename B2bMma::IteratorB", i) + helper.var_idx("::TensorRef ref_B", i) + ";\n"
if i == self.b2bnum - 1:
gen_param += " " + helper.var_idx("typename Epilogue::OutputTileIterator::Params params_C", i) + ";\n"
gen_param += " " + helper.var_idx("typename Epilogue::OutputTileIterator::TensorRef ref_C", i) + ";\n"
else:
gen_param += " " + helper.var_idx("typename FusedAddBiasEpilogue", i) + helper.var_idx("::OutputTileIterator::Params params_C", i) + ";\n"
gen_param += " " + helper.var_idx("typename FusedAddBiasEpilogue", i) + helper.var_idx("::OutputTileIterator::TensorRef ref_C", i) + ";\n"
gen_param += " " + helper.var_idx("typename Epilogue::OutputTileIterator::Params params_D", self.b2bnum - 1) + ";\n"
gen_param += " " + helper.var_idx("typename Epilogue::OutputTileIterator::TensorRef ref_D", self.b2bnum - 1) + ";\n"
for i in range(self.b2bnum):
gen_param += " " + helper.var_idx("typename OutputOp", i) + helper.var_idx("::Params output_op_", i) + ";\n"
gen_param += " " + 'int batch_count' + ";\n"
gen_param += " " + 'int gemm_k_iterations_0' + ";\n"
return gen_param
def gen_Memberfunc(self):
code_default = "\nCUTLASS_HOST_DEVICE\n"
code_default += "Params()"
code_default += " { } \n\n"
code_construct = "\nCUTLASS_HOST_DEVICE\n"
code_construct += "Params(\n"
for i in range(self.b2bnum):
code_construct += " " + helper.var_idx("cutlass::gemm::GemmCoord const & problem_size_", i) + ",\n"
code_construct += " " + "cutlass::gemm::GemmCoord const & grid_tiled_shape,\n"
code_construct += " " + "typename B2bMma::IteratorA0::TensorRef ref_A0,\n"
for i in range(self.b2bnum):
code_construct += " " + helper.var_idx("typename B2bMma::IteratorB", i) + helper.var_idx("::TensorRef ref_B", i) + ",\n"
if i == self.b2bnum - 1:
code_construct += " " + helper.var_idx("typename Epilogue::OutputTileIterator::TensorRef ref_C", i) + ",\n"
else:
code_construct += " " + helper.var_idx("typename FusedAddBiasEpilogue", i) + helper.var_idx("::OutputTileIterator::TensorRef ref_C", i) + ",\n"
code_construct += " " + helper.var_idx("typename Epilogue::OutputTileIterator::TensorRef ref_D", self.b2bnum - 1) + ",\n"
for i in range(self.b2bnum):
code_construct += " " + helper.var_idx("typename OutputOp", i) + helper.var_idx("::Params output_op_", i) + helper.var_idx(" = typename OutputOp", i) + "::Params(),\n"
code_construct += " " + "int batch_count = 1\n"
code_construct += "):\n"
for i in range(self.b2bnum):
code_construct += " " + helper.var_idx("problem_size_", i) + helper.var_idx("(problem_size_", i) + "),\n"
code_construct += " " + "grid_tiled_shape(grid_tiled_shape),\n"
code_construct += " " + "params_A0(ref_A0.layout()),\n"
code_construct += " " + "ref_A0(ref_A0),\n"
for i in range(self.b2bnum):
code_construct += " " + helper.var_idx("params_B", i) + helper.var_idx("(ref_B", i) + ".layout()),\n"
code_construct += " " + helper.var_idx("ref_B", i) + helper.var_idx("(ref_B", i) + "),\n"
code_construct += " " + helper.var_idx("params_C", i) + helper.var_idx("(ref_C", i) + ".layout()),\n"
code_construct += " " + helper.var_idx("ref_C", i) + helper.var_idx("(ref_C", i) + "),\n"
code_construct += " " + helper.var_idx("params_D", self.b2bnum - 1) + helper.var_idx("(ref_D", self.b2bnum - 1) + ".layout()),\n"
code_construct += " " + helper.var_idx("ref_D", self.b2bnum - 1) + helper.var_idx("(ref_D", self.b2bnum - 1) + "),\n"
for i in range(self.b2bnum):
code_construct += " " + helper.var_idx("output_op_", i) + helper.var_idx("(output_op_", i) + "), \n"
code_construct += " " + "batch_count(batch_count) {\n"
code_construct += " " + helper.var_idx("gemm_k_iterations_", 0) + helper.var_idx(" = (problem_size_", 0) + helper.var_idx(".k() + B2bMma::Shape", 0) + helper.var_idx("::kK - 1) / B2bMma::Shape", 0) + "::kK;\n"
code_construct += "}\n"
return code_default + code_construct
def gen_using(self):
code_using = ""
for i in range(self.b2bnum - 1):
code_using += " " + helper.var_idx("using OutputOp", i) + helper.var_idx(" = typename B2bMma::OutputOp", i) + ";\n"
code_using += " " + helper.var_idx("using OutputOp", self.b2bnum - 1) + " = typename Epilogue::OutputOp;\n"
for i in range(self.b2bnum - 1):
code_using += " " + helper.var_idx("using FusedAddBiasEpilogue", i) + helper.var_idx(" = typename B2bMma::FusedAddBiasEpilogue", i) +";\n"
code_using += " " + "using WarpCount0 = typename B2bMma::WarpCount0;\n"
code_using += " " + "static int const kThreadCount = 32 * WarpCount0::kCount;\n"
code_using += gen_ir.gen_struct("Params", self.gen_Params() + self.gen_Memberfunc())
code_using += "union SharedStorage {\n"
code_using += " " + "typename B2bMma::B2bMmaSharedStorage main_loop;\n"
code_using += " " + "typename Epilogue::SharedStorage epilogue;\n"
code_using += "};\n"
return code_using
def gen_can_implement(self):
gen_code = ""
return gen_code
def gen_operator_and_constr(self):
ctr_code = "CUTLASS_HOST_DEVICE\n"
ctr_code += self.gen_class_name + "() { } \n\n"
operator_code = "CUTLASS_DEVICE\n"
operator_code += "void operator()(Params const ¶ms, SharedStorage &shared_storage) {\n"
operator_code += " " + "ThreadblockSwizzle threadblock_swizzle;\n"
operator_code += " " + "cutlass::gemm::GemmCoord threadblock_tile_offset = threadblock_swizzle.get_tile_offset(params.grid_tiled_shape);\n"
operator_code += " " + "int batch_idx = threadblock_tile_offset.k();\n"
operator_code += " " + "if (params.grid_tiled_shape.m() <= threadblock_tile_offset.m() ||\n"
operator_code += " " + "params.grid_tiled_shape.n() <= threadblock_tile_offset.n()) {\n"
operator_code += " " + " " + "return;\n"
operator_code += " " + "}\n"
operator_code += " " + "cutlass::MatrixCoord tb_offset_A0{\n"
operator_code += " " + " " + "threadblock_tile_offset.m() * B2bMma::Shape0::kM,\n"
operator_code += " " + " " + "0\n"
operator_code += " " + "};\n"
for i in range(self.b2bnum):
operator_code += " " + helper.var_idx("cutlass::MatrixCoord tb_offset_B", i) + "{\n"
operator_code += " " + " " + "0,\n"
operator_code += " " + " " + helper.var_idx("threadblock_tile_offset.n() * B2bMma::Shape", i) + "::kN\n"
operator_code += " " + "};\n"
operator_code += " " + "int thread_idx = threadIdx.x;\n\n"
operator_code += " " + "MatrixCoord threadblock_offset(\n"
operator_code += " " + " " + helper.var_idx("threadblock_tile_offset.m() * B2bMma::Shape", self.b2bnum - 1) + "::kM,\n"
operator_code += " " + " " + helper.var_idx("threadblock_tile_offset.n() * B2bMma::Shape", self.b2bnum - 1) + "::kN\n"
operator_code += " " + ");\n"
operator_code += " " + "typename B2bMma::IteratorA0 iterator_A0(\n"
operator_code += " " + " " + "params.params_A0,\n"
operator_code += " " + " " + "params.ref_A0.data(),\n"
operator_code += " " + " " + "params.problem_size_0.mk(),\n"
operator_code += " " + " " + "thread_idx,\n"
operator_code += " " + " " + "tb_offset_A0);\n"
operator_code += " " + "iterator_A0.add_pointer_offset(batch_idx * params.problem_size_0.m() * params.problem_size_0.k());\n\n"
for i in range (self.b2bnum):
operator_code += " " + helper.var_idx("typename B2bMma::IteratorB", i ) + helper.var_idx(" iterator_B", i) + "(\n"
operator_code += " " + " " + helper.var_idx("params.params_B", i) + ",\n"
operator_code += " " + " " + helper.var_idx("params.ref_B", i) + ".data(),\n"
operator_code += " " + " " + helper.var_idx("params.problem_size_", i) + ".kn(),\n"
operator_code += " " + " " + "thread_idx,\n"
operator_code += " " + " " + helper.var_idx("tb_offset_B", i) + ");\n"
operator_code += " " + helper.var_idx("iterator_B", i) + helper.var_idx(".add_pointer_offset(batch_idx * params.problem_size_", i) + helper.var_idx(".n() * params.problem_size_", i) + ".k());\n\n"
for i in range (self.b2bnum - 1):
operator_code += " " + helper.var_idx("typename FusedAddBiasEpilogue", i ) + helper.var_idx("::OutputTileIterator iterator_C", i) + "(\n"
operator_code += " " + " " + helper.var_idx("params.params_C", i) + ",\n"
operator_code += " " + " " + helper.var_idx("params.ref_C", i) + ".data(),\n"
operator_code += " " + " " + helper.var_idx("params.problem_size_" , i) + ".mn(),\n"
operator_code += " " + " " + "thread_idx,\n"
operator_code += " " + " " + "threadblock_offset" + ");\n"
operator_code += " " + helper.var_idx("int ref_C", i) + helper.var_idx("_stride = params.ref_C", i) + ".stride()[0];\n"
operator_code += " " + helper.var_idx("iterator_C", i) + helper.var_idx(".add_pointer_offset(batch_idx * params.problem_size_", i) + helper.var_idx(".n() * (ref_C", i) + helper.var_idx("_stride == 0 ? 1 : params.problem_size_", i) + ".m()));\n\n"
for i in range (self.b2bnum - 1):
operator_code += " " + helper.var_idx("FusedAddBiasEpilogue", i ) + helper.var_idx(" epilogue_", i ) + ";\n"
operator_code += " " + "int warp_idx = __shfl_sync(0x1f, threadIdx.x / 32, 0);\n"
operator_code += " " + "int lane_idx = threadIdx.x % 32;\n"
for i in range (self.b2bnum - 1):
operator_code += " " + helper.var_idx("OutputOp", i) + helper.var_idx(" output_op_", i) + helper.var_idx("(params.output_op_", i) + ");\n"
operator_code += " " + "B2bMma b2bMma(shared_storage.main_loop, thread_idx, warp_idx, lane_idx);\n"
operator_code += " " + "typename B2bMma::FragmentC0 src_accum;\n"
operator_code += " " + helper.var_idx("typename B2bMma::FragmentC", self.b2bnum - 1)+ " accumulators;\n"
operator_code += " " + "src_accum.clear();\n"
operator_code += " " + "accumulators.clear();\n"
operator_code += " " + "b2bMma(params.gemm_k_iterations_0, accumulators, iterator_A0, "
for i in range(self.b2bnum):
operator_code += helper.var_idx("iterator_B", i) + ", "
operator_code += "src_accum"
if self.b2bnum != 1:
operator_code += ", "
for i in range(self.b2bnum - 1):
operator_code += helper.var_idx("output_op_", i) + ", "
for i in range(self.b2bnum - 1):
operator_code += helper.var_idx("epilogue_", i) + ", "
for i in range(self.b2bnum - 1):
final = ", "
if i == self.b2bnum - 2:
final =""
operator_code += helper.var_idx("iterator_C", i) + final
operator_code += ");\n"
operator_code += " " + helper.var_idx("OutputOp", self.b2bnum - 1) + helper.var_idx(" output_op_", self.b2bnum - 1) + helper.var_idx("(params.output_op_", self.b2bnum - 1) + ");\n"
operator_code += " " + "threadblock_tile_offset = threadblock_swizzle.get_tile_offset(params.grid_tiled_shape);\n"
operator_code += " " + helper.var_idx("typename Epilogue::OutputTileIterator iterator_C", self.b2bnum - 1) + "(\n"
operator_code += " " + " " + helper.var_idx("params.params_C", self.b2bnum - 1) + ",\n"
operator_code += " " + " " + helper.var_idx("params.ref_C", self.b2bnum - 1) + ".data(),\n"
operator_code += " " + " " + helper.var_idx("params.problem_size_", self.b2bnum - 1) + ".mn(),\n"
operator_code += " " + " " + "thread_idx,\n"
operator_code += " " + " " + "threadblock_offset\n"
operator_code += " " + ");\n"
operator_code += " " + helper.var_idx("int ref_C", self.b2bnum - 1) + helper.var_idx("_stride = params.ref_C", self.b2bnum - 1) + ".stride()[0];\n"
operator_code += " " + helper.var_idx("iterator_C", self.b2bnum - 1) + helper.var_idx(".add_pointer_offset(batch_idx * params.problem_size_", self.b2bnum - 1) + helper.var_idx(".n() * (ref_C", self.b2bnum - 1) + helper.var_idx("_stride == 0 ? 1 : params.problem_size_", self.b2bnum - 1) + ".m()));\n\n"
operator_code += " " + helper.var_idx("typename Epilogue::OutputTileIterator iterator_D", self.b2bnum - 1) + "(\n"
operator_code += " " + " " + helper.var_idx("params.params_D", self.b2bnum - 1) + ",\n"
operator_code += " " + " " + helper.var_idx("params.ref_D", self.b2bnum - 1) + ".data(),\n"
operator_code += " " + " " + helper.var_idx("params.problem_size_", self.b2bnum - 1) + ".mn(),\n"
operator_code += " " + " " + "thread_idx,\n"
operator_code += " " + " " + "threadblock_offset\n"
operator_code += " " + ");\n"
operator_code += " " + helper.var_idx("iterator_D", self.b2bnum - 1) + helper.var_idx(".add_pointer_offset(batch_idx * params.problem_size_", self.b2bnum - 1) + helper.var_idx(".n() * params.problem_size_", self.b2bnum - 1) + ".m());\n\n"
operator_code += " " + "Epilogue epilogue(\n"
operator_code += " " + " " + "shared_storage.epilogue,\n"
operator_code += " " + " " + "thread_idx,\n"
operator_code += " " + " " + "warp_idx,\n"
operator_code += " " + " " + "lane_idx\n"
operator_code += " " + ");\n"
operator_code += " " + "epilogue("
operator_code += helper.var_idx("output_op_", self.b2bnum - 1) + ", "
operator_code += helper.var_idx("iterator_D", self.b2bnum - 1) + ", "
operator_code += "accumulators, "
operator_code += helper.var_idx("iterator_C", self.b2bnum - 1) + ");\n"
operator_code += "}\n"
return ctr_code + operator_code
def gen_include_header(self):
code = '''
#pragma once
#include \"{cutlass_dir}cutlass/cutlass.h\"
#include \"{cutlass_dir}cutlass/gemm/gemm.h\"
#include \"{cutlass_dir}cutlass/matrix_coord.h\"
#include \"{cutlass_dir}cutlass/semaphore.h\"
'''.format(cutlass_dir=self.cutlass_deps_root)
return code
def gen_code(self):
template_param = []
template_param.append(("typename", "B2bMma"))
template_param.append(("typename", "Epilogue"))
template_param.append(("typename", "ThreadblockSwizzle"))
template_param.append((bool, "SplitKSerial"))
code_body = ""
code_body += self.gen_using()
code_body += self.gen_operator_and_constr()
struct_code = gen_ir.gen_template_struct(self.gen_class_name, template_param, code_body)
code = self.gen_include_header()
code += gen_ir.gen_namespace("cutlass", gen_ir.gen_namespace("gemm", gen_ir.gen_namespace("kernel", struct_code)))
return self.gen_include_header() + code
class gen_kernel:
def __init__(self, template_param, gen_class_name, b2b_num, output_dir, cutlass_deps_root, project_root):
self.template_param = template_param
self.gen_class_name = "B2bGemm"
self.gen_kernel_name = gen_class_name + "Kernel"
self.tempalte_args = []
self.cutlass_deps_root = cutlass_deps_root
self.project_root = project_root
self.gen_default_b2b_gemm = gen_default_Gemm(template_param, gen_class_name, b2b_num, cutlass_deps_root, project_root)
self.gen_Kerenl = gen_Kernel(template_param, gen_class_name, b2b_num, cutlass_deps_root, project_root)
# Include gen_threadBlock
self.gen_threadBlock = gen_tb.gen_threadblock(template_param, gen_class_name, b2b_num, output_dir, cutlass_deps_root, project_root)
self.file_dir = output_dir + "/kernel/"
def gen_code(self, first_use_1stage):
default_b2b_gemm = self.gen_default_b2b_gemm.gen_code()
print("[INFO]: Gen kernel code [default_b2b_gemm.h]output Dir: is ", self.file_dir)
with open(self.file_dir + "default_b2b_gemm.h", "w+") as f:
f.write(default_b2b_gemm)
kernel = self.gen_Kerenl.gen_code()
print("[INFO]: Gen kernel code [b2b_gemm.h]output Dir: is ", self.file_dir)
with open(self.file_dir + "b2b_gemm.h", "w+") as f:
f.write(kernel)
# Call code to gen threadblock
self.gen_threadBlock.gen_code(first_use_1stage)
| warp-main | warp/native/cutlass/examples/44_multi_gemm_ir_and_codegen/ir_gen/gen_kernel.py |
#################################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#################################################################################################
import gen_ir
import helper
class gen_default_b2b_mma:
def __init__(self, template_param, gen_class_name, b2b_num,cutlass_deps_root, project_root):
self.gen_class_name = "DefaultB2bMma"
self.template_param = template_param
self.b2b_num = b2b_num
self.cutlass_deps_root = cutlass_deps_root
self.project_root = project_root
def gen_include_header(self):
code = '''
/* Auto Generated code - Do not edit.*/
#pragma once
#include \"{cutlass_dir}cutlass/cutlass.h\"
#include \"{cutlass_dir}cutlass/numeric_types.h\"
#include \"{cutlass_dir}cutlass/arch/arch.h\"
#include \"{cutlass_dir}cutlass/transform/threadblock/predicated_tile_iterator.h\"
#include \"{cutlass_dir}cutlass/transform/threadblock/predicated_tile_iterator_2dthreadtile.h\"
#include \"{cutlass_dir}cutlass/gemm/threadblock/default_mma_core_sm70.h\"
#include \"{cutlass_dir}cutlass/gemm/threadblock/default_mma_core_sm75.h\"
#include \"{cutlass_dir}cutlass/gemm/threadblock/default_mma_core_sm80.h\"
#include \"../threadblock/b2b_mma_pipelined.h\"
#include \"../../fixed_impl/epilogue/threadblock/fused_bias_act_epilogue.h\"
#include \"../../fixed_impl/epilogue/threadblock/default_bias_act_epilogue_tensor_op.h\"
#include \"../../fixed_impl/gemm/warp/mma_tensor_op_fragment_iterator_without_output_op.h\"
'''.format(cutlass_dir=self.cutlass_deps_root)
return code
def gen_using_MmaCore(self, stage):
threadBlockShape = "ThreadblockShape"
warpShape = "WarpShape"
instrunctionShape = "InstructionShape"
Mma_typename = "typename cutlass::gemm::threadblock::DefaultMmaCore"
gen_code = ""
for i in range(self.b2b_num):
code_using = "using MmaCore" + str(i)
gen_code += code_using + " = " + gen_ir.gen_declare_template_struct(Mma_typename, \
helper.var_idx(threadBlockShape, i), helper.var_idx(warpShape, i), instrunctionShape, \
"ElementA", "LayoutA", \
helper.var_idx("ElementB", i), helper.var_idx("LayoutB", i), \
helper.var_idx("ElementAccumulator", i), "layout::RowMajor", \
"OperatorClass", str(stage), "Operator")
return gen_code
def gen_using_FusedAddBiasEpilouge(self):
gen_code = ""
for i in range(self.b2b_num - 1):
code_using = helper.var_idx("using FusedAddBiasEpilouge", i)
epilouge_name = "typename cutlass::epilogue::threadblock::DefaultFusedBiasActEpilogueTensorOp"
template_args = helper.var_idx("<ThreadblockShape", i) + helper.var_idx(",typename MmaCore", i) + helper.var_idx("::MmaPolicy::Operator, 1, EpilogueOutputOp", i) + ", 2>::Epilogue"
gen_code += code_using + " = " + epilouge_name + template_args + ";\n"
return gen_code
def gen_using_Iterator(self):
code_using = "using IteratorA0"
iterator_typename = "cutlass::transform::threadblock::PredicatedTileIterator"
MmaCore = "MmaCore0"
matrix_shape = "cutlass::MatrixShape<" + MmaCore + "::Shape::kM, " + MmaCore + "::Shape::kK>"
iterator_map = "typename " + MmaCore + "::IteratorThreadMapA"
gen_code = code_using + " = " + gen_ir.gen_declare_template_struct(iterator_typename, \
matrix_shape, "ElementA", "LayoutA", "1", iterator_map, "AlignmentA_")
for i in range(self.b2b_num):
code_using = "using IteratorB" + str(i)
iterator_typename = "cutlass::transform::threadblock::PredicatedTileIterator"
MmaCore = "MmaCore" + str(i)
matrix_shape = "cutlass::MatrixShape<" + MmaCore + "::Shape::kK, " + MmaCore + "::Shape::kN>"
iterator_map = "typename " + MmaCore + "::IteratorThreadMapB"
gen_code += code_using + " = " + gen_ir.gen_declare_template_struct(iterator_typename, \
matrix_shape, helper.var_idx("ElementB", i), helper.var_idx("LayoutB", i), "0", iterator_map, "AlignmentB_")
return gen_code
def gen_fragment_iterator(self):
gen_code = "using AccumulatorLayout = cutlass::layout::ColumnMajor;\n"
for i in range(1, self.b2b_num):
code_using = "using FragmentIteratorA" + str(i)
iterator_typename = "cutlass::gemm::warp::MmaTensorOpPureFragmentIterator"
curr_MmaCore = "MmaCore" + str(i)
prev_MmaCore = "MmaCore" + str(i - 1)
Matrix_shape_curr = "cutlass::MatrixShape<" + curr_MmaCore + "::WarpShape::kM, " + curr_MmaCore + "::InstructionShape::kK>"
Matrix_shape_prev = "cutlass::MatrixShape<" + prev_MmaCore + "::WarpShape::kM, " + prev_MmaCore + "::WarpShape::kN>"
Curr_shape_kK = curr_MmaCore + "::Shape::kK"
gen_code += code_using + " = " + gen_ir.gen_declare_template_struct(iterator_typename, \
Matrix_shape_curr, Matrix_shape_prev, Curr_shape_kK, \
helper.var_idx("ElementAccumulator", i-1), "ElementA", \
"AccumulatorLayout", "InstructionShape_", "true")
return gen_code
def gen_threadblockmma(self):
code_using = "using ThreadblockB2bMma"
iterator_typename = "cutlass::gemm::threadblock::B2bMmaPipelined"
MmaPipelined_param_Mma0_shape = "typename MmaCore0::Shape"
MmaPipelined_param_Mma0_iteratorA = "IteratorA0"
MmaPipelined_param_Mma0_smemIteratorA = "typename MmaCore0::SmemIteratorA"
MmaPipelined_param_Mma0_iteratorB = "IteratorB0"
MmaPipelined_param_Mma0_smemIteratorB = "typename MmaCore0::SmemIteratorB"
MmaPipelined_param_list = MmaPipelined_param_Mma0_shape + ", " + MmaPipelined_param_Mma0_iteratorA + ", " + MmaPipelined_param_Mma0_smemIteratorA + ", " + MmaPipelined_param_Mma0_iteratorB + ", " + MmaPipelined_param_Mma0_smemIteratorB + ", "
for i in range(1, self.b2b_num):
MmaPipelined_param_Mma_shape = "typename MmaCore" + str(i) + "::Shape"
MmaPipelined_param_Mma_iteratorA = "FragmentIteratorA" + str(i)
MmaPipelined_param_Mma_iteratorB = "IteratorB" + str(i)
MmaPipelined_param_Mma_smemIteratorB = "typename MmaCore" + str(i) + "::SmemIteratorB"
MmaPipelined_param_list += MmaPipelined_param_Mma_shape + ", " + MmaPipelined_param_Mma_iteratorA + ", " + MmaPipelined_param_Mma_iteratorB + ", " + MmaPipelined_param_Mma_smemIteratorB + ", "
MmaPipelined_param_list += "ElementAccumulator0, layout::RowMajor, "
for i in range(self.b2b_num - 1):
epilouge_name = "EpilogueOutputOp" + str(i)
MmaPipelined_param_list += epilouge_name + ", "
for i in range(self.b2b_num - 1):
epilouge_name = "FusedAddBiasEpilouge" + str(i)
MmaPipelined_param_list += epilouge_name + ", "
for i in range(self.b2b_num):
MmaPolicy = "typename MmaCore" + str(i) + "::MmaPolicy"
MmaPipelined_param_list += MmaPolicy + ", "
cnt = 0
for i in range(self.b2b_num):
MmaStage = helper.var_idx("Stages", i)
final = ", "
if cnt == self.b2b_num - 1:
final = ""
MmaPipelined_param_list += MmaStage + final
cnt += 1
gen_code = code_using + " = " + gen_ir.gen_declare_template_struct(iterator_typename, MmaPipelined_param_list)
return gen_code
def gen_code(self):
gen_using = ''
# Generate default template struct
gen_code = gen_ir.gen_template_struct(self.gen_class_name, self.template_param, "", speicalized = None, set_default=False)
# Generate specialized template struct
mmacore_codebody = self.gen_using_MmaCore(2)
iterator_codebody = self.gen_using_Iterator()
fragment_iterator_codebody = self.gen_fragment_iterator()
epilogue_iterator_codebody = self.gen_using_FusedAddBiasEpilouge()
threadBlockMma = self.gen_threadblockmma()
specialized_code = mmacore_codebody + iterator_codebody + fragment_iterator_codebody + epilogue_iterator_codebody + threadBlockMma
# Specialize layout C -> cutlass::layout::RowMajor
rtn_template_args, speicalized_template_args = gen_ir.filtered_param(self.template_param, [ ('LayoutD', "cutlass::layout::RowMajor")], keep_= True)
gen_speical_code = gen_ir.gen_template_struct(self.gen_class_name, rtn_template_args, specialized_code, speicalized = speicalized_template_args, set_default=False)
code = gen_ir.gen_namespace("cutlass", gen_ir.gen_namespace("gemm", gen_ir.gen_namespace("threadblock", gen_code + gen_speical_code)))
return self.gen_include_header() + code
class gen_b2b_mme_pipelined:
def __init__(self, template_param, gen_class_name, b2b_num, cutlass_deps_root, project_root):
self.gen_class_name = "B2bMmaPipelined"
self.template_param = template_param
self.b2b_num = b2b_num
self.cutlass_deps_root = cutlass_deps_root
self.project_root = project_root
def gen_include_header(self):
code = '''
#pragma once
#include \"{cutlass_dir}cutlass/cutlass.h\"
#include \"{cutlass_dir}cutlass/array.h\"
#include \"{cutlass_dir}cutlass/aligned_buffer.h\"
#include \"{cutlass_dir}cutlass/numeric_conversion.h\"
#include \"{cutlass_dir}cutlass/numeric_types.h\"
#include \"{cutlass_dir}cutlass/matrix_shape.h\"
#include \"{cutlass_dir}cutlass/gemm/gemm.h\"
#include \"{cutlass_dir}cutlass/gemm/warp/mma_tensor_op_fragment_iterator.h\"
#include \"../threadblock/b2b_mma_base.h\"\n'''.format(cutlass_dir = self.cutlass_deps_root)
return code
def gen_using(self):
code_using = "using FragmentA0 = typename IteratorA0::Fragment;\n"
code_using += "using Base = B2bMmaBase<"
for i in range(self.b2b_num):
code_using += helper.var_idx("Shape", i) + "_, "
for i in range(self.b2b_num):
code_using += helper.var_idx("Policy", i) + "_, "
for i in range(self.b2b_num):
code_using += helper.var_idx("Stage", i) + "_, "
code_using = code_using[: -2] + ">;\n"
for i in range(self.b2b_num):
code_using += helper.var_idx("using FragmentB", i) + helper.var_idx(" = typename IteratorB", i) + "::Fragment;\n"
code_using += helper.var_idx("using FragmentC", i) + helper.var_idx(" = typename Policy", i) + "::Operator::FragmentC;\n"
code_using += helper.var_idx("using Operator", i) + helper.var_idx(" = typename Policy", i) + "::Operator;\n"
for i in range(self.b2b_num - 1):
code_using += helper.var_idx("using IteratorC", i) + helper.var_idx(" = typename FusedAddBiasEpilogue", i) + "::OutputTileIterator;\n"
code_using += "using ArchTag = typename Policy0::Operator::ArchTag;\n"
code_using += "static ComplexTransform const kTransformA0 = Operator0::kTransformA;\n"
for i in range(self.b2b_num):
code_using += helper.var_idx("static ComplexTransform const kTransformB", i) + helper.var_idx(" = Operator", i) + "::kTransformB;\n"
code_using += "private:\n"
code_using += "using WarpFragmentA0 = typename Operator0::FragmentA;\n"
code_using += "using WarpFragmentB0 = typename Operator0::FragmentB;\n"
for i in range(1, self.b2b_num):
code_using += helper.var_idx("using WarpFragmentA", i) + helper.var_idx(" = typename FragmentIteratorA", i) + "::Fragment;\n"
code_using += helper.var_idx("using WarpFragmentB", i) + helper.var_idx(" = typename Operator", i) + "::FragmentB;\n"
code_using += "protected:\n"
code_using += "SmemIteratorA0 smem_iterator_A_;\n"
for i in range(self.b2b_num):
code_using += helper.var_idx("SmemIteratorB", i) + helper.var_idx(" smem_iterator_B", i) + "_;\n"
return code_using
def gen_operator(self, first_use_1stage = False):
code = ""
def gen_operator_param(b2b_num):
param_code = ""
param_code += "int gemm_k_iterations_0,\n"
param_code += helper.var_idx("FragmentC", b2b_num-1) + helper.var_idx(" &accum", b2b_num-1) + ",\n"
param_code += "IteratorA0 iterator_A,\n"
for i in range(b2b_num):
param_code += helper.var_idx("IteratorB", i) + " " + helper.var_idx("iterator_B", i) + ",\n"
param_code += "FragmentC0 const &src_accum, \n"
for i in range(b2b_num - 1):
param_code += helper.var_idx("OutputOp", i) + " " + helper.var_idx("output_op_", i) + ",\n"
for i in range(b2b_num - 1):
param_code += helper.var_idx("FusedAddBiasEpilogue", i) + " " + helper.var_idx("epilogue_", i) + ",\n"
for i in range(b2b_num - 1):
param_code += helper.var_idx("IteratorC", i) + " " + helper.var_idx("iterator_C", i) + ",\n"
param_code += "TransformA0 transform_A0 = TransformA0(), \n"
for i in range(b2b_num):
final = "(),\n"
if i == b2b_num - 1:
final = "()\n"
param_code += helper.var_idx("TransformB", i) + " " + helper.var_idx("transform_B", i) + " = " +helper.var_idx("TransformB", i) + final
return param_code
def gen_first_gemm_1stage(b2b_num):
accu_code = " FragmentC0 accum0 = src_accum;\n"
if b2b_num == 1:
accu_code = " accum0 = src_accum;\n"
code ="\
\n\
FragmentA0 tb_frag_A;\n\
FragmentB0 tb_frag_B0;\n\
\n\
int smem_write_stage_idx = 1;\n\
\n\
tb_frag_A.clear();\n\
tb_frag_B0.clear();\n\
\n\
// The last kblock is loaded in the prolog\n\
iterator_A.load(tb_frag_A);\n\
iterator_B0.load(tb_frag_B0);\n\
\n\
++iterator_A;\n\
++iterator_B0;\n\
\n\
WarpFragmentA0 warp_frag_A0;\n\
WarpFragmentB0 warp_frag_B0;\n\
\n\
Operator0 warp_mma0;\n\
\n\
// Avoid reading out of bounds\n\
if (gemm_k_iterations_0 <= 1) {\n\
iterator_A.clear_mask();\n\
iterator_B0.clear_mask();\n\
}\n\
\n\
// Issue loads during the first warp-level matrix multiply-add *AFTER* issuing \n\
// shared memory loads (which have the tighest latency requirement).\n\
\n\
//\n\
// Mainloop\n\
//\n\
\n\
// Note: The main loop does not support Base::WarpGemmIterations == 2.\n\
CUTLASS_GEMM_LOOP\n\
for (; gemm_k_iterations_0 > 0; --gemm_k_iterations_0) {\n\
\n\
this->smem_iterator_A_.store(tb_frag_A);\n\
this->smem_iterator_B0_.store(tb_frag_B0);\n\
\n\
__syncthreads();\n\
//\n\
// Loop over GEMM K dimension\n\
//\n\
\n\
CUTLASS_PRAGMA_UNROLL\n\
for (int warp_mma_k = 0; warp_mma_k < Base::kWarpGemmIterations0; ++warp_mma_k) {\n\
\n\
// Load warp-level tiles from shared memory, wrapping to k offset if this is the last group\n\
// as the case may be.\n\
\n\
this->warp_tile_iterator_A0_.set_kgroup_index(warp_mma_k % Base::kWarpGemmIterations0);\n\
this->warp_tile_iterator_B0_.set_kgroup_index(warp_mma_k % Base::kWarpGemmIterations0);\n\
\n\
this->warp_tile_iterator_A0_.load(warp_frag_A0);\n\
this->warp_tile_iterator_B0_.load(warp_frag_B0);\n\
\n\
++this->warp_tile_iterator_A0_;\n\
++this->warp_tile_iterator_B0_;\n\
\n\
warp_mma0(accum0, warp_frag_A0, warp_frag_B0, accum0);\n\
}\n\
this->warp_tile_iterator_A0_.add_tile_offset({0, -Policy0::kPartitionsK * Base::kWarpGemmIterations0});\n\
this->warp_tile_iterator_B0_.add_tile_offset({-Policy0::kPartitionsK * Base::kWarpGemmIterations0, 0});\n\
\n\
__syncthreads();\n\
iterator_A.load(tb_frag_A);\n\
iterator_B0.load(tb_frag_B0);\n\
\n\
++iterator_A;\n\
++iterator_B0;\n\
\n\
if(gemm_k_iterations_0 <= 2) {\n\
iterator_A.clear_mask();\n\
iterator_B0.clear_mask();\n\
}\n\
}\n"
return accu_code + code
def gen_first_gemm_2stage(b2b_num):
accu_code = " FragmentC0 accum0 = src_accum;\n"
if b2b_num == 1:
accu_code = " accum0 = src_accum;\n"
code ="\
\n\
FragmentA0 tb_frag_A;\n\
FragmentB0 tb_frag_B0;\n\
\n\
tb_frag_A.clear();\n\
tb_frag_B0.clear();\n\
\n\
// The last kblock is loaded in the prolog\n\
iterator_A.load(tb_frag_A);\n\
iterator_B0.load(tb_frag_B0);\n\
\n\
++iterator_A;\n\
++iterator_B0;\n\
\n\
this->smem_iterator_A_.store(tb_frag_A);\n\
this->smem_iterator_B0_.store(tb_frag_B0);\n\
\n\
++this->smem_iterator_A_;\n\
++this->smem_iterator_B0_;\n\
\n\
__syncthreads();\n\
\n\
// Pair of fragments used to overlap shared memory loads and math instructions\n\
WarpFragmentA0 warp_frag_A0[2];\n\
WarpFragmentB0 warp_frag_B0[2];\n\
\n\
this->warp_tile_iterator_A0_.set_kgroup_index(0);\n\
this->warp_tile_iterator_B0_.set_kgroup_index(0);\n\
\n\
this->warp_tile_iterator_A0_.load(warp_frag_A0[0]);\n\
this->warp_tile_iterator_B0_.load(warp_frag_B0[0]);\n\
\n\
++this->warp_tile_iterator_A0_;\n\
++this->warp_tile_iterator_B0_;\n\
\n\
Operator0 warp_mma0;\n\
\n\
int smem_write_stage_idx = 1;\n\
\n\
// Avoid reading out of bounds\n\
if (gemm_k_iterations_0 <= 1) {\n\
iterator_A.clear_mask();\n\
iterator_B0.clear_mask();\n\
}\n\
\n\
// Issue loads during the first warp-level matrix multiply-add *AFTER* issuing \n\
// shared memory loads (which have the tighest latency requirement).\n\
iterator_A.load(tb_frag_A);\n\
\n\
//\n\
// Mainloop\n\
//\n\
\n\
// Note: The main loop does not support Base::WarpGemmIterations == 2.\n\
CUTLASS_GEMM_LOOP\n\
for (; gemm_k_iterations_0 > 0; --gemm_k_iterations_0) {\n\
\n\
//\n\
// Loop over GEMM K dimension\n\
//\n\
\n\
CUTLASS_PRAGMA_UNROLL\n\
for (int warp_mma_k = 0; warp_mma_k < Base::kWarpGemmIterations0; ++warp_mma_k) {\n\
\n\
// Load warp-level tiles from shared memory, wrapping to k offset if this is the last group\n\
// as the case may be.\n\
\n\
if (warp_mma_k == Base::kWarpGemmIterations0 - 1) {\n\
\n\
// Write fragments to shared memory\n\
this->smem_iterator_A_.store(tb_frag_A);\n\
\n\
this->smem_iterator_B0_.store(tb_frag_B0);\n\
\n\
__syncthreads();\n\
\n\
// Issue loads during the first warp-level matrix multiply-add *AFTER* issuing \n\
// shared memory loads (which have the tighest latency requirement).\n\
iterator_A.load(tb_frag_A);\n\
\n\
++this->smem_iterator_B0_;\n\
++this->smem_iterator_A_;\n\
\n\
\n\
// Add negative offsets to return iterators to the 'start' of the circular buffer in shared memory\n\
if (smem_write_stage_idx == 1) {\n\
this->smem_iterator_A_.add_tile_offset({0, -Base::Stage0});\n\
this->smem_iterator_B0_.add_tile_offset({-Base::Stage0, 0});\n\
}\n\
else {\n\
this->warp_tile_iterator_A0_.add_tile_offset(\n\
{0, -Base::Stage0 * Policy0::kPartitionsK * Base::kWarpGemmIterations0});\n\
this->warp_tile_iterator_B0_.add_tile_offset(\n\
{-Base::Stage0 * Policy0::kPartitionsK * Base::kWarpGemmIterations0,\n\
0});\n\
}\n\
\n\
smem_write_stage_idx ^= 1;\n\
}\n\
\n\
this->warp_tile_iterator_A0_.set_kgroup_index((warp_mma_k + 1) % Base::kWarpGemmIterations0);\n\
this->warp_tile_iterator_B0_.set_kgroup_index((warp_mma_k + 1) % Base::kWarpGemmIterations0);\n\
\n\
this->warp_tile_iterator_A0_.load(warp_frag_A0[(warp_mma_k + 1) % 2]);\n\
this->warp_tile_iterator_B0_.load(warp_frag_B0[(warp_mma_k + 1) % 2]);\n\
\n\
++this->warp_tile_iterator_A0_;\n\
++this->warp_tile_iterator_B0_;\n\
\n\
if (warp_mma_k == 0) {\n\
\n\
iterator_B0.load(tb_frag_B0);\n\
\n\
++iterator_A;\n\
++iterator_B0;\n\
\n\
// Avoid reading out of bounds if this was the last loop iteration\n\
if (gemm_k_iterations_0 <= 2) {\n\
iterator_A.clear_mask();\n\
iterator_B0.clear_mask();\n\
}\n\
}\n\
\n\
warp_mma0(accum0, warp_frag_A0[warp_mma_k % 2], warp_frag_B0[warp_mma_k % 2], accum0);\n\
}\n\
}\n"
return accu_code + code
def gen_other_gemms_2stage(b2b_num):
code = ""
def gemm_teamplate(id):
code = "// " + str(id + 1) + " Gemm"
code += " /// Iterator to load a warp-scoped tile of A1 operand from intermediate accumulator tile\n"
code += " " + helper.var_idx("FragmentC", id - 1) + helper.var_idx(" after_epilouge_accu", id - 1) + ";\n"
code += " " + helper.var_idx("epilogue_", id - 1) + helper.var_idx("(output_op_", id - 1) + helper.var_idx(", accum", id - 1) \
+ helper.var_idx(", after_epilouge_accu", id - 1) + helper.var_idx(", iterator_C", id - 1) +");\n"
# FragmentIteratorA1 warp_tile_iterator_A1_(accum0);
code += " " + helper.var_idx("FragmentIteratorA", id) + helper.var_idx(" warp_tile_iterator_A", id) +"_(" + helper.var_idx("after_epilouge_accu", id - 1) + ");\n"
# FragmentB1 tb_frag_B1;
code += " " + helper.var_idx("FragmentB", id) + " " + helper.var_idx("tb_frag_B", id) + ";\n"
# tb_frag_B1.clear();
code += " " + helper.var_idx("tb_frag_B", id) + ".clear();\n"
# iterator_B1.load(tb_frag_B1);
code += " " + helper.var_idx("iterator_B", id) + ".load(" + helper.var_idx("tb_frag_B", id) + ");\n"
# ++iterator_B1;
code += " " + "++" + helper.var_idx("iterator_B", id) + ";\n"
# this->smem_iterator_B1_.store(tb_frag_B1);
code += " " + helper.var_idx("this->smem_iterator_B", id) + "_.store(" + helper.var_idx("tb_frag_B", id) + ");\n"
# ++this->smem_iterator_B1_;
code += " " + helper.var_idx("++this->smem_iterator_B", id) + "_;\n"
# __syncthreads();
code += " " + "__syncthreads();\n"
# WarpFragmentA1 warp_frag_A1[2];
code += " " + helper.var_idx("WarpFragmentA", id) + helper.var_idx(" warp_frag_A", id) + "[2];\n"
# WarpFragmentB1 warp_frag_B1[2];
code += " " + helper.var_idx("WarpFragmentB", id) + helper.var_idx(" warp_frag_B", id) + "[2];\n"
# this->warp_tile_iterator_B1_.set_kgroup_index(0);
code += " " + helper.var_idx("this->warp_tile_iterator_B", id) + "_.set_kgroup_index(0);\n"
# warp_tile_iterator_A1_.load(warp_frag_A1[0], output_op_0);
code += " " + helper.var_idx("warp_tile_iterator_A", id) + helper.var_idx("_.load(warp_frag_A", id) + "[0]);\n"
# this->warp_tile_iterator_B1_.load(warp_frag_B1[0]);
code += " " + helper.var_idx("this->warp_tile_iterator_B", id) + helper.var_idx("_.load(warp_frag_B", id) + "[0]);\n"
# ++warp_tile_iterator_A1_;
code += " " + helper.var_idx("++warp_tile_iterator_A", id) + "_;\n"
# ++this->warp_tile_iterator_B1_;
code += " " + helper.var_idx("++this->warp_tile_iterator_B", id) + "_;\n"
# Operator1 warp_mma1;
code += " " + helper.var_idx("Operator", id) + " " + helper.var_idx("warp_mma", id) + ";\n"
# smem_write_stage_idx = 1;
code += " " + "smem_write_stage_idx = 1;\n"
# int gemm_k_iterations_1 = FragmentIteratorA1::Policy::kIterations / Base::kWarpGemmIterations1;
code += " " + helper.var_idx("int gemm_k_iterations_", id) + " = " + helper.var_idx("FragmentIteratorA", id) + helper.var_idx("::Policy::kIterations / Base::kWarpGemmIterations", id) +";\n"
# if (gemm_k_iterations_1 <= 1) {
# iterator_B1.clear_mask();
# }
code += " " + "if (" + helper.var_idx("gemm_k_iterations_", id) + " <= 1 ){\n" \
+ " " + " " + helper.var_idx("iterator_B", id) + ".clear_mask();\n" \
+ " " +"}\n"
# CUTLASS_PRAGMA_UNROLL
code += " " + "CUTLASS_PRAGMA_UNROLL\n"
# for (; gemm_k_iterations_1 > 0; --gemm_k_iterations_1) {
code += " " + helper.var_idx("for (; gemm_k_iterations_", id) + helper.var_idx(" > 0; --gemm_k_iterations_", id) + ") {\n"
# CUTLASS_PRAGMA_UNROLL
code += " " + " " + "CUTLASS_PRAGMA_UNROLL\n"
# for (int warp_mma_k = 0; warp_mma_k < Base::kWarpGemmIterations1; ++warp_mma_k) {
code += " " + " " + helper.var_idx("for (int warp_mma_k = 0; warp_mma_k < Base::kWarpGemmIterations", id) + "; ++warp_mma_k) {\n"
# if (warp_mma_k == Base::kWarpGemmIterations1 - 1) {
code += " " + " " + " " + helper.var_idx("if (warp_mma_k == Base::kWarpGemmIterations", id) + " - 1) {\n"
# this->smem_iterator_B1_.store(tb_frag_B1);
code += " " + " " + " " + " " + helper.var_idx(" this->smem_iterator_B", id) + helper.var_idx("_.store(tb_frag_B", id) + ");\n"
# __syncthreads();
code += " " + " " + " " + " " + "__syncthreads();\n"
# ++smem_iterator_B1_;
code += " " + " " + " " + " " + helper.var_idx(" ++smem_iterator_B", id) + "_;\n"
# if (smem_write_stage_idx == 1) {
# smem_iterator_B1_.add_tile_offset({-Base::Stage, 0});
# }
code += " " + " " + " " + " " + "if ( smem_write_stage_idx == 1 ) {\n" \
+ " " + " " + " " + " " + " " + helper.var_idx("smem_iterator_B", id) + helper.var_idx("_.add_tile_offset({-Base::Stage", i) + ", 0});\n" \
+ " " + " " + " " + " " +"}\n"
# else {
# this->warp_tile_iterator_B1_.add_tile_offset(
# {-Base::Stage * Policy1::kPartitionsK *
# Base::kWarpGemmIterations1,
# 0});
# }
code += " " + " " + " " + " " + "else {\n" \
+ " " + " " + " " + " " + " " + helper.var_idx("this->warp_tile_iterator_B", id) + "_.add_tile_offset(\n" \
+ " " + " " + " " + " " + " " + helper.var_idx("{-Base::Stage", id) + helper.var_idx(" * Policy", id) + "::kPartitionsK *\n" \
+ " " + " " + " " + " " + " " + helper.var_idx("Base::kWarpGemmIterations", id) + ",\n" \
+ " " + " " + " " + " " + " " + "0});\n" \
+ " " + " " + " " + " " + "}\n"
# smem_write_stage_idx ^= 1;
# }
code += " " + " " + " " + " " + "smem_write_stage_idx ^= 1;\n" \
+ " " + " " + " " + "}\n"
# this->warp_tile_iterator_B1_.set_kgroup_index((warp_mma_k + 1) % Base::kWarpGemmIterations1);
code += " " + " " + " " + helper.var_idx("this->warp_tile_iterator_B", id) + helper.var_idx("_.set_kgroup_index((warp_mma_k + 1) % Base::kWarpGemmIterations", id) + ");\n"
# warp_tile_iterator_A1_.load(warp_frag_A1[(warp_mma_k + 1) % 2], output_op_0);
code += " " + " " + " " + helper.var_idx("warp_tile_iterator_A", id) + helper.var_idx("_.load(warp_frag_A", id) + "[(warp_mma_k + 1) % 2]);\n"
# this->warp_tile_iterator_B1_.load(warp_frag_B1[(warp_mma_k + 1) % 2]);
code += " " + " " + " " + helper.var_idx("this->warp_tile_iterator_B", id) + helper.var_idx("_.load(warp_frag_B", id) + "[(warp_mma_k + 1) % 2]);\n"
# ++warp_tile_iterator_A1_;
code += " " + " " + " " + helper.var_idx("++warp_tile_iterator_A", id) + "_;\n"
# ++this->warp_tile_iterator_B1_;
code += " " + " " + " " + helper.var_idx("++this->warp_tile_iterator_B", id) + "_;\n"
# if (warp_mma_k == 0) {
# iterator_B1.load(tb_frag_B1);
# ++iterator_B1;
# if (gemm_k_iterations_1 <= 2) {
# iterator_B1.clear_mask();
# }
# }
code += " " + " " + " " + " if (warp_mma_k == 0) {\n" \
+ " " + " " + " " + " " + helper.var_idx("iterator_B", id) + helper.var_idx(".load(tb_frag_B", id) + ");\n" \
+ " " + " " + " " + " " + helper.var_idx("++iterator_B", id) +";\n" \
+ " " + " " + " " + " " + helper.var_idx("if (gemm_k_iterations_", id) +" <= 2) {\n" \
+ " " + " " + " " + " " + " " + helper.var_idx("iterator_B", id) + ".clear_mask();\n" \
+ " " + " " + " " + " " + "}\n" \
+ " " + " " + " " + "}\n"
# warp_mma1(accum, warp_frag_A1[warp_mma_k % 2], warp_frag_B1[warp_mma_k % 2], accum);
# }
# }
code += " " + " " + " " + helper.var_idx("warp_mma", id) + helper.var_idx("(accum", id) + helper.var_idx(", warp_frag_A", id) + helper.var_idx("[warp_mma_k % 2], warp_frag_B", id) + helper.var_idx("[warp_mma_k % 2], accum", id) + ");\n" \
+ " " + " " + "}\n" \
+ " " + "}\n\n\n"
return code
for i in range (1, b2b_num):
clear_accu = ""
if i != b2b_num - 1:
clear_accu = " " + helper.var_idx("FragmentC", i) + helper.var_idx(" accum", i) +";\n"
clear_accu += " " + helper.var_idx("accum", i) +".clear();\n"
code += clear_accu + gemm_teamplate(i)
return code
operator_code = " CUTLASS_DEVICE\n\
void operator()(\n " + gen_operator_param(self.b2b_num) + ") {\n"
if first_use_1stage:
operator_code += gen_first_gemm_1stage(self.b2b_num)
else:
operator_code += gen_first_gemm_2stage(self.b2b_num)
operator_code += gen_other_gemms_2stage(self.b2b_num) + "}\n"
return operator_code
def gen_construct_func(self):
name = self.gen_class_name
func_code = "CUTLASS_DEVICE\n"
func_code += name + "(\n" \
+ " " + "typename Base::B2bMmaSharedStorage &shared_storage,\n" \
+ " " + "int thread_idx,\n" \
+ " " + "int warp_idx,\n" \
+ " " + "int lane_idx\n" \
+ "):\n"
func_code += " " + "Base(shared_storage, thread_idx, warp_idx, lane_idx),\n" \
+ " " + "smem_iterator_A_(shared_storage.sharedStorage0.operand_A_ref(), thread_idx),\n"
for i in range(self.b2b_num):
final = ",\n"
if i == self.b2b_num - 1:
final = " {\n"
func_code += helper.var_idx("smem_iterator_B", i) + helper.var_idx("_(shared_storage.sharedStorage", i) +".operand_B_ref(), thread_idx)" + final
func_code += " " + "int warp_idx_mn = warp_idx % (Base::WarpCount0::kM * Base::WarpCount0::kN);\n"
func_code += " " + "int warp_idx_k = warp_idx / (Base::WarpCount0::kM * Base::WarpCount0::kN);\n"
func_code += " " + "int warp_idx_m = warp_idx_mn % Base::WarpCount0::kM;\n"
func_code += " " + "int warp_idx_n = warp_idx_mn / Base::WarpCount0::kM;\n"
for i in range(self.b2b_num):
func_code += " " + helper.var_idx("int tile_offset_k", i) + helper.var_idx(" = Base::kWarpGemmIterations", i) + " * warp_idx_k;\n"
func_code += " " + "this->warp_tile_iterator_A0_.add_tile_offset({warp_idx_m, tile_offset_k0});\n"
for i in range(self.b2b_num):
func_code += " " + helper.var_idx("this->warp_tile_iterator_B", i) + helper.var_idx("_.add_tile_offset({tile_offset_k", i) + ", warp_idx_n});\n"
func_code += "}\n"
return func_code
def gen_member_func(self, first_use_1stage):
code = "public:\n"
code += self.gen_operator(first_use_1stage)
code += self.gen_construct_func()
return code
def gen_code(self, first_use_1stage):
def gen_template_args(b2b_num):
template_param = []
template_param.append(("typename", "Shape0"))
template_param.append(("typename", "IteratorA0"))
template_param.append(("typename", "SmemIteratorA0"))
template_param.append(("typename", "IteratorB0"))
template_param.append(("typename", "SmemIteratorB0"))
for i in range(1, b2b_num):
template_param.append(("typename", helper.var_idx("Shape", i)))
template_param.append(("typename", helper.var_idx("FragmentIteratorA", i)))
template_param.append(("typename", helper.var_idx("IteratorB", i)))
template_param.append(("typename", helper.var_idx("SmemIteratorB", i)))
template_param.append(("typename", "ElementC"))
template_param.append(("typename", "LayoutC"))
for i in range(0, b2b_num - 1):
template_param.append(("typename", helper.var_idx("OutputOp", i)))
for i in range(0, b2b_num - 1):
template_param.append(("typename", helper.var_idx("FusedAddBiasEpilogue", i)))
for i in range(0, b2b_num):
template_param.append(("typename", helper.var_idx("Policy", i)))
for i in range(0, b2b_num):
template_param.append((int, helper.var_idx("Stage", i)))
template_param.append(("typename","TransformA0", "NumericArrayConverter<typename SmemIteratorA0_::Element, typename IteratorA0_::Element, IteratorA0_::Fragment::kElements>"))
for i in range(0, b2b_num):
cvtr = helper.var_idx("NumericArrayConverter<typename SmemIteratorB", i) + helper.var_idx("_::Element, typename IteratorB", i) + helper.var_idx("_::Element, IteratorB", i) + "_::Fragment::kElements>"
template_param.append(("typename", helper.var_idx("TransformB", i), cvtr))
template_param.append(("typename", "Enable", "bool"))
return template_param
template_param = gen_template_args(self.b2b_num)
inheritance_code = "public B2bMmaBase<"
for i in range(self.b2b_num):
inheritance_code += helper.var_idx("Shape", i) + "_, "
for i in range(self.b2b_num):
inheritance_code += helper.var_idx("Policy", i) + "_, "
for i in range(self.b2b_num - 1):
inheritance_code += helper.var_idx("Stage", i) + "_, "
inheritance_code += helper.var_idx("Stage", self.b2b_num - 1) + "_"
inheritance_code += ">"
code_body = ""
using_code= self.gen_using()
func_code = self.gen_member_func(first_use_1stage)
code_body = using_code + func_code
class_code = gen_ir.gen_template_class(self.gen_class_name, template_param, code_body, inheritance_code = inheritance_code)
code = self.gen_include_header()
code += gen_ir.gen_namespace("cutlass", gen_ir.gen_namespace("gemm", gen_ir.gen_namespace("threadblock", class_code)))
# print(code)
return code
class gen_b2b_mma_base:
def __init__(self, template_param, gen_class_name, b2b_num, cutlass_deps_root, project_root):
self.gen_class_name = gen_class_name
self.template_param = template_param
self.b2b_num = b2b_num
self.cutlass_deps_root = cutlass_deps_root
self.project_root = project_root
def gen_include_header(self):
code = '''
#pragma once
#include \"{cutlass_dirs}cutlass/aligned_buffer.h\"
#include \"{cutlass_dirs}cutlass/arch/memory.h\"
#include \"{cutlass_dirs}cutlass/array.h\"
#include \"{cutlass_dirs}cutlass/cutlass.h\"
#include \"{cutlass_dirs}cutlass/gemm/gemm.h\"
#include \"{cutlass_dirs}cutlass/matrix_shape.h\"
#include \"{cutlass_dirs}cutlass/numeric_types.h\"\n'''.format(cutlass_dirs=self.cutlass_deps_root)
return code
def gen_shared_storage(self):
code = \
" template< \n\
typename Shape_,\n\
typename Policy_,\n\
int ThisStage_\n\
>\n\
class SharedStorage {\n\
public:\n\
using Shape = Shape_;\n\
using Policy = Policy_;\n\
static int const ThisStage = ThisStage_;\n\
using Operator = typename Policy::Operator;\n\
\
using TensorRefA = TensorRef<typename Operator::ElementA, typename Operator::LayoutA>;\n\
\
/// Tensor reference to the B operand \n\
using TensorRefB = TensorRef<typename Operator::ElementB, typename Operator::LayoutB>;\n\
\n\
/// Shape of the A matrix operand in shared memory \n\
using ShapeA = MatrixShape<Shape::kM + Policy::SmemPaddingA::kRow,\n\
Shape::kK * ThisStage +\n\
Policy::SmemPaddingA::kColumn>;\n\
\n\
/// Shape of the B matrix operand in shared memory\n\
using ShapeB =\n\
MatrixShape<Shape::kK * ThisStage + Policy::SmemPaddingB::kRow,\n\
Shape::kN + Policy::SmemPaddingB::kColumn>;\n\
\n\
public:\n\
\n\
/// Buffer for A operand\n\
AlignedBuffer<typename Operator::ElementA, ShapeA::kCount> operand_A;\n\
\n\
/// Buffer for B operand\n\
AlignedBuffer<typename Operator::ElementB, ShapeB::kCount> operand_B;\n\
\n\
public:\n\
\n\
/// Returns a layout object for the A matrix\n\
CUTLASS_DEVICE\n\
static typename Operator::LayoutA LayoutA() {\n\
return Operator::LayoutA::packed({ShapeA::kRow, ShapeA::kColumn});\n\
}\n\
\n\
/// Returns a layout object for the B matrix\n\
CUTLASS_HOST_DEVICE\n\
static typename Operator::LayoutB LayoutB() {\n\
return Operator::LayoutB::packed({ShapeB::kRow, ShapeB::kColumn});\n\
}\n\
\n\
/// Returns a TensorRef to the A operand\n\
CUTLASS_HOST_DEVICE\n\
TensorRefA operand_A_ref() {\n\
return TensorRefA{operand_A.data(), LayoutA()};\n\
}\n\
\n\
/// Returns a TensorRef to the B operand\n\
CUTLASS_HOST_DEVICE\n\
TensorRefB operand_B_ref() {\n\
return TensorRefB{operand_B.data(), LayoutB()};\n\
}\n\
CUTLASS_HOST_DEVICE\n\
void * get_B_Shared_ptr() {\n\
return operand_B.data();\n\
}\n\
};\n"
return code
def gen_using_and_misc(self, b2b_num):
code_using = ""
for i in range(b2b_num):
code_using += "using Operator" +str(i) + " = typename Policy" + str(i) +"::Operator;\n"
for i in range(b2b_num):
code_using += "using WarpGemm" +str(i) + " = typename Policy" + str(i) +"::Operator::Shape;\n"
for i in range(b2b_num):
code_using += "using WarpCount" +str(i) + " = GemmShape<" + helper.var_idx("Shape", i) +"::kM / " + helper.var_idx("WarpGemm", i) +"::kM, "\
+ helper.var_idx("Shape", i) +"::kN / " + helper.var_idx("WarpGemm", i) +"::kN, "\
+ helper.var_idx("Shape", i) +"::kK / " + helper.var_idx("WarpGemm", i) +"::kK>;\n"
code_misc = ""
for i in range(b2b_num):
code_misc += "static int const " + helper.var_idx("kWarpGemmIterations", i) + " = (" + helper.var_idx("WarpGemm", i) + "::kK / " + helper.var_idx("Operator", i) +"::Policy::MmaShape::kK);\n"
code = code_using + code_misc + self.gen_shared_storage()
for i in range(b2b_num):
code += "using " + helper.var_idx("SharedStorage", i) + " = SharedStorage<" + helper.var_idx("Shape", i) + ", " + helper.var_idx("Policy", i) +", " + helper.var_idx("Stage", i) + ">;\n"
def gen_union_shared_storage(b2b_num):
code = ""
for i in range(b2b_num):
code += " " +helper.var_idx("SharedStorage", i) + " " + helper.var_idx("sharedStorage", i) +";\n"
return code
code += "union B2bMmaSharedStorage {\n" + gen_union_shared_storage(self.b2b_num) + "};\n"
for i in range(b2b_num - 1):
code += helper.var_idx("void * C", i) + "_smm_ptr;\n"
return code
def gen_protected(self):
code = "\nprotected:\n"
code += "typename Operator0::IteratorA warp_tile_iterator_A0_;\n"
for i in range(self.b2b_num):
code += "typename Operator" +str(i) + "::IteratorB" +" warp_tile_iterator_B" + str(i) + "_;\n"
return code
def gen_public_member(self):
code = "\npublic:\n"
code += "CUTLASS_DEVICE\n"
code += \
"B2bMmaBase(\n" + \
" B2bMmaSharedStorage & shared_storage,\n" + \
" int thread_idx,\n" + \
" int warp_idx,\n" + \
" int lane_idx\n" + \
"):\n" + \
" warp_tile_iterator_A0_(shared_storage.sharedStorage0.operand_A_ref(), lane_idx),\n"
for i in range(self.b2b_num):
final = ",\n"
if i == self.b2b_num-1:
final = "\n"
iterator = " warp_tile_iterator_B" + str(i) + "_"
shared_storage = "shared_storage.sharedStorage" + str(i) + ".operand_B_ref()"
code += iterator + "(" + shared_storage + ", lane_idx)" + final
code += "{\n"
for i in range(self.b2b_num - 1):
code += helper.var_idx(" C", i) + helper.var_idx("_smm_ptr = shared_storage.sharedStorage", i) + ".get_B_Shared_ptr();\n"
code += "}\n"
return code
def gen_code(self):
tempalte_arg = []
for i in range(self.b2b_num):
tempalte_arg.append(("typename", helper.var_idx("Shape", i)))
for i in range(self.b2b_num):
tempalte_arg.append(("typename", helper.var_idx("Policy", i)))
for i in range(self.b2b_num):
tempalte_arg.append((int, helper.var_idx("Stage", i)))
code_body = self.gen_using_and_misc(self.b2b_num)
code_body += self.gen_protected()
code_body += self.gen_public_member()
class_code = gen_ir.gen_template_class("B2bMmaBase", tempalte_arg, code_body)
code = self.gen_include_header() + gen_ir.gen_namespace("cutlass", gen_ir.gen_namespace("gemm", gen_ir.gen_namespace("threadblock", class_code)))
return code
class gen_threadblock:
def __init__(self, template_param, gen_class_name, b2b_num, output_dir, cutlass_deps_root, project_root):
self.gen_class_name = gen_class_name
self.template_param = template_param
self.b2b_num = b2b_num
self.file_dir = output_dir + "/threadblock/"
self.cutlass_deps_root = cutlass_deps_root
self.project_root = project_root
self.gen_b2b_mma_base = gen_b2b_mma_base(template_param, gen_class_name, b2b_num, cutlass_deps_root, project_root)
self.gen_b2b_mma_piplined = gen_b2b_mme_pipelined(template_param, gen_class_name, b2b_num, cutlass_deps_root, project_root)
self.gen_default_b2b_mma = gen_default_b2b_mma(template_param, gen_class_name, b2b_num, cutlass_deps_root, project_root)
def gen_code(self, first_use_1stage):
base_code = self.gen_b2b_mma_base.gen_code()
print("[INFO]: Gen kernel code [b2b_mma_base.h]output Dir: is ", self.file_dir)
with open(self.file_dir + "b2b_mma_base.h", "w+") as f:
f.write(base_code)
pipeline_code = self.gen_b2b_mma_piplined.gen_code(first_use_1stage = first_use_1stage)
print("[INFO]: Gen kernel code [b2b_mma_pipelined.h]output Dir: is ", self.file_dir)
with open(self.file_dir + "b2b_mma_pipelined.h", "w+") as f:
f.write(pipeline_code)
default_code = self.gen_default_b2b_mma.gen_code()
print("[INFO]: Gen kernel code [default_b2b_mma.h]output Dir: is ", self.file_dir)
with open(self.file_dir + "default_b2b_mma.h", "w+") as f:
f.write(default_code)
| warp-main | warp/native/cutlass/examples/44_multi_gemm_ir_and_codegen/ir_gen/gen_threadblock.py |
#################################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#################################################################################################
import ast
fuse_gemm_info = [
{
'epilogue': {
'tp': 'LeakyRelu', #'CustomizedLeaky_RELU'
'bias': {'addbias': False, 'bias_tp': 'mat'},
'args': [('float', 'leaky_alpha', 1.3), ],
'func': '''
y = max(leaky_alpha * x, x)
y = y * x
'''
}
},
]
class AnalysisNodeVisitor(ast.NodeVisitor):
def visit_Import(self,node):
ast.NodeVisitor.generic_visit(self, node)
def visit_ImportFrom(self,node):
ast.NodeVisitor.generic_visit(self, node)
def visit_Assign(self,node):
print('Node type: Assign and fields: ', node._fields)
# print('Node type: Assign and targets value: ', node.targets, node.value)
ast.NodeVisitor.generic_visit(self, node)
def visit_BinOp(self, node):
print('Node type: BinOp and fields: ', node._fields)
print('node op: ', type(node.op).__name__)
ast.NodeVisitor.generic_visit(self, node)
def visit_Expr(self, node):
print('Node type: Expr and fields: ', node._fields)
ast.NodeVisitor.generic_visit(self, node)
def visit_Num(self,node):
print('Node type: Num and fields: ', node._fields)
print('Node type: Num: ', node.n)
def visit_Name(self,node):
print('Node type: Name and fields: ', node._fields)
print('Node type: Name and fields: ', type(node.ctx).__name__, node.id)
ast.NodeVisitor.generic_visit(self, node)
def visit_Str(self, node):
print('Node type: Str and fields: ', node._fields)
class CodeVisitor(ast.NodeVisitor):
def visit_BinOp(self, node):
if isinstance(node.op, ast.Add):
node.op = ast.Sub()
self.generic_visit(node)
def visit_Assign(self, node):
print('Assign %s' % node.value)
self.generic_visit(node)
def visit_Name(self, node):
print("Name:", node.id)
self.generic_visit(node)
def visit_FunctionDef(self, node):
print('Function Name:%s'% node.name.op)
self.generic_visit(node)
func_log_stmt = ast.Print(
dest = None,
values = [ast.Str(s = 'calling func: %s' % node.name, lineno = 0, col_offset = 0)],
nl = True,
lineno = 0,
col_offset = 0,
)
node.body.insert(0, func_log_stmt)
visitor = AnalysisNodeVisitor()
code = \
'''
a=max(leaky_alpha * x, x +1)
'''
visitor.visit(ast.parse(code))
| warp-main | warp/native/cutlass/examples/44_multi_gemm_ir_and_codegen/ir_gen/gen_customized_epilogue.py |
#################################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#################################################################################################
class gen_build_sys:
def __init__(self, cutlass_deps_dir, output_dir = "../"):
self.output_dir = output_dir
self.cutlass_deps_dir = cutlass_deps_dir
def gen_top(self):
code = ""
code += '''\
# Auto Generated code - Do not edit.
cmake_minimum_required(VERSION 3.8)
project(CUTLASS_MULTI_GEMMS LANGUAGES CXX CUDA)
find_package(CUDAToolkit)
set(CUDA_PATH ${{CUDA_TOOLKIT_ROOT_DIR}})
set(CUTLASS_PATH \"{cutlass_deps_dir}/include\")
set(CUTLASS_UTIL_PATH \"{cutlass_deps_dir}/tools/util/include\")
list(APPEND CMAKE_MODULE_PATH ${{CUDAToolkit_LIBRARY_DIR}})
'''.format(cutlass_deps_dir=self.cutlass_deps_dir)
code += '''\
set(GPU_ARCHS \"\" CACHE STRING
\"List of GPU architectures (semicolon-separated) to be compiled for.\")
if(\"${GPU_ARCHS}\" STREQUAL \"\")
set(GPU_ARCHS \"70\")
endif()
foreach(arch ${GPU_ARCHS})
set(CMAKE_CUDA_FLAGS \"${CMAKE_CUDA_FLAGS} -gencode arch=compute_${arch},code=sm_${arch}\")
if(SM STREQUAL 70 OR SM STREQUAL 75)
set(CMAKE_C_FLAGS \"${CMAKE_C_FLAGS} -DWMMA\")
set(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -DWMMA\")
set(CMAKE_CUDA_FLAGS \"${CMAKE_CUDA_FLAGS} -DWMMA\")
endif()
endforeach()
set(CMAKE_C_FLAGS \"${CMAKE_C_FLAGS}\")
set(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS}\")
set(CMAKE_CUDA_FLAGS \"${CMAKE_CUDA_FLAGS} -Xcompiler -Wall\")
set(CMAKE_C_FLAGS_DEBUG \"${CMAKE_C_FLAGS_DEBUG} -Wall -O0\")
set(CMAKE_CXX_FLAGS_DEBUG \"${CMAKE_CXX_FLAGS_DEBUG} -Wall -O0\")
set(CMAKE_CUDA_FLAGS_DEBUG \"${CMAKE_CUDA_FLAGS_DEBUG} -O0 -G -Xcompiler -Wall\")
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
if(CMAKE_CXX_STANDARD STREQUAL \"11\")
set(CMAKE_CUDA_FLAGS \"${CMAKE_CUDA_FLAGS} --expt-extended-lambda\")
set(CMAKE_CUDA_FLAGS \"${CMAKE_CUDA_FLAGS} --expt-relaxed-constexpr\")
endif()
set(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -g -O3\")
set(CMAKE_CUDA_FLAGS \"${CMAKE_CUDA_FLAGS} -Xcompiler -O3\")
set(CMAKE_CUDA_FLAGS \"${CMAKE_CUDA_FLAGS} -Xcompiler=-fno-strict-aliasing\")
set(COMMON_HEADER_DIRS
${PROJECT_SOURCE_DIR}
${CUDAToolkit_INCLUDE_DIRS}
)
set(COMMON_LIB_DIRS
${CUDAToolkit_LIBRARY_DIR}
)
list(APPEND COMMON_HEADER_DIRS ${CUTLASS_PATH})
list(APPEND COMMON_HEADER_DIRS ${CUTLASS_UTIL_PATH})
'''
code += '''\
include_directories(
${COMMON_HEADER_DIRS}
)
link_directories(
${COMMON_LIB_DIRS}
)
add_definitions(-D_GLIBCXX_USE_CXX11_ABI=0)
add_definitions(-DGOOGLE_CUDA=1)
add_executable(sample
sample/sample.cu
one_api.cu
)
target_link_libraries(sample PRIVATE
-lcudart
-lnvToolsExt
${CMAKE_THREAD_LIBS_INIT}
)
if(NOT DEFINED LIB_INSTALL_PATH)
set(LIB_INSTALL_PATH ${CMAKE_CURRENT_BINARY_DIR})
endif()
'''
return code
def gen_code(self):
top_code = self.gen_top()
with open(self.output_dir + "CMakeLists.txt", "w") as f:
f.write(top_code)
| warp-main | warp/native/cutlass/examples/44_multi_gemm_ir_and_codegen/ir_gen/gen_cmake.py |
#################################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#################################################################################################
import helper
import gen_ir as ir
import gen_turing_and_volta as gen_basic
class gen_verify:
def __init__(self, fuse_gemm_info, gen_class_name, user_header_file, output_dir = "../"):
self.fuse_gemm_info = fuse_gemm_info
self.name = gen_class_name + "_verify"
self.b2b_num = len(fuse_gemm_info)
self.params = []
self.user_header_file = ""
for header in user_header_file:
self.user_header_file += "#include \"" + header + "\"\n"
self.seperate_cutlass = gen_basic.gen_volta_turing_fuse_act_impl(fuse_gemm_info, gen_class_name, user_header_file, output_dir)
self.gen_params()
self.output_dir = output_dir
def gen_code(self):
code = ""
code += self.user_header_file
code += self.seperate_cutlass.gen_using(False) #False -> Turing, True -> Volta
code_body = ""
for i in range(self.b2b_num):
code_body += " " + helper.var_idx("Gemm", i) + helper.var_idx(" gemm_op_", i) + ";\n"
code_body += " " + helper.var_idx("gemm_op_", i) + helper.var_idx(".initialize(Arguments_", i) + ", nullptr);\n"
code_body += self.seperate_cutlass.gen_run()
code += ir.gen_func(self.name, self.params, code_body)
helper.write_2_headfile("cutlass_verify.h", self.output_dir, code)
def gen_params(self):
for i in range(self.b2b_num):
self.params.append(
(
helper.var_idx("typename Gemm", i)+ "::Arguments",
helper.var_idx("Arguments_", i)
)
)
def get_params(self, declartion = True):
code = ""
if declartion:
for param in self.params:
code += param[0] + " " + param[1] + ";\n"
return code
def gen_initialize():
code = ""
initialize_code = self.seperate_cutlass.gen_initialize()
code = ir.gen_func("initialize", [[]])
| warp-main | warp/native/cutlass/examples/44_multi_gemm_ir_and_codegen/ir_gen/gen_verify.py |
#################################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#################################################################################################
def type_2_cutlass_type(input_type = "fp16"):
# float point type
if input_type == "fp32":
return "float"
if input_type == "bf16":
return "cutlass::bfloat16_t"
if input_type == "fp16":
return "cutlass::half_t"
# integer type
if(input_type == "int32"):
return "int32_t"
if(input_type == "int8"):
return "int8_t"
if input_type == 'Row':
return 'cutlass::layout::RowMajor'
if input_type == 'Col':
return 'cutlass::layout::ColumnMajor'
def cvt_2_cutlass_shape(gemm_shape):
# gemm shape
if len(gemm_shape) == 3:
val = "cutlass::gemm::GemmShape<" \
+ str(gemm_shape[0]) + ", " \
+ str(gemm_shape[1]) + ", " \
+ str(gemm_shape[2]) + ">"
return val
def write_2_headfile(filename, file_dir, string):
with open(file_dir + filename, 'w') as f:
f.write("/* Auto Generated code - Do not edit.*/\n\n\n#pragma once\n" + string)
def var_idx(varaiable, index):
return varaiable + str(index)
def list_2_string(input_list, ):
rtn_string = ""
cnt = 0
for element in input_list:
final = ", \n"
if cnt == len(input_list) - 1:
final = "\n"
cnt += 1
rtn_string += str(element) + final
return rtn_string
def get_epilouge_info(layer_info):
return layer_info['epilogue']
def get_epilogue_tp(layer_info):
epilogue_info = get_epilouge_info(layer_info)
return epilogue_info['tp']
def get_epilogue_add_bias_or_not(layer_info):
epilogue_info = get_epilouge_info(layer_info)
return epilogue_info['bias']['addbias']
def get_epilogue_add_bias_tp(layer_info):
epilogue_info = get_epilouge_info(layer_info)
return epilogue_info['bias']['bias_tp']
def get_epilogue_args(layer_info):
epilogue_info = get_epilouge_info(layer_info)
return epilogue_info['args']
def get_epilogue_bias_shape(layer_info):
bias_tp = get_epilogue_add_bias_tp(layer_info).lower()
mn_shape = layer_info['mnk'][:-1]
if bias_tp == 'mat':
mn_shape[0] = 'M'
return mn_shape
elif bias_tp == 'vec':
mn_shape[0] = 1
return mn_shape
else:
assert(0)
def get_epilogue_bias_ldm(layer_info):
bias_tp = get_epilogue_add_bias_tp(layer_info).lower()
mn_shape = layer_info['mnk'][:-1]
c_layout = layer_info['C_format'].lower()
if c_layout != 'row':
assert(0)
if bias_tp == 'mat':
return mn_shape[1]
elif bias_tp == 'vec':
return 0
else:
assert(0)
def get_epilogue_compute_tp(layer_info):
return layer_info['Acc_tp']
| warp-main | warp/native/cutlass/examples/44_multi_gemm_ir_and_codegen/ir_gen/helper.py |
#################################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#################################################################################################
import helper
import gen_ir as ir
class gen_turing_impl:
def __init__(self,fuse_gemm_info, gen_class_name, user_header_file, output_dir = "../"):
self.fuse_gemm_info = fuse_gemm_info
self.class_name = gen_class_name
self.gen_class_name = gen_class_name + "_turing_impl"
self.user_header_file = ""
for header in user_header_file:
self.user_header_file += "#include \"" + header + "\"\n"
self.output_dir = output_dir
self.b2b_num = len(fuse_gemm_info)
self.gen_turing_unfused = gen_volta_turing_fuse_act_impl(fuse_gemm_info, gen_class_name, user_header_file, output_dir)
def gen_using(self):
code_using = "using b2b_gemm = typename cutlass::gemm::device::" + self.class_name + "<cutlass::half_t>;"
return code_using + "\n"
def gen_initialize(self):
code = ""
for i in range(self.b2b_num):
code_this = ""
code_this += helper.var_idx(helper.type_2_cutlass_type(self.fuse_gemm_info[i]['Acc_tp']) + " alpha", i) + " = " + helper.type_2_cutlass_type(self.fuse_gemm_info[i]['Acc_tp']) + "(1);\n"
beta = "(1)"
if helper.get_epilogue_add_bias_or_not(self.fuse_gemm_info[i]) is False:
beta = "(0)"
code_this += helper.var_idx(helper.type_2_cutlass_type(self.fuse_gemm_info[i]['Acc_tp']) + " beta", i) + " = " + helper.type_2_cutlass_type(self.fuse_gemm_info[i]['Acc_tp']) + beta + ";\n"
k_str = str(self.fuse_gemm_info[i]['mnk'][2])
if i == 0:
k_str = "K0"
code_this += helper.var_idx("cutlass::gemm::GemmCoord problem_size_", i) + "(M, " + str(self.fuse_gemm_info[i]['mnk'][1]) + ", " + k_str + ");\n"
code += code_this
code += "typename b2b_gemm::Arguments arguments{\n"
for i in range(self.b2b_num):
code += " " + helper.var_idx("problem_size_", i) + ",\n"
code += " " + "{reinterpret_cast<" + helper.type_2_cutlass_type(self.fuse_gemm_info[i]['A_tp']) + "*>(" + helper.var_idx("A", 0) + "), " + helper.var_idx("problem_size_", 0) + ".k()},\n"
for i in range(self.b2b_num):
ldmB = str(self.fuse_gemm_info[i]['mnk'][2])
if i == 0:
ldmB = "K0"
if self.fuse_gemm_info[i]['B_format'] is 'Row':
ldmB = str(self.fuse_gemm_info[i]['mnk'][1])
ldmC = str(helper.get_epilogue_bias_ldm(self.fuse_gemm_info[i]))
code += " " + "{reinterpret_cast<" + helper.type_2_cutlass_type(self.fuse_gemm_info[i]['B_tp']) + "*>(" + helper.var_idx("B", i) + "), " + ldmB + "},\n"
code += " " + "{reinterpret_cast<" + helper.type_2_cutlass_type(self.fuse_gemm_info[i]['C_tp']) + "*>(" + helper.var_idx("C", i) + "), " + ldmC + "},\n"
code += " " + "{reinterpret_cast<" + helper.type_2_cutlass_type(self.fuse_gemm_info[i]['C_tp']) + "*>(" + helper.var_idx("D", self.b2b_num -1) + "), " + helper.var_idx("problem_size_", self.b2b_num - 1) + ".n()},\n"
for i in range(self.b2b_num):
code += " " + "{ " + helper.var_idx("alpha", i) + ", " + helper.var_idx("beta", i)
for epilogue_arg in helper.get_epilogue_args(self.fuse_gemm_info[i]):
arg_name = helper.var_idx("Epilogue", i) + "_" + epilogue_arg[1]
code += ", " + helper.type_2_cutlass_type(self.fuse_gemm_info[i]['Acc_tp']) + "(" + str(arg_name) + ")"
code += "},\n"
code += " " + "Batch};\n\n"
code += " " "b2b_gemm gemm_op;\n"
code += " " + "gemm_op.initialize(arguments);\n"
return code + "\n"
def gen_run(self):
code = " " + "gemm_op(stream);\n"
return code
def gen_wrapper(self):
code_body = ""
arg_lists = []
arg_lists.append(["int", "M"])
arg_lists.append(["int", "K0"])
arg_lists.append(["int", "Batch"])
arg_lists.append(["void*", helper.var_idx("A", 0)])
for i in range(self.b2b_num):
arg_lists.append(["void*", helper.var_idx("B", i)])
arg_lists.append(["void*", helper.var_idx("C", i)])
arg_lists.append(["void*", helper.var_idx("D", i)])
epilogue_args = helper.get_epilogue_args(self.fuse_gemm_info[i])
acc_tp = helper.get_epilogue_compute_tp(self.fuse_gemm_info[i])
for arg in epilogue_args:
arg_tp = arg[0]
arg_name = helper.var_idx("Epilogue", i) + "_" + arg[1]
arg_lists.append([arg_tp, arg_name])
if self.b2b_num == 1:
code_body += self.gen_turing_unfused.gen_using(False) #False -> Turing, True -> Volta
code_body += self.gen_turing_unfused.gen_initialize()
code_body += self.gen_turing_unfused.gen_run()
else:
code_body += self.gen_using()
code_body += self.gen_initialize()
code_body += self.gen_run()
code = ir.gen_func(self.gen_class_name, arg_lists, code_body)
return code
def gen_code(self):
code = self.gen_wrapper()
helper.write_2_headfile("turing_impl.h", self.output_dir, self.user_header_file + "\n" + code)
class gen_volta_turing_fuse_act_impl:
def __init__(self, fuse_gemm_info, gen_class_name, user_header_file, output_dir = "../"):
self.fuse_gemm_info = fuse_gemm_info
self.gen_class_name = gen_class_name + "_volta_impl"
self.user_header_file = ""
for header in user_header_file:
self.user_header_file += "#include \"" + header + "\"\n"
self.output_dir = output_dir
self.b2b_num = len(fuse_gemm_info)
def perf_tiling(self, layer_mnk):
mnk = layer_mnk[:]
block_tile = mnk[:]
block_tile[2] = 32 # force the K tile to be 32
# M tile gen
block_tile[0] = 32
# N tile gen
if mnk[1] > 128:
block_tile[1] = 256
elif mnk[1] > 64:
block_tile[1] = 128
elif mnk[1] > 32:
block_tile[1] = 64
else :
block_tile[1] = 32
warp_tile = block_tile[:]
if block_tile[1] == 256:
warp_tile[1] = 64
elif block_tile[1] == 128:
warp_tile[1] = 32
elif block_tile[1] == 64:
warp_tile[1] = 32
else :
warp_tile[1] = 32
warp_tile[0] = 32
return block_tile, warp_tile
def process_epilogue(self, epilogue_tp, n, C_tp, Acc_tp):
epilogue_setted_type = epilogue_tp
cutlass_epilogue_name = "LinearCombinationRelu"
if epilogue_setted_type.lower() == 'leakyrelu':
cutlass_epilogue_name = "LinearCombinationLeakyRelu"
elif epilogue_setted_type.lower() == 'identity':
cutlass_epilogue_name = "LinearCombination"
n_mod_8 = n % 4
N_align_elements = 1
if n_mod_8 == 0:
N_align_elements = 8
elif n_mod_8 == 4:
N_align_elements = 4
elif n_mod_8 == 2 or n_mod_8 == 6:
N_align_elements = 2
epilogue_str = "cutlass::epilogue::thread::" + cutlass_epilogue_name+ "<" + C_tp + ", " + str(N_align_elements) + ", " + Acc_tp + ", " + Acc_tp + ">"
return epilogue_str
def gen_using(self, volta = True):
code_using = ""
volta_arch = "cutlass::arch::Sm70"
volta_tc = "cutlass::gemm::GemmShape<8, 8, 4>"
turing_arch = "cutlass::arch::Sm75"
turing_tc = "cutlass::gemm::GemmShape<16, 8, 8>"
arch = ""
tc = ""
if volta:
arch = volta_arch
tc = volta_tc
else:
arch = turing_arch
tc = turing_tc
for i in range(self.b2b_num):
k = self.fuse_gemm_info[i]['mnk'][2]
k_mod_8 = k % 4
ab_ldm = 1
if k_mod_8 == 0:
ab_ldm = 8
elif k_mod_8 == 4:
ab_ldm = 4
elif k_mod_8 == 2 or k_mod_8 == 6:
ab_ldm = 2
block_tile, warp_tile = self.perf_tiling(self.fuse_gemm_info[i]['mnk'])
this_gemm_config = helper.var_idx("using Gemm", i) + " = cutlass::gemm::device::GemmBatched<\n"
this_gemm_config += " " + helper.type_2_cutlass_type(self.fuse_gemm_info[i]['A_tp']) + ",\n"
this_gemm_config += " " + helper.type_2_cutlass_type(self.fuse_gemm_info[i]['A_format']) + ",\n"
this_gemm_config += " " + helper.type_2_cutlass_type(self.fuse_gemm_info[i]['B_tp']) + ",\n"
this_gemm_config += " " + helper.type_2_cutlass_type(self.fuse_gemm_info[i]['B_format']) + ",\n"
this_gemm_config += " " + helper.type_2_cutlass_type(self.fuse_gemm_info[i]['C_tp']) + ",\n"
this_gemm_config += " " + helper.type_2_cutlass_type(self.fuse_gemm_info[i]['C_format']) + ",\n"
this_gemm_config += " " + helper.type_2_cutlass_type(self.fuse_gemm_info[i]['Acc_tp']) + ",\n"
this_gemm_config += " " + "cutlass::arch::OpClassTensorOp,\n"
this_gemm_config += " " + arch + ",\n"
this_gemm_config += " " + "cutlass::gemm::GemmShape<" + str(block_tile[0]) + ", " + str(block_tile[1]) + ", " + str(block_tile[2]) + ">,\n"
this_gemm_config += " " + "cutlass::gemm::GemmShape<" + str(warp_tile[0]) + ", " + str(warp_tile[1]) + ", " + str(warp_tile[2]) + ">,\n"
this_gemm_config += " " + tc + ",\n"
this_gemm_config += " " + self.process_epilogue(helper.get_epilogue_tp(self.fuse_gemm_info[i]), self.fuse_gemm_info[i]['mnk'][1], helper.type_2_cutlass_type(self.fuse_gemm_info[i]['C_tp']), helper.type_2_cutlass_type(self.fuse_gemm_info[i]['Acc_tp'])) + ",\n"
this_gemm_config += " " + "cutlass::gemm::threadblock::GemmBatchedIdentityThreadblockSwizzle,\n"
this_gemm_config += " " + "2,\n"
this_gemm_config += " " + str(ab_ldm) + ",\n"
this_gemm_config += " " + str(ab_ldm) + ">;\n"
code_using += this_gemm_config + "\n"
return code_using + "\n"
def gen_initialize(self):
code = ""
for i in range(self.b2b_num):
code_this = ""
N_str = str(self.fuse_gemm_info[i]['mnk'][1])
code_this += helper.var_idx(helper.type_2_cutlass_type(self.fuse_gemm_info[i]['Acc_tp']) + " alpha", i) + " = " + helper.type_2_cutlass_type(self.fuse_gemm_info[i]['Acc_tp']) + "(1);\n"
beta = "(1)"
if helper.get_epilogue_add_bias_or_not( self.fuse_gemm_info[i]) is False:
beta = "(0)"
code_this += helper.var_idx(helper.type_2_cutlass_type(self.fuse_gemm_info[i]['Acc_tp']) + " beta", i) + " = " + helper.type_2_cutlass_type(self.fuse_gemm_info[i]['Acc_tp']) + beta + ";\n"
k_str = str(self.fuse_gemm_info[i]['mnk'][2])
if i == 0:
k_str = "K0"
code_this += helper.var_idx("cutlass::gemm::GemmCoord problem_size_", i) + "(M, " + str(self.fuse_gemm_info[i]['mnk'][1]) + ", " + k_str + ");\n"
code_this += helper.var_idx("typename Gemm", i) + helper.var_idx("::Arguments arguments_", i) + "{\n"
code_this += " " + helper.var_idx("problem_size_", i) + ",\n"
ldmA = k_str
ldmB = k_str
ldmC = str(self.fuse_gemm_info[i]['mnk'][1])
ldmBias = str(helper.get_epilogue_bias_ldm(self.fuse_gemm_info[i]))
if self.fuse_gemm_info[i]['A_format'] is 'Col':
ldmA = "M"
if self.fuse_gemm_info[i]['B_format'] is 'Row':
ldmB = str(self.fuse_gemm_info[i]['mnk'][1])
if self.fuse_gemm_info[i]['C_format'] is 'Col':
ldmC = "M"
if i == 0:
code_this += " " + "{reinterpret_cast<" + helper.type_2_cutlass_type(self.fuse_gemm_info[i]['A_tp']) + "*>(" + helper.var_idx("A", i) + "), " + ldmA + "}, " + "M * " + ldmA + ",\n"
else:
code_this += " " + "{reinterpret_cast<" + helper.type_2_cutlass_type(self.fuse_gemm_info[i]['A_tp']) + "*>(" + helper.var_idx("D", i - 1) + "), " + ldmA + "}, " + "M * " + ldmA + ",\n"
code_this += " " + "{reinterpret_cast<" + helper.type_2_cutlass_type(self.fuse_gemm_info[i]['B_tp']) + "*>(" + helper.var_idx("B", i) + "), " + ldmB + "}, " + N_str + " * " + ldmB + ",\n"
M_bias = str(helper.get_epilogue_bias_shape(self.fuse_gemm_info[i])[0])
code_this += " " + "{reinterpret_cast<" + helper.type_2_cutlass_type(self.fuse_gemm_info[i]['C_tp']) + "*>(" + helper.var_idx("C", i) + "), " + ldmBias + "}, " + M_bias + " * " + N_str + ",\n"
code_this += " " + "{reinterpret_cast<" + helper.type_2_cutlass_type(self.fuse_gemm_info[i]['C_tp']) + "*>(" + helper.var_idx("D", i) + "), " + ldmC + "}, " + "M * " + ldmC + ",\n"
code_this += " " + "{ " + helper.var_idx("alpha", i) + ", " + helper.var_idx("beta", i)
for epilogue_arg in helper.get_epilogue_args(self.fuse_gemm_info[i]):
arg_name = helper.var_idx("Epilogue", i) + "_" + epilogue_arg[1]
code_this += ", " + helper.type_2_cutlass_type(self.fuse_gemm_info[i]['Acc_tp']) + "(" + str(arg_name) + ")"
code_this += " },\n"
code_this += " " + "Batch};\n"
code_this += " " + helper.var_idx("Gemm", i) + helper.var_idx(" gemm_op_", i) + ";\n"
code_this += " " + helper.var_idx("gemm_op_", i) + helper.var_idx(".initialize(arguments_", i) + ", nullptr);\n"
code += code_this + "\n"
return code + "\n"
def gen_run(self):
code = ""
for i in range(self.b2b_num):
code_this = ""
code_this += " " + helper.var_idx("gemm_op_", i) + "(stream);\n"
code += code_this
return code
def gen_wrapper(self):
code_body = ""
arg_lists = []
arg_lists.append(["int", "M"])
arg_lists.append(["int", "K0"])
arg_lists.append(["int", "Batch"])
arg_lists.append(["void*", helper.var_idx("A", 0)])
for i in range(self.b2b_num):
arg_lists.append(["void*", helper.var_idx("B", i)])
arg_lists.append(["void*", helper.var_idx("C", i)])
arg_lists.append(["void*", helper.var_idx("D", i)])
epilogue_args = helper.get_epilogue_args(self.fuse_gemm_info[i])
acc_tp = helper.get_epilogue_compute_tp(self.fuse_gemm_info[i])
for arg in epilogue_args:
arg_tp = arg[0]
arg_name = helper.var_idx("Epilogue", i) + "_" + arg[1]
arg_lists.append([arg_tp, arg_name])
code_body += self.gen_using()
code_body += self.gen_initialize()
code_body += self.gen_run()
code = ir.gen_func(self.gen_class_name, arg_lists, code_body)
return code
def gen_code(self):
code = self.gen_wrapper()
helper.write_2_headfile("volta_impl.h", self.output_dir, self.user_header_file + "\n" + code)
class gen_one_API:
def __init__(self, fuse_gemm_info, gen_class_name, user_header_file, output_dir = "../"):
self.fuse_gemm_info = fuse_gemm_info
self.gen_class_name = gen_class_name
self.user_header_file = ""
for header in user_header_file:
self.user_header_file += "#include \"" + header + "\"\n"
self.output_dir = output_dir
self.b2b_num = len(fuse_gemm_info)
self.gen_volta = gen_volta_turing_fuse_act_impl(fuse_gemm_info, gen_class_name, user_header_file, output_dir)
self.gen_turing = gen_turing_impl(fuse_gemm_info, gen_class_name, user_header_file, output_dir)
def gen_CUTLASS_irrelevant_API(self):
code = ""
code += "#include <cuda_runtime.h>\n"
code += "#include <assert.h>\n"
param_name = "Fused" + str(self.b2b_num) + "xGemm_"
for i in range(self.b2b_num):
param_name += str(self.fuse_gemm_info[i]['mnk'][1]) + "_"
param_name += "Params"
params = ""
params += " " + "int M;\n"
params += " " + "int K0;\n"
params += " " + "int Batch;\n"
params += " " + "const void* A0;\n"
for i in range(self.b2b_num):
params += " " + "const void* " + helper.var_idx("B", i) + ";\n"
params += " " + "const void* " + helper.var_idx("C", i) + ";\n"
epilogue_args = helper.get_epilogue_args(self.fuse_gemm_info[i])
acc_tp = helper.get_epilogue_compute_tp(self.fuse_gemm_info[i])
for arg in epilogue_args:
arg_tp = arg[0]
arg_name = helper.var_idx("Epilogue", i) + "_" + arg[1]
params += " " + arg_tp + " " + arg_name + ";\n"
params += " " + "void* " + helper.var_idx("D", i) + ";\n"
code += ir.gen_struct(param_name, params)
code += "using Param = " + param_name + ";\n"
code += "void one_api( const Param & param, int sm, cudaStream_t stream);\n"
return code
def gen_one_api(self):
code = ""
code += "/* Auto Generated code - Do not edit.*/\n"
code += "#include \"cutlass_irrelevant.h\"\n"
code += "#include \"api.h\"\n"
code += "void one_api( const Param & param, int sm, cudaStream_t stream) {\n"
code += " " + "if (sm == 70) \n"
code += " " + " " + self.gen_class_name + "_volta_impl(param.M, param.K0, param.Batch, const_cast<void*>(param.A0), "
for i in range(self.b2b_num):
code += helper.var_idx("const_cast<void*>(param.B", i) + "), "
code += helper.var_idx("const_cast<void*>(param.C", i) + "), "
code += helper.var_idx("param.D", i) + ", "
epilogue_args = helper.get_epilogue_args(self.fuse_gemm_info[i])
for arg in epilogue_args:
arg_name = helper.var_idx("Epilogue", i) + "_" + arg[1]
code += "param." + arg_name + ", "
code += "stream);\n"
code += " " + "else if(sm >= 75) \n"
code += " " + " " + self.gen_class_name + "_turing_impl(param.M, param.K0, param.Batch, const_cast<void*>(param.A0), "
for i in range(self.b2b_num):
code += helper.var_idx("const_cast<void*>(param.B", i) + "), "
code += helper.var_idx("const_cast<void*>(param.C", i) + "), "
code += helper.var_idx("param.D", i) + ", "
epilogue_args = helper.get_epilogue_args(self.fuse_gemm_info[i])
for arg in epilogue_args:
arg_name = helper.var_idx("Epilogue", i) + "_" + arg[1]
code += "param." + arg_name + ", "
code += "stream);\n"
code += " " + "else assert(0);\n"
code += "}\n"
return code
def gen_code(self):
turing_code = self.gen_turing.gen_wrapper()
volta_code = self.gen_volta.gen_wrapper()
cutlass_irrelevant_code = self.gen_CUTLASS_irrelevant_API()
one_api_code = self.gen_one_api()
with open(self.output_dir + "one_api.cu", "w+") as f:
f.write(one_api_code)
helper.write_2_headfile("cutlass_irrelevant.h", self.output_dir, cutlass_irrelevant_code)
helper.write_2_headfile("api.h", self.output_dir, self.user_header_file + "\n" + turing_code + volta_code)
| warp-main | warp/native/cutlass/examples/44_multi_gemm_ir_and_codegen/ir_gen/gen_turing_and_volta.py |
#################################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#################################################################################################
import helper
import gen_ir as ir
class gen_test:
def __init__(self, fuse_gemm_info, gen_class_name, user_header_file, output_dir = "../"):
self.fuse_gemm_info = fuse_gemm_info
self.gen_class_name = gen_class_name
self.user_header_file = user_header_file
self.sample_dir = output_dir
self.b2b_num = len(fuse_gemm_info)
def gen_cpp_sample(self):
code = "/* Auto Generated code - Do not edit.*/\n"
code += "#include <stdio.h> \n"
code += "#include \"cutlass/gemm/device/gemm_batched.h\" \n"
code += "#include \"cutlass/cutlass.h\" \n"
code += "#include \"../cutlass_irrelevant.h\" \n"
code += "#include \"../cutlass_verify.h\" \n"
code += "#include \"leaky_bias.h\" \n"
code += "#include \"utils.h\" \n"
code += "int main(int args, char * argv[]) {\n"
code += " " + "int M = atoi(argv[1]);\n"
code += " " + "int K0 = " + str(self.fuse_gemm_info[0]['mnk'][0]) + ";\n"
code += " " + "if(args == 3);\n"
code += " " + " " + "K0 = atoi(argv[2]);\n"
code += " " + "int B = 1;\n"
code += " " + "if(args == 4);\n"
code += " " + " " + "B = atoi(argv[3]);\n"
code += " " + "srand(1234UL);\n"
code += " " + "int device_id = 0;\n"
code += " " + "cudaGetDevice(&device_id);\n"
code += " " + "cudaDeviceProp prop;\n"
code += " " + "cudaGetDeviceProperties(&prop, device_id);\n"
code += " " + "int sm = prop.major *10 + prop.minor;\n"
code += "using ElementCompute = cutlass::half_t;\n"
for i in range(self.b2b_num):
code += " " + helper.var_idx("ElementCompute alpha", i) + " = ElementCompute(1);\n"
addbias = helper.get_epilogue_add_bias_or_not( self.fuse_gemm_info[i])
if addbias:
code += " " + helper.var_idx("ElementCompute beta", i) + " = ElementCompute(1);\n"
else:
code += " " + helper.var_idx("ElementCompute beta", i) + " = ElementCompute(0);\n"
code += " " + "size_t flops = 0;\n"
for i in range(self.b2b_num):
m = self.fuse_gemm_info[i]['mnk'][0]
n = self.fuse_gemm_info[i]['mnk'][1]
k = self.fuse_gemm_info[i]['mnk'][2]
bias_shape = helper.get_epilogue_bias_shape(self.fuse_gemm_info[i])
this_k = "K0"
if (i > 0):
this_k = str(k)
code += " " + "flops += size_t(2) * size_t(M) * size_t(B) * " + "size_t(" + str(n) + ") * size_t(" + this_k + ");\n"
code += " " + helper.var_idx("cutlass::gemm::GemmCoord problem_size_", i) + "(" + "M" + ", " + str(n) + ", " + this_k + ");\n"
code += " " + helper.var_idx("memory_unit<cutlass::half_t> Mat_A", i) + helper.var_idx("(B * problem_size_", i) + helper.var_idx(".m() * problem_size_", i) + ".k());\n"
code += " " + helper.var_idx("memory_unit<cutlass::half_t> Mat_B", i) + helper.var_idx("(B * problem_size_", i) + helper.var_idx(".n() * problem_size_", i) + ".k());\n"
code += " " + helper.var_idx("memory_unit<cutlass::half_t> Mat_C", i) + "(B * " + str(bias_shape[0]) + " * " + str(bias_shape[1]) + ");\n"
code += " " + helper.var_idx("memory_unit<cutlass::half_t> Mat_D_cutlass_ref", i) + helper.var_idx("(B * problem_size_", i) + helper.var_idx(".m() * problem_size_", i) + ".n());\n"
code += " " + helper.var_idx("Mat_A", i) + ".init();\n"
code += " " + helper.var_idx("Mat_B", i) + ".init();\n"
code += " " + helper.var_idx("Mat_C", i) + ".init();\n"
code += " " + helper.var_idx("memory_unit<cutlass::half_t> Mat_D", self.b2b_num - 1) + helper.var_idx("(B * problem_size_", i) + helper.var_idx(".m() * problem_size_",self.b2b_num - 1) + ".n());\n"
params = []
params.append("M")
params.append("B")
params.append("Mat_A0.device_ptr")
for i in range(self.b2b_num):
params.append(helper.var_idx("Mat_B", i) + ".device_ptr")
params.append(helper.var_idx("Mat_C", i) + ".device_ptr")
if i != self.b2b_num-1:
params.append(helper.var_idx("Mat_D_cutlass_ref", i) + ".device_ptr")
params.append(helper.var_idx("Mat_D", self.b2b_num - 1) + ".device_ptr")
code += " " + "Param arguments = {\n"
code += " " + " " + "M,\n"
code += " " + " " + "K0,\n"
code += " " + " " + "B,\n"
code += " " + " " + "reinterpret_cast<const void*>(Mat_A0.device_ptr),\n"
cnt = 1
for i in range(self.b2b_num):
bias_flag = helper.get_epilogue_add_bias_or_not( self.fuse_gemm_info[i])
code += " " + " " + "reinterpret_cast<const void*>(" + helper.var_idx("Mat_B", i) + ".device_ptr" + "),\n"
cnt += 1
if bias_flag:
code += " " + " " + "reinterpret_cast<const void*>(" + helper.var_idx("Mat_C", i) + ".device_ptr" + "),\n"
cnt += 1
else:
code += " " + " " + "reinterpret_cast<const void*>(NULL),\n"
epilogue_args = helper.get_epilogue_args(self.fuse_gemm_info[i])
acc_tp = helper.get_epilogue_compute_tp(self.fuse_gemm_info[i])
for arg in epilogue_args:
arg_value = str(arg[2])
code += " " + " " + helper.type_2_cutlass_type(acc_tp) + "(" + arg_value + "),\n"
if i != self.b2b_num - 1:
code += " " + " " + "reinterpret_cast<void*>(" + helper.var_idx("Mat_D_cutlass_ref", i) + ".device_ptr" + "),\n"
else:
code += " " + " " + "reinterpret_cast<void*>(" + helper.var_idx("Mat_D", i) + ".device_ptr" + ")};\n"
code += " " + "TI(FUSED_CUTLASS);\n"
code += " " + "for(int i = 0; i < 100; i++){\n"
code += " " + " " + "one_api(arguments, sm, NULL);\n"
code += " " + "}\n"
code += " " + "TO(FUSED_CUTLASS, \"FUSED_CUTLASS\", 100);\n"
code += "\n"
for i in range(self.b2b_num):
code_this = ""
N_str = str(self.fuse_gemm_info[i]['mnk'][1])
code_this += " " + helper.var_idx("typename Gemm", i) + helper.var_idx("::Arguments arguments_", i) + "{\n"
code_this += " " + " " + helper.var_idx("problem_size_", i) + ",\n"
ldmA = str(self.fuse_gemm_info[i]['mnk'][2])
if i == 0:
ldmA = "K0"
ldmB = str(self.fuse_gemm_info[i]['mnk'][2])
if i == 0:
ldmB = "K0"
ldmC = str(self.fuse_gemm_info[i]['mnk'][1])
ldmBias = str(helper.get_epilogue_bias_ldm(self.fuse_gemm_info[i]))
if self.fuse_gemm_info[i]['A_format'] is 'Col':
ldmA = "M"
if self.fuse_gemm_info[i]['B_format'] is 'Row':
ldmB = str(self.fuse_gemm_info[i]['mnk'][1])
if self.fuse_gemm_info[i]['C_format'] is 'Col':
ldmC = "M"
if i == 0:
code_this += " " + " " + "{reinterpret_cast<" + helper.type_2_cutlass_type(self.fuse_gemm_info[i]['A_tp']) + "*>(" + helper.var_idx("Mat_A", i) + ".device_ptr), " + ldmA + "}, " + "M * " + ldmA + ",\n"
else:
code_this += " " + " " + "{reinterpret_cast<" + helper.type_2_cutlass_type(self.fuse_gemm_info[i]['A_tp']) + "*>(" + helper.var_idx("Mat_D_cutlass_ref", i - 1) + ".device_ptr), " + ldmA + "}, " + "M * " + ldmA + ",\n"
code_this += " " + " " + "{reinterpret_cast<" + helper.type_2_cutlass_type(self.fuse_gemm_info[i]['B_tp']) + "*>(" + helper.var_idx("Mat_B", i) + ".device_ptr), " + ldmB + "}, " + N_str + " * " + ldmB + ",\n"
M_bias = str(helper.get_epilogue_bias_shape(self.fuse_gemm_info[i])[0])
code_this += " " + " " + "{reinterpret_cast<" + helper.type_2_cutlass_type(self.fuse_gemm_info[i]['C_tp']) + "*>(" + helper.var_idx("Mat_C", i) + ".device_ptr), " + ldmBias + "}, " + M_bias + " * " + N_str + ",\n"
code_this += " " + " " + "{reinterpret_cast<" + helper.type_2_cutlass_type(self.fuse_gemm_info[i]['C_tp']) + "*>(" + helper.var_idx("Mat_D_cutlass_ref", i) + ".device_ptr), " + ldmC + "}, " + "M * " + ldmC + ",\n"
code_this += " " + " " + "{ " + helper.var_idx("alpha", i) + ", " + helper.var_idx("beta", i)
for epilogue_arg in helper.get_epilogue_args(self.fuse_gemm_info[i]):
arg_value = str(epilogue_arg[2])
code_this += ", " + helper.type_2_cutlass_type(self.fuse_gemm_info[i]['Acc_tp']) + "(" + str(arg_value) + ")"
code_this += " " + " },\n"
code_this += " " + " " + "B};\n"
code += code_this
code += " " + "TI(UNFUSED_CUTLASS);\n"
code += " " + "for(int i = 0; i < 100; i++){\n"
code += " " + " " + self.gen_class_name + "_verify(\n"
for i in range(self.b2b_num):
code += " " + " " + " " + helper.var_idx("arguments_", i) + ",\n"
code += " " + " " + " " + "NULL);\n"
code += " " + "}\n"
code += " " + "TO(UNFUSED_CUTLASS, \"UNFUSED_CUTLASS\", 100);\n"
code += " " + helper.var_idx("Mat_D_cutlass_ref", self.b2b_num - 1) + ".d2h();\n"
code += " " + helper.var_idx("Mat_D", self.b2b_num - 1) + ".d2h();\n"
code += " " + helper.var_idx("check_result(Mat_D_cutlass_ref", self.b2b_num - 1) + helper.var_idx(".host_ptr, Mat_D", self.b2b_num - 1) \
+ helper.var_idx(".host_ptr, Mat_D", self.b2b_num - 1) + ".elements);\n"
code += "\n\n}\n"
with open(self.sample_dir + "sample.cu", "w+") as f:
f.write(code)
| warp-main | warp/native/cutlass/examples/44_multi_gemm_ir_and_codegen/ir_gen/gen_sample.py |
#################################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#################################################################################################
import os
class replace_fix_impl:
def __init__(self, src_dir, dst_dir, cutlass_deps_root):
self.src_dir = src_dir
self.dst_dir = dst_dir
self.cutlass_deps_root = cutlass_deps_root
def gen_code(self):
for sub_dir in os.walk(self.src_dir):
files_in_sub_dir = sub_dir[2]
src_dirs = sub_dir[0]
output_dirs = self.dst_dir + sub_dir[0][len(self.src_dir):]
if not os.path.exists(output_dirs):
os.mkdir(output_dirs)
for f in files_in_sub_dir:
with open(src_dirs +"/" + f, 'r') as current_file:
output_lines = []
lines = current_file.readlines()
for line in lines:
if(len(line) >= len("#include \"cutlass") and line[:len("#include \"cutlass")] == "#include \"cutlass"):
new_line = "#include \"" + self.cutlass_deps_root + line[len("#include \""):]
# print(new_line)
output_lines.append(new_line)
else:
output_lines.append(line)
with open(output_dirs + "/" + f, "w+") as dest_file:
dest_file.writelines(output_lines)
| warp-main | warp/native/cutlass/examples/44_multi_gemm_ir_and_codegen/ir_gen/replace_fix_impl_header.py |
#################################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#################################################################################################
import helper
indentation = " "
def append_word(word):
code = ""
code += word
code += " "
return code
def gen_namespace(namespace, codeBody):
code_gen = "namespace " + namespace + " {\n"
code_gen += codeBody
code_gen += "} // namespace " + namespace + "\n"
return code_gen
def gen_expression(type, lval, rval = None):
code_gen = ""
code_gen += append_word(type)
code_gen += append_word(lval)
if rval is not None:
code_gen += append_word("=")
code_gen += append_word(rval)
return code_gen
def gen_class(name, codeBody, inheritance_code = None):
code_gen = ""
if inheritance_code is None:
code_gen = "class " + name + "{\n"
else:
code_gen = "class " + name + " : "+ inheritance_code + "{\n"
code_gen += codeBody
code_gen += "}; // class " + name + "\n"
return code_gen
def gen_struct(name, codeBody, specialized = None):
specialized_code = ""
if specialized is not None:
specialized_code = "<" + specialized + ">"
code_gen = "struct " + name + specialized_code + "{\n"
code_gen += codeBody
code_gen += "}; // struct " + name + "\n"
return code_gen
def gen_template_arg(arg_type, arg_name, default_val = None):
rval = None
if default_val is not None:
rval = str(default_val)
arg_typename = ""
if arg_type is int:
arg_typename = "int"
elif arg_type is bool:
arg_typename = "bool"
else:
arg_typename = "typename"
internal_arg_name = arg_name + "_"
code_gen = indentation
code_gen += gen_expression(arg_typename, internal_arg_name, rval)
return code_gen
def gen_template_args(args, set_default = True):
arg_len = len(args)
cnt = 1
code_gen = ""
for arg_tuple in args:
arg_type = arg_tuple[0]
arg_name = arg_tuple[1]
arg_default_val = None
if len(arg_tuple) == 3 and set_default:
arg_default_val = arg_tuple[2]
code_gen += gen_template_arg(arg_type, arg_name, arg_default_val)
if cnt != arg_len:
code_gen += ",\n"
cnt += 1
return code_gen
def gen_template_head(args, set_default = True):
code_gen = "template <\n"
code_gen += gen_template_args(args, set_default)
code_gen += ">\n"
return code_gen
def export_template_args(args):
code_gen = "public:\n"
for arg_tuple in args:
code_gen += indentation
arg_type = arg_tuple[0]
arg_name = arg_tuple[1]
internal_arg_name = arg_name + "_"
typename = ""
if arg_type is int:
typename = "static int const"
elif arg_type is bool:
typename = "static bool const"
else:
typename = "using"
code_gen += gen_expression(typename, arg_name, internal_arg_name)
code_gen += ";\n"
return code_gen
def gen_template_class(class_name, args, codeBody, set_default = True, inheritance_code = None):
code_gen = ""
code_gen += gen_template_head(args, set_default)
code_gen += gen_class(class_name, export_template_args(args) + codeBody, inheritance_code)
return code_gen
def gen_template_struct(struct_name, args, codeBody, speicalized = None, set_default = True, export_args = True):
code_gen = ""
code_gen += gen_template_head(args, set_default)
code = export_template_args(args) + codeBody
if export_args is False:
code = codeBody
code_gen += gen_struct(struct_name, code , speicalized)
return code_gen
def gen_declare_template_struct(name, *params):
code = name + "<"
cnt = 0
param_num = len(params)
for param in params:
final = ", "
if cnt == param_num - 1:
final = ""
code += param + final
cnt += 1
code += ">;\n"
return code
def filtered_param(params, name_and_value_pair, keep_ = False):
rtn_template_args = []
speicalized_template_args = []
for param in params:
param_name = ""
if len(param) >= 1:
param_name = param[1]
else:
param_name = param[0]
hit_flag = False
set_value = ""
for n_v_pair in name_and_value_pair:
filter_name = n_v_pair[0]
set_value = n_v_pair[1]
if param_name == (filter_name + "_") or param_name == filter_name :
hit_flag = True
break
if hit_flag is False:
rtn_template_args.append(param)
if hit_flag is True:
speicalized_template_args.append(set_value)
else:
if keep_ is True:
speicalized_template_args.append(param_name + "_")
else:
speicalized_template_args.append(param_name)
specialized_template_arg_str = helper.list_2_string(speicalized_template_args)
return rtn_template_args, specialized_template_arg_str
def gen_func(func_name, arg_lists, code_body, only_declare = False, with_cudaStream = True):
code = "void " + func_name + "(\n"
for arg in arg_lists:
arg_tp = arg[0]
arg_nm = arg[1]
code += " " + arg_tp + " " + arg_nm + ",\n"
code += "cudaStream_t stream)"
if only_declare :
return code
code += "{\n"
code += code_body + "\n"
code += "}\n"
return code
def indent_level(code, level = 0):
rtn_code = ""
for i in range(level):
rtn_code += " "
rtn_code += code
return rtn_code
| warp-main | warp/native/cutlass/examples/44_multi_gemm_ir_and_codegen/ir_gen/gen_ir.py |
################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
################################################################################
"""
Basic example of using the CUTLASS Python interface to run a GEMM
"""
import argparse
import numpy as np
import sys
import cutlass
import pycutlass
from pycutlass import *
from pycutlass.utils.device import device_cc
parser = argparse.ArgumentParser(description="Launch a GEMM kernel from Python: 'D = alpha * A * B + beta * C'")
parser.add_argument("--m", default=128, type=int, help="M dimension of the GEMM")
parser.add_argument("--n", default=128, type=int, help="N dimension of the GEMM")
parser.add_argument("--k", default=128, type=int, help="K dimension of the GEMM")
parser.add_argument('--print_cuda', action="store_true", help="Print the underlying CUDA kernel")
try:
args = parser.parse_args()
except:
sys.exit(0)
# Check that the device is of a sufficient compute capability
cc = device_cc()
assert cc >= 70, "The CUTLASS Python GEMM example requires compute capability greater than or equal to 70."
alignment = 8
assert args.m % alignment == 0, "M dimension of size {} is not divisible by alignment of {}".format(args.m, alignment)
assert args.n % alignment == 0, "N dimension of size {} is not divisible by alignment of {}".format(args.n, alignment)
assert args.k % alignment == 0, "K dimension of size {} is not divisible by alignment of {}".format(args.k, alignment)
np.random.seed(0)
# Allocate a pool of device memory to be used by the kernel
pycutlass.get_memory_pool(init_pool_size=2**30, max_pool_size=2**32)
# Set the compiler to use to NVCC
pycutlass.compiler.nvcc()
# Set up A, B, C and accumulator
A = TensorDescription(cutlass.float16, cutlass.ColumnMajor, alignment)
B = TensorDescription(cutlass.float16, cutlass.RowMajor, alignment)
C = TensorDescription(cutlass.float32, cutlass.ColumnMajor, alignment)
element_acc = cutlass.float32
element_epilogue = cutlass.float32
# Select instruction shape based on the Tensor Core instructions supported
# by the device on which we are running
if cc == 70:
instruction_shape = [8, 8, 4]
elif cc == 75:
instruction_shape = [16, 8, 8]
else:
instruction_shape = [16, 8, 16]
math_inst = MathInstruction(
instruction_shape,
A.element, B.element, element_acc,
cutlass.OpClass.TensorOp,
MathOperation.multiply_add
)
tile_description = TileDescription(
[128, 128, 32], # Threadblock shape
2, # Number of stages
[2, 2, 1], # Number of warps within each dimension of the threadblock shape
math_inst
)
epilogue_functor = pycutlass.LinearCombination(C.element, C.alignment, element_acc, element_epilogue)
operation = GemmOperationUniversal(
arch=cc, tile_description=tile_description,
A=A, B=B, C=C,
epilogue_functor=epilogue_functor)
if args.print_cuda:
print(operation.rt_module.emit())
operations = [operation, ]
# Compile the operation
pycutlass.compiler.add_module(operations)
# Randomly initialize tensors
tensor_A = np.ceil(np.random.uniform(low=-8.5, high=7.5, size=(args.m * args.k,))).astype(np.float16)
tensor_B = np.ceil(np.random.uniform(low=-8.5, high=7.5, size=(args.k * args.n,))).astype(np.float16)
tensor_C = np.ceil(np.random.uniform(low=-8.5, high=7.5, size=(args.m * args.n,))).astype(np.float32)
tensor_D = np.zeros(shape=(args.m * args.n,)).astype(np.float32)
problem_size = cutlass.gemm.GemmCoord(args.m, args.n, args.k)
alpha = 1.
beta = 0.
arguments = GemmArguments(
operation=operation, problem_size=problem_size,
A=tensor_A, B=tensor_B, C=tensor_C, D=tensor_D,
output_op=operation.epilogue_type(alpha, beta))
# Run the operation
operation.run(arguments)
arguments.sync()
# Run the host reference module and compare to the CUTLASS result
reference = ReferenceModule(A, B, C)
tensor_D_ref = reference.run(tensor_A, tensor_B, tensor_C, problem_size, alpha, beta)
try:
assert np.array_equal(tensor_D, tensor_D_ref)
except:
assert np.allclose(tensor_D, tensor_D_ref, atol=1e-5)
print("Passed.")
| warp-main | warp/native/cutlass/examples/40_cutlass_py/gemm.py |
################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
################################################################################
"""
Basic example of using the CUTLASS Python interface to run a 2d convolution
"""
import argparse
import torch
import numpy as np
import sys
import cutlass
import pycutlass
from pycutlass import *
from pycutlass.utils.device import device_cc
parser = argparse.ArgumentParser(
description=("Launch a 2d convolution kernel from Python. "
"See https://docs.nvidia.com/deeplearning/performance/dl-performance-convolutional/index.html#convo-intro for notation."))
parser.add_argument("--n", default=1, type=int, help="N dimension of the convolution")
parser.add_argument("--c", default=64, type=int, help="C dimension of the convolution")
parser.add_argument("--h", default=32, type=int, help="H dimension of the convolution")
parser.add_argument("--w", default=32, type=int, help="W dimension of the convolution")
parser.add_argument("--k", default=32, type=int, help="N dimension of the convolution")
parser.add_argument("--r", default=3, type=int, help="R dimension of the convolution")
parser.add_argument("--s", default=3, type=int, help="S dimension of the convolution")
parser.add_argument('--print_cuda', action="store_true", help="Print the underlying CUDA kernel")
try:
args = parser.parse_args()
except:
sys.exit(0)
# Check that the device is of a sufficient compute capability
cc = device_cc()
assert cc >= 70, "The CUTLASS Python Conv2d example requires compute capability greater than or equal to 70."
alignment = 1
np.random.seed(0)
# Allocate a pool of device memory to be used by the kernel
pycutlass.get_memory_pool(init_pool_size=2**30, max_pool_size=2**32)
# Set the compiler to use to NVCC
pycutlass.compiler.nvcc()
# Set up A, B, C and accumulator
A = TensorDescription(cutlass.float16, cutlass.TensorNHWC, alignment)
B = TensorDescription(cutlass.float16, cutlass.TensorNHWC, alignment)
C = TensorDescription(cutlass.float32, cutlass.TensorNHWC, alignment)
element_acc = cutlass.float32
element_epilogue = cutlass.float32
# Select instruction shape based on the Tensor Core instructions supported
# by the device on which we are running
if cc == 70:
instruction_shape = [8, 8, 4]
elif cc == 75:
instruction_shape = [16, 8, 8]
else:
instruction_shape = [16, 8, 16]
math_inst = MathInstruction(
instruction_shape,
A.element, B.element, element_acc,
cutlass.OpClass.TensorOp,
MathOperation.multiply_add
)
tile_description = TileDescription(
[128, 128, 32], # Threadblock shape
2, # Number of stages
[2, 2, 1], # Number of warps within each dimension of the threadblock shape
math_inst
)
epilogue_functor = pycutlass.LinearCombination(C.element, C.alignment, element_acc, element_epilogue)
operation = Conv2dOperation(
conv_kind=cutlass.conv.Operator.fprop,
iterator_algorithm=cutlass.conv.IteratorAlgorithm.optimized,
arch=cc, tile_description=tile_description,
A=A, B=B, C=C, stride_support=StrideSupport.Strided,
epilogue_functor=epilogue_functor
)
if args.print_cuda:
print(operation.rt_module.emit())
operations = [operation, ]
# Compile the operation
pycutlass.compiler.add_module(operations)
# Randomly initialize tensors
problem_size = cutlass.conv.Conv2dProblemSize(
cutlass.Tensor4DCoord(args.n, args.h, args.c, args.w),
cutlass.Tensor4DCoord(args.k, args.r, args.s, args.c),
cutlass.Tensor4DCoord(0, 0, 0, 0), # Padding
cutlass.MatrixCoord(1, 1), # Strides
cutlass.MatrixCoord(1, 1), # Dilation
cutlass.conv.Mode.cross_correlation,
1, # Split k slices
1 # Groups
)
tensor_A_size = cutlass.conv.implicit_gemm_tensor_a_size(operation.conv_kind, problem_size)
tensor_B_size = cutlass.conv.implicit_gemm_tensor_b_size(operation.conv_kind, problem_size)
tensor_C_size = cutlass.conv.implicit_gemm_tensor_c_size(operation.conv_kind, problem_size)
tensor_A = torch.ceil(torch.empty(size=(tensor_A_size,), dtype=torch.float16, device="cuda").uniform_(-8.5, 7.5))
tensor_B = torch.ceil(torch.empty(size=(tensor_B_size,), dtype=torch.float16, device="cuda").uniform_(-8.5, 7.5))
tensor_C = torch.ceil(torch.empty(size=(tensor_C_size,), dtype=torch.float32, device="cuda").uniform_(-8.5, 7.5))
tensor_D = torch.ones(size=(tensor_C_size,), dtype=torch.float32, device="cuda")
alpha = 1.
beta = 0.
arguments = Conv2dArguments(
operation=operation, problem_size=problem_size,
A=tensor_A, B=tensor_B, C=tensor_C, D=tensor_D,
output_op=operation.epilogue_type(alpha, beta)
)
# Run the operation
operation.run(arguments)
arguments.sync()
# Run the host reference module and compare to the CUTLASS result
reference = Conv2dReferenceModule(A, B, C, operation.conv_kind)
tensor_D_ref = reference.run(tensor_A, tensor_B, tensor_C, problem_size, alpha, beta)
try:
assert torch.equal(tensor_D, tensor_D_ref)
except:
assert torch.allclose(tensor_D, tensor_D_ref, rtol=1e-2)
print("Passed.")
| warp-main | warp/native/cutlass/examples/40_cutlass_py/conv2d.py |
################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
################################################################################
"""
Basic example of using the CUTLASS Python interface to run a grouped GEMM
"""
import argparse
import numpy as np
import sys
import cutlass
import pycutlass
from pycutlass import *
from pycutlass.utils.device import device_cc
parser = argparse.ArgumentParser(description="Launch a grouped GEMM kernel from Python")
parser.add_argument('--print_cuda', action="store_true", help="Print the underlying CUDA kernel")
try:
args = parser.parse_args()
except:
sys.exit(0)
# Check that the device is of a sufficient compute capability
cc = device_cc()
assert cc >= 70, "The CUTLASS Python grouped GEMM example requires compute capability greater than or equal to 70."
np.random.seed(0)
# Allocate a pool of device memory to be used by the kernel
pycutlass.get_memory_pool(init_pool_size=2**30, max_pool_size=2**32)
# Set the compiler to use to NVCC
pycutlass.compiler.nvcc()
# Set up A, B, C and accumulator
alignment = 1
A = TensorDescription(cutlass.float16, cutlass.ColumnMajor, alignment)
B = TensorDescription(cutlass.float16, cutlass.RowMajor, alignment)
C = TensorDescription(cutlass.float32, cutlass.ColumnMajor, alignment)
element_acc = cutlass.float32
element_epilogue = cutlass.float32
# Select instruction shape based on the Tensor Core instructions supported
# by the device on which we are running
if cc == 70:
instruction_shape = [8, 8, 4]
elif cc == 75:
instruction_shape = [16, 8, 8]
else:
instruction_shape = [16, 8, 16]
math_inst = MathInstruction(
instruction_shape,
A.element, B.element, element_acc,
cutlass.OpClass.TensorOp,
MathOperation.multiply_add
)
tile_description = TileDescription(
[128, 128, 32], # Threadblock shape
2, # Number of stages
[2, 2, 1], # Number of warps within each dimension of the threadblock shape
math_inst
)
epilogue_functor = pycutlass.LinearCombination(C.element, C.alignment, element_acc, element_epilogue)
operation = GemmOperationGrouped(
arch=cc, tile_description=tile_description,
A=A, B=B, C=C,
epilogue_functor=epilogue_functor,
precompute_mode=SchedulerMode.Device)
if args.print_cuda:
print(operation.rt_module.emit())
operations = [operation, ]
# Compile the operation
pycutlass.compiler.add_module(operations)
# Initialize tensors for each problem in the group
problem_sizes = [
cutlass.gemm.GemmCoord(128, 128, 64),
cutlass.gemm.GemmCoord(512, 256, 128)
]
problem_count = len(problem_sizes)
alpha = 1.
beta = 0.
tensor_As = []
tensor_Bs = []
tensor_Cs = []
tensor_Ds = []
tensor_D_refs = []
reference = ReferenceModule(A, B, C)
for problem_size in problem_sizes:
# Randomly initialize tensors
m = problem_size.m()
n = problem_size.n()
k = problem_size.k()
tensor_A = np.ceil(np.random.uniform(low=-8.5, high=7.5, size=(m * k,))).astype(np.float16)
tensor_B = np.ceil(np.random.uniform(low=-8.5, high=7.5, size=(k * n,))).astype(np.float16)
tensor_C = np.ceil(np.random.uniform(low=-8.5, high=7.5, size=(m * n,))).astype(np.float32)
tensor_D = np.zeros(shape=(m * n,)).astype(np.float32)
tensor_As.append(tensor_A)
tensor_Bs.append(tensor_B)
tensor_Cs.append(tensor_C)
tensor_Ds.append(tensor_D)
# Run the reference GEMM
tensor_D_ref = reference.run(tensor_A, tensor_B, tensor_C, problem_size, alpha, beta)
tensor_D_refs.append(tensor_D_ref)
arguments = GemmGroupedArguments(
operation, problem_sizes, tensor_As, tensor_Bs, tensor_Cs, tensor_Ds,
output_op=operation.epilogue_type(alpha, beta)
)
# Run the operation
operation.run(arguments)
arguments.sync()
# Compare the CUTLASS result to the host reference result
for tensor_d, tensor_d_ref in zip(tensor_Ds, tensor_D_refs):
try:
assert np.array_equal(tensor_d, tensor_d_ref)
except:
assert np.allclose(tensor_d, tensor_d_ref, rtol=1e-5)
print("Passed.")
| warp-main | warp/native/cutlass/examples/40_cutlass_py/gemm_grouped.py |
################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
################################################################################
import numpy as np
import pycutlass
from pycutlass import *
import cutlass
from bfloat16 import bfloat16
from pycutlass.utils.device import device_cc
import sys
import argparse
# parse the arguments
parser = argparse.ArgumentParser(description="Launch CUTLASS GEMM kernels from Python: 'D = alpha * A * B + beta * C'")
# Operation description
# math instruction description
parser.add_argument("-i", "--instruction_shape",
default=[1, 1, 1], nargs=3, type=int,
help="This option describes the size of MMA op")
parser.add_argument("-ta", "--element_a", default="float32", type=str,
choices=['float64', 'float32', 'float16', 'bfloat16', 'int32', 'int8'],
help='Data type of elements in input tensor A')
parser.add_argument("-tb", "--element_b", default="float32", type=str,
choices=['float64', 'float32', 'float16', 'bfloat16', 'int32', 'int8'],
help='Data type of elements in input tensor B')
parser.add_argument("-tc", "--element_c", default="float32", type=str,
choices=['float64', 'float32', 'float16', 'bfloat16', 'int32', 'int8'],
help='Data type of elements in input tensor C and output tensor D')
parser.add_argument("-tacc", "--element_acc", default="float32", type=str,
choices=['float64', 'float32', 'float16', 'bfloat16', 'int32', 'int8'],
help='Data type of accumulator')
parser.add_argument('-m', "--math", default="multiply_add",
type=str, choices=["multiply_add", "multiply_add_fast_bf16", "multiply_add_fast_f32"], help="math instruction")
parser.add_argument('-op', "--opcode", default="simt", type=str,
choices=["Simt", 'TensorOp'],
help="This option describes whether you want to use tensor \
cores (TensorOp) or regular SIMT cores (Simt) on GPU SM")
# tile description
parser.add_argument("-b", "--threadblock_shape",
default=[128, 128, 8], nargs=3, type=int,
help="This option describes the tile size a thread block with compute")
parser.add_argument("-s", "--stages", default=4,
type=int, help="Number of pipelines you want to use")
parser.add_argument("-w", "--warp_count", default=[4, 2, 1], nargs=3, type=int,
help="This option describes the number of warps along M, N, and K of the threadblock")
parser.add_argument("-cc", "--compute_capability", default=80,
type=int, help="This option describes CUDA SM architecture number")
# A
parser.add_argument('-la', "--layout_a", default="RowMajor", type=str, choices=[
"RowMajor", "ColumnMajor", "RowMajorInterleaved32", "ColumnMajorInterleaved32"],
help="Memory layout of input tensor A")
parser.add_argument('-aa', '--alignment_a', default=1,
type=int, help="Memory alignement of input tensor A")
# B
parser.add_argument('-lb', "--layout_b", default="RowMajor", type=str, choices=[
"RowMajor", "ColumnMajor", "RowMajorInterleaved32", "ColumnMajorInterleaved32"],
help="Memory layout of input tensor B")
parser.add_argument('-ab', '--alignment_b', default=1,
type=int, help="Memory alignment of input tensor B")
# C
parser.add_argument('-lc', "--layout_c", default="RowMajor", type=str, choices=[
"RowMajor", "ColumnMajor", "RowMajorInterleaved32", "ColumnMajorInterleaved32"],
help="Memory layout of input tensor C and output tensor D")
parser.add_argument('-ac', '--alignment_c', default=1,
type=int, help="Memory alignment of input tensor C and output tensor D")
# epilogue
parser.add_argument("-te", "--element_epilogue", default="float32", type=str,
choices=['float64', 'float32', 'float16', 'bfloat16'], help='Epilogue datatype')
parser.add_argument("-ep", "--epilogue_functor", default="LinearCombination",
type=str, choices=['LinearCombination', 'FastLinearCombinationClamp', 'LinearCombinationClamp'],
help="This option describes the epilogue part of the kernel")
parser.add_argument("-epv", "--epilogue_visitor", default=None,
type=str, choices=['RowReduction', 'ColumnReduction', 'RowBroadcast', 'ColumnBroadcast'], help="epilogue visitor for more complex epilogues")
# swizzling
parser.add_argument("-sw", "--swizzling_functor", default="IdentitySwizzle1", type=str, choices=[
"IdentitySwizzle1", "IdentitySwizzle2", "IdentitySwizzle4", "IdentitySwizzle8", "HorizontalSwizzle", "BatchedIdentitySwizzle"],
help="This option describes how thread blocks are scheduled on GPU")
# Argument
parser.add_argument("-p", "--problem_size",
default=[128, 128, 128], nargs=3, type=int,
help="GEMM problem size M, N, K")
parser.add_argument("-alpha", "--alpha", default=1.0, type=float,
help="Scaling factor of A * B")
parser.add_argument("-beta", "--beta", default=0.0, type=float,
help="Scaling factor of C")
parser.add_argument("-gm", "--gemm_mode", default="Gemm", type=str,
choices=["Gemm", "GemmSplitKParallel", "Batched", "Array"],
help="GEMM mode. Gemm is used for non-splitK or serial-splitK. \
GemmSplitKParallel is used for parallel splitK")
parser.add_argument('-k', '--split_k_slices', default=1,
type=int, help="Number of split-k partitions. (default 1)")
parser.add_argument('-bias', '--bias', action='store_true', help="C is bias vector")
parser.add_argument('-batch', '--batch', default=1, type=int, help="batch size for batched GEMM")
# Activation function
parser.add_argument("-activ", "--activation_function", default="identity",
choices=["identity", "relu", "leaky_relu", "tanh", "sigmoid", "silu", "hardswish", "gelu"], help="activation function")
parser.add_argument("-activ_arg", "--activation_args", default=[], nargs="+", type=float,
help="addition arguments for activation")
parser.add_argument('--print_cuda', action="store_true",
help="print the underlying CUDA kernel")
try:
args = parser.parse_args()
except:
sys.exit(0)
cc = device_cc()
if args.compute_capability != cc:
raise Exception(("Parameter --compute-capability of {} "
"does not match that of the device of {}.").format(args.compute_capability, cc))
pycutlass.get_memory_pool(init_pool_size=2**30, max_pool_size=2**32)
pycutlass.compiler.nvcc()
np.random.seed(0)
element_a = getattr(cutlass, args.element_a)
element_b = getattr(cutlass, args.element_b)
element_c = getattr(cutlass, args.element_c)
element_acc = getattr(cutlass, args.element_acc)
math_operation = getattr(MathOperation, args.math)
opclass = getattr(cutlass.OpClass, args.opcode)
math_inst = MathInstruction(
args.instruction_shape, element_a, element_b,
element_acc, opclass, math_operation
)
tile_description = TileDescription(
args.threadblock_shape, args.stages, args.warp_count,
math_inst
)
layout_a = getattr(cutlass, args.layout_a)
layout_b = getattr(cutlass, args.layout_b)
layout_c = getattr(cutlass, args.layout_c)
A = TensorDescription(
element_a, layout_a, args.alignment_a
)
B = TensorDescription(
element_b, layout_b, args.alignment_b
)
C = TensorDescription(
element_c, layout_c, args.alignment_c
)
element_epilogue = getattr(cutlass, args.element_epilogue)
if (args.activation_function == "identity"
or (args.gemm_mode == "GemmSplitKParallel" and args.split_k_slices > 1)):
#
epilogue_functor = getattr(pycutlass, args.epilogue_functor)(
C.element, C.alignment, math_inst.element_accumulator, element_epilogue)
else:
epilogue_functor = getattr(pycutlass, "LinearCombinationGeneric")(
getattr(pycutlass, args.activation_function)(element_epilogue),
C.element, C.alignment, math_inst.element_accumulator, element_epilogue)
swizzling_functor = getattr(cutlass, args.swizzling_functor)
visitor = args.epilogue_visitor is not None
if args.epilogue_visitor == "ColumnReduction":
class ColumnReduction_(EpilogueVisitTree):
def __call__(
self, accum: 'tensor', c: 'tensor',
alpha: 'scalar', beta: 'scalar'):
#
D = alpha * accum + beta * c
reduction = reduction_op(D, "column", "Add", args.threadblock_shape[0])
return D, reduction
epilogue_functor = ColumnReduction_(
epilogue_functor, tile_description, math_inst.element_accumulator,
C.alignment, element_epilogue, C.element)
epilogue_functor.initialize()
elif args.epilogue_visitor == "RowReduction":
class RowReduction_(EpilogueVisitTree):
def __call__(
self, accum: 'tensor', c: 'tensor',
alpha: 'scalar', beta: 'scalar'):
#
D = alpha * accum + tanh.numpy(beta * c)
reduction = reduction_op(D, "row", "Add", args.threadblock_shape[1])
return D, reduction
epilogue_functor = RowReduction_(
epilogue_functor, tile_description, math_inst.element_accumulator,
C.alignment, element_epilogue, C.element)
epilogue_functor.initialize()
elif args.epilogue_visitor == "RowBroadcast":
class RowBroadcast_(EpilogueVisitTree):
def __call__(
self, accum: 'tensor', c: 'tensor',
vector: 'row', alpha: 'scalar', beta: 'scalar'):
#
T = accum + vector
scale_T = alpha * T
Z = relu.numpy(scale_T + beta * c)
return Z, T
epilogue_functor = RowBroadcast_(
epilogue_functor, tile_description, math_inst.element_accumulator,
C.alignment, element_epilogue, C.element)
epilogue_functor.initialize()
elif args.epilogue_visitor == "ColumnBroadcast":
class ColumnBroadcast_(EpilogueVisitTree):
def __call__(
self, accum: 'tensor', c: 'tensor',
vector: 'column', alpha: 'scalar', beta: 'scalar'):
#
T = accum + vector
scale_T = leaky_relu.numpy(alpha * T, 0.2)
Z = scale_T + beta * c
return Z, T
epilogue_functor = ColumnBroadcast_(
epilogue_functor, tile_description, math_inst.element_accumulator,
C.alignment, element_epilogue, C.element)
epilogue_functor.initialize()
else:
epilogue_functor = epilogue_functor
operation = GemmOperationUniversal(
arch=args.compute_capability, tile_description=tile_description,
A=A, B=B, C=C,
epilogue_functor=epilogue_functor, swizzling_functor=swizzling_functor,
visitor=visitor
)
if args.print_cuda:
print(operation.rt_module.emit())
operations = [operation, ]
if args.gemm_mode == "GemmSplitKParallel":
if (args.activation_function == "identity"):
epilogue_functor_reduction = getattr(pycutlass, args.epilogue_functor)(
C.element, C.alignment, math_inst.element_accumulator, element_epilogue)
else:
epilogue_functor_reduction = getattr(pycutlass, "LinearCombinationGeneric")(
getattr(pycutlass, args.activation_function)(element_epilogue),
C.element, C.alignment, math_inst.element_accumulator, element_epilogue)
reduction_operation = ReductionOperation(
shape=cutlass.MatrixCoord(4, 32 * C.alignment),
C=C, element_accumulator=element_acc,
element_compute=element_epilogue,
epilogue_functor=epilogue_functor_reduction,
count=C.alignment
)
operations.append(reduction_operation)
pycutlass.compiler.add_module(operations)
# User-provide inputs
problem_size = cutlass.gemm.GemmCoord(
args.problem_size[0], args.problem_size[1], args.problem_size[2])
tensor_a_size = args.batch * problem_size.m() * problem_size.k()
if args.element_a != "int8":
if args.element_a == "bfloat16":
tensor_A = np.ceil(
np.random.uniform(low=-8.5, high=7.5, size=(tensor_a_size,))
).astype(bfloat16)
else:
tensor_A = np.ceil(
np.random.uniform(low=-8.5, high=7.5, size=(tensor_a_size,))
).astype(getattr(np, args.element_a))
else:
tensor_A = np.random.uniform(
low=-2, high=2,size=(tensor_a_size,)
).astype(getattr(np, args.element_a))
tensor_b_size = args.batch * problem_size.k() * problem_size.n()
if args.element_b != "int8":
if args.element_b == "bfloat16":
tensor_B = np.ceil(
np.random.uniform(low=-8.5, high=7.5, size=(tensor_b_size,))
).astype(bfloat16)
else:
tensor_B = np.ceil(
np.random.uniform(low=-8.5, high=7.5, size=(tensor_b_size,))
).astype(getattr(np, args.element_b))
else:
tensor_B = np.random.uniform(
low=-2, high=2, size=(tensor_b_size,)
).astype(getattr(np, args.element_b))
if args.element_c != "int8":
if args.bias:
if args.layout_c == "RowMajor":
tensor_c_size = args.batch * problem_size.n()
elif args.layout_c == "ColumnMajor":
tensor_c_size = args.batch * problem_size.m()
else:
raise ValueError(args.layout_c)
else:
tensor_c_size = args.batch * problem_size.m() * problem_size.n()
if args.element_c == "bfloat16":
tensor_C = np.ceil(
np.random.uniform(low=-8.5, high=7.5, size=(tensor_c_size,))
).astype(bfloat16)
else:
tensor_C = np.ceil(
np.random.uniform(low=-8.5, high=7.5, size=(tensor_c_size,))
).astype(getattr(np, args.element_c))
else:
tensor_C = np.random.uniform(
low=-2, high=2, size=(args.batch * problem_size.m() * problem_size.n(),)
).astype(getattr(np, args.element_c))
tensor_D = np.zeros(
shape=(args.batch * problem_size.m() * problem_size.n(),)
).astype(getattr(np, args.element_c))
if args.epilogue_visitor == "RowReduction":
cta_n = args.threadblock_shape[1]
num_cta_n = (problem_size.n() + cta_n - 1) // cta_n
reduction = np.zeros(shape=(args.batch * problem_size.m() * num_cta_n,), dtype=getattr(np, args.element_c))
output_op = operation.epilogue_type(
D=tensor_D, alpha=args.alpha, beta=args.beta, c=tensor_C, reduction=reduction, problem_size=[problem_size.m(), problem_size.n()]
)
elif args.epilogue_visitor == "ColumnReduction":
cta_m = args.threadblock_shape[0]
num_cta_m = (problem_size.m() + cta_m - 1) // cta_m
reduction = np.zeros(shape=(args.batch * problem_size.n() * num_cta_m,), dtype=getattr(np, args.element_c))
output_op = operation.epilogue_type(
D=tensor_D, alpha=args.alpha, beta=args.beta, c=tensor_C, reduction=reduction, problem_size=[problem_size.m(), problem_size.n()]
)
elif args.epilogue_visitor == "RowBroadcast":
vector = np.ceil(
np.random.uniform(low=-8.5, high=7.5, size=(args.batch, 1, problem_size.n()))
).astype(getattr(np, args.element_c))
tensor_t = np.empty_like(tensor_D)
output_op = operation.epilogue_type(
c=tensor_C, vector=vector, alpha=args.alpha, beta=args.beta, Z=tensor_D, T=tensor_t, problem_size=[problem_size.m(), problem_size.n()]
)
elif args.epilogue_visitor == "ColumnBroadcast":
vector = np.ceil(
np.random.uniform(low=-8.5, high=7.5, size=(args.batch, problem_size.m(), 1))
).astype(getattr(np, args.element_c))
tensor_t = np.empty_like(tensor_D)
output_op = operation.epilogue_type(
c=tensor_C, vector=vector, alpha=args.alpha, beta=args.beta, Z=tensor_D, T=tensor_t, problem_size=[problem_size.m(), problem_size.n()]
)
else:
output_op = operation.epilogue_type(*([args.alpha, args.beta] + args.activation_args))
arguments = GemmArguments(
operation=operation, problem_size=problem_size,
A=tensor_A, B=tensor_B, C=tensor_C, D=tensor_D,
output_op=output_op,
gemm_mode=getattr(cutlass.gemm.Mode, args.gemm_mode),
split_k_slices=args.split_k_slices, batch=args.batch
)
if args.gemm_mode == "GemmSplitKParallel":
reduction_arguments = ReductionArguments(
operation=reduction_operation,
problem_size=[problem_size.m(), problem_size.n()],
partitions=args.split_k_slices, workspace=arguments.ptr_D,
destination=tensor_D, source=tensor_C,
output_op=reduction_operation.epilogue_type(*([args.alpha, args.beta] + args.activation_args)),
bias = arguments.bias
)
operation.run(arguments)
if args.gemm_mode == "GemmSplitKParallel":
reduction_operation.run(reduction_arguments)
reduction_arguments.sync()
else:
arguments.sync()
# run the host reference module
reference = ReferenceModule(A, B, C)
tensor_D_ref = reference.run(
tensor_A, tensor_B, tensor_C, problem_size, args.alpha, args.beta, args.bias, args.batch)
if args.epilogue_visitor in ["RowBroadcast", "ColumnBroadcast"]:
tensor_D_ref = (tensor_D_ref.reshape((args.batch, problem_size.m(), problem_size.n())) + vector).flatten()
tensor_D_ref = getattr(pycutlass, args.activation_function).numpy(*([tensor_D_ref,] + args.activation_args))
if args.epilogue_visitor in ["RowReduction", "ColumnReduction"]:
output_op.sync()
accum_ref = reference.run(
tensor_A, tensor_B, tensor_C, problem_size, 1.0, 0.0, args.bias, args.batch)
tensor_D_ref, reduction_ref = epilogue_functor(
accum_ref.reshape((args.batch, problem_size.m(), problem_size.n())),
tensor_C.reshape((args.batch, problem_size.m(), problem_size.n())),
args.alpha, args.beta
)
tensor_D_ref = tensor_D_ref.flatten()
reduction_ref = reduction_ref.flatten()
assert np.allclose(reduction_ref, reduction, atol=1e-2)
elif args.epilogue_visitor in ["RowBroadcast", "ColumnBroadcast"]:
output_op.sync()
accum_ref = reference.run(
tensor_A, tensor_B, tensor_C, problem_size, 1.0, 0.0, args.bias, args.batch)
tensor_D_ref, tensor_T_ref = epilogue_functor(
accum_ref.reshape((args.batch, problem_size.m(), problem_size.n())),
tensor_C.reshape((args.batch, problem_size.m(), problem_size.n())),
vector, args.alpha, args.beta)
tensor_D_ref = tensor_D_ref.flatten()
tensor_T_ref = tensor_T_ref.flatten()
assert np.array_equal(tensor_t, tensor_T_ref)
try:
assert np.array_equal(tensor_D, tensor_D_ref)
except:
assert np.allclose(tensor_D, tensor_D_ref, atol=1e-5)
print("Passed.")
| warp-main | warp/native/cutlass/examples/40_cutlass_py/customizable/gemm.py |
################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
################################################################################
import numpy as np
import pycutlass
from pycutlass import *
from pycutlass.conv2d_operation import *
from pycutlass.utils import reference_model
from pycutlass.utils.device import device_cc
import sys
import torch.nn.functional as F
import argparse
# parse the arguments
parser = argparse.ArgumentParser(description="Launch CUTLASS convolution 2d kernels from Python")
# Operation description
# math instruction description
parser.add_argument("-i", "--instruction_shape",
default=[1, 1, 1], nargs=3, type=int,
help="This option describes the size of MMA op")
parser.add_argument("-ta", "--element_a", default="float32", type=str,
choices=['float64', 'float32', 'float16', 'bfloat16', 'int32', 'int8'],
help='Data type of elements in input tensor A')
parser.add_argument("-tb", "--element_b", default="float32", type=str,
choices=['float64', 'float32', 'float16', 'bfloat16', 'int32', 'int8'],
help='Data type of elements in input tensor B')
parser.add_argument("-tc", "--element_c", default="float32", type=str,
choices=['float64', 'float32', 'float16', 'bfloat16', 'int32', 'int8'],
help='Data type of elements in input tensor C and output tensor D')
parser.add_argument("-tacc", "--element_acc", default="float32", type=str,
choices=['float64', 'float32', 'float16', 'bfloat16', 'int32', 'int8'],
help='Data type of accumulator')
parser.add_argument('-m', "--math", default="multiply_add",
type=str, choices=["multiply_add", "multiply_add_fast_bf16", "multiply_add_fast_f32"], help="math instruction")
parser.add_argument('-op', "--opcode", default="simt", type=str,
choices=["Simt", 'TensorOp'],
help='This option describes whether you want to use tensor \
cores (TensorOp) or regular SIMT cores (Simt) on GPU SM')
# tile description
parser.add_argument("-b", "--threadblock_shape",
default=[128, 128, 8], nargs=3, type=int,
help="This option describes the tile size a thread block with compute")
parser.add_argument("-s", "--stages", default=4,
type=int, help="Number of pipelines you want to use")
parser.add_argument("-w", "--warp_count", default=[
4, 2, 1], nargs=3, type=int,
help="This option describes the number of warps along M, N, and K of the threadblock")
parser.add_argument("-cc", "--compute_capability", default=80,
type=int, help="This option describes CUDA SM architecture number")
# A
parser.add_argument('-la', "--layout_a", default="TensorNHWC", type=str, choices=[
"TensorNHWC", "TensorNC32HW32"],
help="Memory layout of input tensor A")
parser.add_argument('-aa', '--alignment_a', default=1,
type=int, help="Memory alignement of input tensor A")
# B
parser.add_argument('-lb', "--layout_b", default="TensorNHWC", type=str, choices=[
"TensorNHWC", "TensorC32RSK32"],
help="Memory layout of input tensor B")
parser.add_argument('-ab', '--alignment_b', default=1,
type=int, help="Memory alignment of input tensor B")
# C
parser.add_argument('-lc', "--layout_c", default="TensorNHWC", type=str, choices=[
"TensorNHWC", "TensorNC32HW32"],
help="Memory layout of input tensor C and output tensor D")
parser.add_argument('-ac', '--alignment_c', default=1,
type=int, help="Memory alignment of input tensor C and output tensor D")
# epilogue
parser.add_argument("-te", "--element_epilogue", default="float32", type=str,
choices=['float64', 'float32', 'float16', 'bfloat16'],
help='Data type of computation in the epilogue')
parser.add_argument("-ep", "--epilogue_functor", default="LinearCombination",
type=str, choices=['LinearCombination', 'FastLinearCombinationClamp', 'LinearCombinationClamp'],
help="This option describes the epilogue part of the kernel")
# swizzling
parser.add_argument("-sw", "--swizzling_functor", default="IdentitySwizzle1", type=str, choices=[
"IdentitySwizzle1", "IdentitySwizzle2", "IdentitySwizzle4", "IdentitySwizzle8",
"HorizontalSwizzle", "StridedDgradIdentitySwizzle1", "StridedDgradIdentitySwizzle4",
"StridedDgradHorizontalSwizzle"],
help="This option describes how thread blocks are scheduled on GPU")
# conv related
parser.add_argument("-co", "--conv_kind", default="fprop", type=str, choices=['fprop', 'dgrad', 'wgrad'],
help="The type of convolution: forward propagation (fprop), \
gradient of activation (dgrad), gradient of weight (wgrad)")
parser.add_argument("-st", "--stride_support", default="Strided", type=str, choices=["Strided", "Unity"],
)
parser.add_argument("-ia", "--iterator_algorithm", default="analytic", type=str,
choices=["analytic", "optimized", "fixed_channels", "few_channels"],
help="This option describes iterator algorithm")
# arguments
parser.add_argument("-sm", "--split_k_mode", default="Serial", type=str, choices=["Serial", "Parallel"],
help="Split K Mode. Serial is used for non-splitK or serial-splitK.\
Parallel is used for parallel splitK.")
parser.add_argument('-k', '--split_k_slices', default=1,
type=int, help="Number of split-k partitions. (default 1)")
parser.add_argument("-nhwc", "--nhwc", nargs=4, type=int, help="input size (NHWC)")
parser.add_argument("-krsc", "--krsc", nargs=4, type=int, help="filter size (KRSC)")
parser.add_argument("-pad", "--pad", nargs=4, type=int, help="padding (pad_h, _, pad_w, _)")
parser.add_argument("-stride", "--stride", nargs=2, type=int, help="stride (stride_h, stride_w)")
parser.add_argument("-dilation", "--dilation", nargs=2, type=int, help="dilation (dilation_h, dilation_w)")
parser.add_argument("-alpha", "--alpha", default=1.0, type=float, help="alpha")
parser.add_argument("-beta", "--beta", default=0.0, type=float, help="beta")
parser.add_argument('-bias', '--bias', action='store_true', help="C is bias vector")
# Activation function
parser.add_argument("-activ", "--activation_function", default="identity",
choices=["identity", "relu", "leaky_relu", "tanh", "sigmoid", "silu", "hardswish", "gelu"], help="activation function")
parser.add_argument("-activ_arg", "--activation_args", default=[], nargs="+", type=float,
help="addition arguments for activation")
parser.add_argument('--print_cuda', action="store_true",
help="print the underlying CUDA kernel")
try:
args = parser.parse_args()
except:
sys.exit(0)
cc = device_cc()
if args.compute_capability != cc:
raise Exception(("Parameter --compute-capability of {} "
"does not match that of the device of {}.").format(args.compute_capability, cc))
pycutlass.get_memory_pool(init_pool_size=2**30, max_pool_size=2**32)
np.random.seed(0)
element_a = getattr(cutlass, args.element_a)
element_b = getattr(cutlass, args.element_b)
element_c = getattr(cutlass, args.element_c)
element_acc = getattr(cutlass, args.element_acc)
math_operation = getattr(MathOperation, args.math)
opclass = getattr(cutlass.OpClass, args.opcode)
math_inst = MathInstruction(
args.instruction_shape, element_a, element_b,
element_acc, opclass, math_operation
)
tile_description = TileDescription(
args.threadblock_shape, args.stages, args.warp_count,
math_inst
)
layout_a = getattr(cutlass, args.layout_a)
layout_b = getattr(cutlass, args.layout_b)
layout_c = getattr(cutlass, args.layout_c)
A = TensorDescription(
element_a, layout_a, args.alignment_a
)
B = TensorDescription(
element_b, layout_b, args.alignment_b
)
C = TensorDescription(
element_c, layout_c, args.alignment_c
)
element_epilogue = getattr(cutlass, args.element_epilogue)
if (args.activation_function == "identity"
or (args.split_k_mode == "Parallel" and args.split_k_slices > 1)):
#
epilogue_functor = getattr(pycutlass, args.epilogue_functor)(
C.element, C.alignment, math_inst.element_accumulator, element_epilogue)
else:
epilogue_functor = getattr(pycutlass, "LinearCombinationGeneric")(
getattr(pycutlass, args.activation_function)(element_epilogue),
C.element, C.alignment, math_inst.element_accumulator, element_epilogue)
iterator_algorithm = getattr(cutlass.conv.IteratorAlgorithm, args.iterator_algorithm)
swizzling_functor = getattr(cutlass, args.swizzling_functor)
stride_support = getattr(StrideSupport, args.stride_support)
conv_kind = getattr(cutlass.conv.Operator, args.conv_kind)
operation = Conv2dOperation(
conv_kind=conv_kind, iterator_algorithm=iterator_algorithm,
arch=args.compute_capability, tile_description=tile_description,
A=A, B=B, C=C, stride_support=stride_support,
epilogue_functor=epilogue_functor, swizzling_functor=swizzling_functor
)
if args.print_cuda:
print(operation.rt_module.emit())
operations = [operation,]
if args.split_k_mode == "Parallel" and args.split_k_slices > 1:
if (args.activation_function == "identity"):
epilogue_functor_reduction = getattr(pycutlass, args.epilogue_functor)(
C.element, C.alignment, math_inst.element_accumulator, element_epilogue)
else:
epilogue_functor_reduction = getattr(pycutlass, "LinearCombinationGeneric")(
getattr(pycutlass, args.activation_function)(element_epilogue),
C.element, C.alignment, math_inst.element_accumulator, element_epilogue)
reduction_operation = ReductionOperation(
shape=cutlass.MatrixCoord(4, 32 * C.alignment),
C=C, element_accumulator=element_acc,
element_compute=element_epilogue,
epilogue_functor=epilogue_functor_reduction,
count=C.alignment
)
operations.append(reduction_operation)
pycutlass.compiler.add_module(operations)
problem_size = cutlass.conv.Conv2dProblemSize(
cutlass.Tensor4DCoord(args.nhwc[0], args.nhwc[1], args.nhwc[2], args.nhwc[3]),
cutlass.Tensor4DCoord(args.krsc[0], args.krsc[1], args.krsc[2], args.krsc[3]),
cutlass.Tensor4DCoord(args.pad[0], args.pad[1], args.pad[2], args.pad[3]),
cutlass.MatrixCoord(args.stride[0], args.stride[1]),
cutlass.MatrixCoord(args.dilation[0], args.dilation[1]),
cutlass.conv.Mode.cross_correlation,
args.split_k_slices, 1
)
# User-provide inputs
tensor_A_size = cutlass.conv.implicit_gemm_tensor_a_size(
conv_kind, problem_size
)
tensor_B_size = cutlass.conv.implicit_gemm_tensor_b_size(
conv_kind, problem_size
)
if args.bias:
tensor_C_size = cutlass.conv.implicit_gemm_tensor_c_extent(
conv_kind, problem_size
).at(3)
else:
tensor_C_size = cutlass.conv.implicit_gemm_tensor_c_size(
conv_kind, problem_size
)
tensor_D_size = cutlass.conv.implicit_gemm_tensor_c_size(
conv_kind, problem_size
)
if args.element_a != "int8":
tensor_A = torch.ceil(torch.empty(size=(tensor_A_size,), dtype=getattr(torch, args.element_a), device="cuda").uniform_(-8.5, 7.5))
else:
tensor_A = torch.empty(size=(tensor_A_size,), dtype=getattr(torch, args.element_a), device="cuda").uniform_(-2, 2)
if args.element_b != "int8":
tensor_B = torch.ceil(torch.empty(size=(tensor_B_size,), dtype=getattr(torch, args.element_b), device="cuda").uniform_(-8.5, 7.5))
else:
tensor_B = torch.empty(size=(tensor_B_size,), dtype=getattr(torch, args.element_b), device="cuda").uniform_(-2, 2)
if args.element_c != "int8":
tensor_C = torch.ceil(torch.empty(size=(tensor_C_size,), dtype=getattr(torch, args.element_c), device="cuda").uniform_(-8.5, 7.5))
else:
tensor_C = torch.empty(size=(tensor_C_size,), dtype=getattr(torch, args.element_c), device="cuda").uniform_(-2, 2)
tensor_D = torch.ones(size=(tensor_D_size,), dtype=getattr(torch, args.element_c), device="cuda")
arguments = Conv2dArguments(
operation=operation, problem_size=problem_size, A=tensor_A,
B=tensor_B, C=tensor_C, D=tensor_D,
output_op = operation.epilogue_type(*([args.alpha, args.beta] + args.activation_args)),
split_k_mode=getattr(cutlass.conv.SplitKMode, args.split_k_mode),
split_k_slices=problem_size.split_k_slices
)
if args.split_k_mode == "Parallel" and args.split_k_slices > 1:
implicit_gemm_size = cutlass.conv.implicit_gemm_problem_size(conv_kind, arguments.problem_size)
reduction_arguments = ReductionArguments(
reduction_operation,
problem_size=[implicit_gemm_size.m(), implicit_gemm_size.n()],
partitions=problem_size.split_k_slices,
workspace=arguments.ptr_D,
destination=tensor_D,
source=tensor_C,
output_op = reduction_operation.epilogue_type(*([args.alpha, args.beta] + args.activation_args)),
bias = arguments.bias
)
operation.run(arguments)
if args.split_k_mode == "Parallel" and args.split_k_slices > 1:
reduction_operation.run(reduction_arguments)
reduction_arguments.sync()
else:
arguments.sync()
reference_model = Conv2dReferenceModule(A, B, C, conv_kind)
tensor_D_ref = reference_model.run(tensor_A, tensor_B, tensor_C, arguments.problem_size, args.alpha, args.beta, args.bias)
if (args.activation_function != "identity"):
tensor_D_ref = getattr(F, args.activation_function)(*([tensor_D_ref,] + args.activation_args))
try:
assert torch.equal(tensor_D, tensor_D_ref)
except:
assert torch.allclose(tensor_D, tensor_D_ref, rtol=1e-2)
print("Passed.")
| warp-main | warp/native/cutlass/examples/40_cutlass_py/customizable/conv2d.py |
################################################################################
#
# Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
################################################################################
import numpy as np
import pycutlass
from pycutlass import *
from pycutlass.utils.device import device_cc
import csv
import sys
import argparse
# parse the arguments
parser = argparse.ArgumentParser(
description="Launch CUTLASS GEMM Grouped kernels from Python")
# Operation description
# math instruction description
parser.add_argument("-i", "--instruction_shape",
default=[1, 1, 1], nargs=3, type=int,
help="This option describes the size of MMA op")
parser.add_argument("-ta", "--element_a", default="float32", type=str,
choices=['float64', 'float32', 'float16', 'bfloat16', 'int32', 'int8'],
help='Data type of elements in input tensor A')
parser.add_argument("-tb", "--element_b", default="float32", type=str,
choices=['float64', 'float32', 'float16', 'bfloat16', 'int32', 'int8'],
help='Data type of elements in input tensor B')
parser.add_argument("-tc", "--element_c", default="float32", type=str,
choices=['float64', 'float32', 'float16', 'bfloat16', 'int32', 'int8'],
help='Data type of elements in input tensor C and output tensor D')
parser.add_argument("-tacc", "--element_acc", default="float32", type=str,
choices=['float64', 'float32', 'float16', 'bfloat16', 'int32', 'int8'],
help='Data type of accumulator')
parser.add_argument('-m', "--math", default="multiply_add",
type=str, choices=["multiply_add", "multiply_add_fast_bf16", "multiply_add_fast_f32"], help="math instruction")
parser.add_argument('-op', "--opcode", default="simt", type=str,
choices=["Simt", 'TensorOp'], help='This option describes whether you want to use tensor \
cores (TensorOp) or regular SIMT cores (Simt) on GPU SM')
# tile description
parser.add_argument("-b", "--threadblock_shape",
default=[128, 128, 8], nargs=3, type=int,
help="This option describes the tile size a thread block with compute")
parser.add_argument("-s", "--stages", default=4,
type=int, help="Number of pipelines you want to use")
parser.add_argument("-w", "--warp_count", default=[
4, 2, 1], nargs=3, type=int,
help="This option describes the number of warps along M, N, and K of the threadblock")
parser.add_argument("-cc", "--compute_capability", default=80,
type=int, help="This option describes CUDA SM architecture number")
# A
parser.add_argument('-la', "--layout_a", default="RowMajor", type=str, choices=[
"RowMajor", "ColumnMajor", "RowMajorInterleaved32", "ColumnMajorInterleaved32"],
help="Memory layout of input tensor A")
parser.add_argument('-aa', '--alignment_a', default=1,
type=int, help="Memory alignment of input tensor A")
# B
parser.add_argument('-lb', "--layout_b", default="RowMajor", type=str, choices=[
"RowMajor", "ColumnMajor", "RowMajorInterleaved32", "ColumnMajorInterleaved32"],
help="Memory layout of input tensor B")
parser.add_argument('-ab', '--alignment_b', default=1,
type=int, help="Memory alignment of input tensor B")
# C
parser.add_argument('-lc', "--layout_c", default="RowMajor", type=str, choices=[
"RowMajor", "ColumnMajor", "RowMajorInterleaved32", "ColumnMajorInterleaved32"],
help="Memory layout of input tensor C and output tensor D")
parser.add_argument('-ac', '--alignment_c', default=1,
type=int, help="Memory alignment of input tensor C and output tensor D")
# epilogue
parser.add_argument("-te", "--element_epilogue", default="float32", type=str,
choices=['float64', 'float32', 'float16', 'bfloat16'], help='Epilogue datatype')
parser.add_argument("-ep", "--epilogue_functor", default="LinearCombination",
type=str, choices=['LinearCombination', 'FastLinearCombinationClamp', 'LinearCombinationClamp'],
help="This option describes the epilogue part of the kernel")
# swizzling
parser.add_argument("-sw", "--swizzling_functor", default="IdentitySwizzle1", type=str, choices=[
"IdentitySwizzle1", "IdentitySwizzle2", "IdentitySwizzle4", "IdentitySwizzle8", "HorizontalSwizzle"],
help="This option describes how thread blocks are scheduled on GPU. \
NOTE: Threadblock swizzling is currently not supported by CUTLASS's grouped kernels. \
This parameter is passed in at present to match the APIs of other kernels. The parameter \
is unused within the kernel")
# precompute mode
parser.add_argument("-pm", "--precompute_mode",
default="Device", type=str, choices=["Host", "Device"],
help="Grouped Gemm Scheduing on device only (Device) or using host precompute (Host)")
# arguments
parser.add_argument("-p", "--problem_size_dir", type=str,
help="path to the csv file contains the problem sizes")
parser.add_argument("-alpha", "--alpha", default=1.0, type=float, help="alpha")
parser.add_argument("-beta", "--beta", default=0.0, type=float, help="beta")
parser.add_argument('-bias', '--bias', action='store_true', help="C is bias vector")
# Activation function
parser.add_argument("-activ", "--activation_function", default="identity",
choices=["identity", "relu", "leaky_relu", "tanh", "sigmoid", "silu", "hardswish", "gelu"], help="activation function")
parser.add_argument("-activ_arg", "--activation_args", default=[], nargs="+", type=float,
help="addition arguments for activation")
parser.add_argument('--print_cuda', action="store_true",
help="print the underlying CUDA kernel")
try:
args = parser.parse_args()
except:
sys.exit(0)
cc = device_cc()
if args.compute_capability != cc:
raise Exception(("Parameter --compute-capability of {} "
"does not match that of the device of {}.").format(args.compute_capability, cc))
pycutlass.get_memory_pool(init_pool_size=2**30, max_pool_size=2**32)
np.random.seed(0)
element_a = getattr(cutlass, args.element_a)
element_b = getattr(cutlass, args.element_b)
element_c = getattr(cutlass, args.element_c)
element_acc = getattr(cutlass, args.element_acc)
math_operation = getattr(MathOperation, args.math)
opclass = getattr(cutlass.OpClass, args.opcode)
math_inst = MathInstruction(
args.instruction_shape, element_a, element_b,
element_acc, opclass, math_operation
)
tile_description = TileDescription(
args.threadblock_shape, args.stages, args.warp_count,
math_inst
)
layout_a = getattr(cutlass, args.layout_a)
layout_b = getattr(cutlass, args.layout_b)
layout_c = getattr(cutlass, args.layout_c)
A = TensorDescription(
element_a, layout_a, args.alignment_a
)
B = TensorDescription(
element_b, layout_b, args.alignment_b
)
C = TensorDescription(
element_c, layout_c, args.alignment_c
)
element_epilogue = getattr(cutlass, args.element_epilogue)
if args.activation_function == "identity":
epilogue_functor = getattr(pycutlass, args.epilogue_functor)(
C.element, C.alignment, math_inst.element_accumulator, element_epilogue)
else:
epilogue_functor = getattr(pycutlass, "LinearCombinationGeneric")(
getattr(pycutlass, args.activation_function)(element_epilogue),
C.element, C.alignment, math_inst.element_accumulator, element_epilogue)
swizzling_functor = getattr(cutlass, args.swizzling_functor)
precompute_mode = getattr(SchedulerMode, args.precompute_mode)
operation = GemmOperationGrouped(
arch=args.compute_capability, tile_description=tile_description,
A=A, B=B, C=C,
epilogue_functor=epilogue_functor, swizzling_functor=swizzling_functor,
precompute_mode=precompute_mode
)
if args.print_cuda:
print(operation.rt_module.emit())
pycutlass.compiler.add_module([operation, ])
reference_module = ReferenceModule(A, B, C)
# get problems
problem_sizes = []
with open(args.problem_size_dir) as csv_file:
reader = csv.reader(csv_file)
for row in reader:
problem_sizes.append(
cutlass.gemm.GemmCoord(int(row[0]), int(row[1]), int(row[2]))
)
problem_count = len(problem_sizes)
tensor_As = []
tensor_Bs = []
tensor_Cs = []
tensor_Ds = []
problem_sizes_coord = []
tensor_D_refs = []
for problem_size in problem_sizes:
if args.element_a != "int8":
if args.element_a == "bfloat16":
tensor_A = np.ceil(np.random.uniform(low=-8.5, high=7.5, size=(problem_size.m()
* problem_size.k(),))).astype(bfloat16)
else:
tensor_A = np.ceil(np.random.uniform(low=-8.5, high=7.5, size=(problem_size.m()
* problem_size.k(),))).astype(getattr(np, args.element_a))
else:
tensor_A = np.random.uniform(low=-2, high=2, size=(problem_size.m()
* problem_size.k(),)).astype(getattr(np, args.element_a))
if args.element_b != "int8":
if args.element_b == "bfloat16":
tensor_B = np.ceil(np.random.uniform(low=-8.5, high=7.5, size=(problem_size.k()
* problem_size.n(),))).astype(bfloat16)
else:
tensor_B = np.ceil(np.random.uniform(low=-8.5, high=7.5, size=(problem_size.k()
* problem_size.n(),))).astype(getattr(np, args.element_b))
else:
tensor_B = np.random.uniform(low=-2, high=2, size=(problem_size.k()
* problem_size.n(),)).astype(getattr(np, args.element_b))
if args.element_c != "int8":
if args.bias:
if args.layout_c == "RowMajor":
c_size = problem_size.n()
elif args.layout_c == "ColumnMajor":
c_size = problem_size.m()
else:
raise ValueError(args.layout_c)
else:
c_size = problem_size.m() * problem_size.n()
if args.element_c == "bfloat16":
tensor_C = np.ceil(
np.random.uniform(low=-8.5, high=7.5, size=(c_size,))
).astype(bfloat16)
else:
tensor_C = np.ceil(
np.random.uniform(low=-8.5, high=7.5, size=(c_size,))
).astype(getattr(np, args.element_c))
else:
tensor_C = np.random.uniform(
low=-2, high=2, size=(problem_size.m() * problem_size.n(),)
).astype(getattr(np, args.element_c))
tensor_D = np.zeros(
shape=(problem_size.m() * problem_size.n(),)
).astype(getattr(np, args.element_c))
tensor_As.append(tensor_A)
tensor_Bs.append(tensor_B)
tensor_Cs.append(tensor_C)
tensor_Ds.append(tensor_D)
tensor_D_ref = reference_module.run(
tensor_A, tensor_B, tensor_C, problem_size,
args.alpha, args.beta, args.bias)
tensor_D_ref = getattr(pycutlass, args.activation_function).numpy(*([tensor_D_ref,] + args.activation_args))
tensor_D_refs.append(tensor_D_ref)
problem_sizes_coord.append(problem_size)
arguments = GemmGroupedArguments(
operation, problem_sizes_coord, tensor_As, tensor_Bs, tensor_Cs, tensor_Ds,
output_op=operation.epilogue_type(*([args.alpha, args.beta] + args.activation_args))
)
operation.run(arguments)
arguments.sync()
for tensor_d, tensor_d_ref in zip(tensor_Ds, tensor_D_refs):
try:
assert np.array_equal(tensor_d, tensor_d_ref)
except:
assert np.allclose(tensor_d, tensor_d_ref, rtol=1e-5)
print("Passed.")
| warp-main | warp/native/cutlass/examples/40_cutlass_py/customizable/gemm_grouped.py |
from typing import Any, Optional
import warp as wp
from warp.types import type_length, type_is_matrix
from warp.sparse import BsrMatrix, bsr_copy, bsr_mv, bsr_mm, bsr_assign, bsr_axpy
from .utils import array_axpy
def normalize_dirichlet_projector(projector_matrix: BsrMatrix, fixed_value: Optional[wp.array] = None):
"""
Scale projector so that it becomes idempotent, and apply the same scaling to fixed_value if provided
"""
if projector_matrix.nrow < projector_matrix.nnz or projector_matrix.ncol != projector_matrix.nrow:
raise ValueError("Projector must be a square diagonal matrix, with at most one non-zero block per row")
# Cast blocks to matrix type if necessary
projector_values = projector_matrix.values
if not type_is_matrix(projector_values.dtype):
projector_values = wp.array(
data=None,
ptr=projector_values.ptr,
capacity=projector_values.capacity,
owner=False,
device=projector_values.device,
dtype=wp.mat(shape=projector_matrix.block_shape, dtype=projector_matrix.scalar_type),
shape=projector_values.shape[0],
)
if fixed_value is None:
wp.launch(
kernel=_normalize_dirichlet_projector_kernel,
dim=projector_matrix.nrow,
device=projector_values.device,
inputs=[projector_matrix.offsets, projector_matrix.columns, projector_values],
)
else:
if fixed_value.shape[0] != projector_matrix.nrow:
raise ValueError("Fixed value array must be of length equal to the number of rows of blocks")
if type_length(fixed_value.dtype) == 1:
# array of scalars, convert to 1d array of vectors
fixed_value = wp.array(
data=None,
ptr=fixed_value.ptr,
capacity=fixed_value.capacity,
owner=False,
device=fixed_value.device,
dtype=wp.vec(length=projector_matrix.block_shape[0], dtype=projector_matrix.scalar_type),
shape=fixed_value.shape[0],
)
wp.launch(
kernel=_normalize_dirichlet_projector_and_values_kernel,
dim=projector_matrix.nrow,
device=projector_values.device,
inputs=[projector_matrix.offsets, projector_matrix.columns, projector_values, fixed_value],
)
def project_system_rhs(
system_matrix: BsrMatrix, system_rhs: wp.array, projector_matrix: BsrMatrix, fixed_value: wp.array
):
"""Projects the right-hand-side of a linear system to enforce Dirichlet boundary conditions
``rhs = (I - projector) * ( rhs - system * projector * fixed_value) + projector * fixed_value``
"""
rhs_tmp = wp.empty_like(system_rhs)
rhs_tmp.assign(system_rhs)
bsr_mv(A=projector_matrix, x=fixed_value, y=system_rhs, alpha=1.0, beta=0.0)
bsr_mv(A=system_matrix, x=system_rhs, y=rhs_tmp, alpha=-1.0, beta=1.0)
# here rhs_tmp = system_rhs - system_matrix * projector * fixed_value
# system_rhs = projector * fixed_value
array_axpy(x=rhs_tmp, y=system_rhs, alpha=1.0, beta=1.0)
bsr_mv(A=projector_matrix, x=rhs_tmp, y=system_rhs, alpha=-1.0, beta=1.0)
def project_system_matrix(system_matrix: BsrMatrix, projector_matrix: BsrMatrix):
"""Projects the right-hand-side of a linear system to enforce Dirichlet boundary conditions
``system = (I - projector) * system * (I - projector) + projector``
"""
complement_system = bsr_copy(system_matrix)
bsr_mm(x=projector_matrix, y=system_matrix, z=complement_system, alpha=-1.0, beta=1.0)
bsr_assign(dest=system_matrix, src=complement_system)
bsr_axpy(x=projector_matrix, y=system_matrix)
bsr_mm(x=complement_system, y=projector_matrix, z=system_matrix, alpha=-1.0, beta=1.0)
def project_linear_system(
system_matrix: BsrMatrix,
system_rhs: wp.array,
projector_matrix: BsrMatrix,
fixed_value: wp.array,
normalize_projector=True,
):
"""
Projects both the left-hand-side and right-hand-side of a linear system to enforce Dirichlet boundary conditions
If normalize_projector is True, first apply scaling so that the projector_matrix is idempotent
"""
if normalize_projector:
normalize_dirichlet_projector(projector_matrix, fixed_value)
project_system_rhs(system_matrix, system_rhs, projector_matrix, fixed_value)
project_system_matrix(system_matrix, projector_matrix)
@wp.kernel
def _normalize_dirichlet_projector_kernel(
offsets: wp.array(dtype=int),
columns: wp.array(dtype=int),
block_values: wp.array(dtype=Any),
):
row = wp.tid()
beg = offsets[row]
end = offsets[row + 1]
if beg == end:
return
diag = wp.lower_bound(columns, beg, end, row)
if diag < end and columns[diag] == row:
P = block_values[diag]
P_sq = P * P
trace_P = wp.trace(P)
trace_P_sq = wp.trace(P_sq)
if wp.nonzero(trace_P_sq):
scale = trace_P / trace_P_sq
block_values[diag] = scale * P
else:
block_values[diag] = P - P
@wp.kernel
def _normalize_dirichlet_projector_and_values_kernel(
offsets: wp.array(dtype=int),
columns: wp.array(dtype=int),
block_values: wp.array(dtype=Any),
fixed_values: wp.array(dtype=Any),
):
row = wp.tid()
beg = offsets[row]
end = offsets[row + 1]
if beg == end:
return
diag = wp.lower_bound(columns, beg, end, row)
if diag < end and columns[diag] == row:
P = block_values[diag]
P_sq = P * P
trace_P = wp.trace(P)
trace_P_sq = wp.trace(P_sq)
if wp.nonzero(trace_P_sq):
scale = trace_P / trace_P_sq
block_values[diag] = scale * P
fixed_values[row] = scale * fixed_values[row]
else:
block_values[diag] = P - P
fixed_values[row] = fixed_values[row] - fixed_values[row]
| warp-main | warp/fem/dirichlet.py |
from typing import Union
from enum import Enum
import warp as wp
import warp.codegen
import warp.context
from warp.fem.geometry import (
Element,
Geometry,
GeometryPartition,
WholeGeometryPartition,
)
GeometryOrPartition = Union[Geometry, GeometryPartition]
class GeometryDomain:
"""Interface class for domains, i.e. (partial) views of elements in a Geometry"""
class ElementKind(Enum):
"""Possible kinds of elements contained in a domain"""
CELL = 0
SIDE = 1
def __init__(self, geometry: GeometryOrPartition):
if isinstance(geometry, GeometryPartition):
self.geometry_partition = geometry
else:
self.geometry_partition = WholeGeometryPartition(geometry)
self.geometry = self.geometry_partition.geometry
@property
def name(self) -> str:
return f"{self.geometry_partition.name}_{self.__class__.__name__}"
def __str__(self) -> str:
return self.name
def __eq__(self, other) -> bool:
return self.__class__ == other.__class__ and self.geometry_partition == other.geometry_partition
@property
def element_kind(self) -> ElementKind:
"""Kind of elements that this domain contains (cells or sides)"""
raise NotImplementedError
def dimension(self) -> int:
"""Dimension of the elements of the domain"""
raise NotImplementedError
def element_count(self) -> int:
"""Number of elements in the domain"""
raise NotImplementedError
def geometry_element_count(self) -> int:
"""Number of elements in the underlying geometry"""
return self.geometry.cell_count()
def reference_element(self) -> Element:
"""Protypical element"""
raise NotImplementedError
def element_index_arg_value(self, device: warp.context.Devicelike) -> warp.codegen.StructInstance:
"""Value of the argument to be passed to device functions"""
raise NotImplementedError
def element_arg_value(self, device: warp.context.Devicelike) -> warp.codegen.StructInstance:
"""Value of the argument to be passed to device functions"""
raise NotImplementedError
ElementIndexArg: warp.codegen.Struct
"""Structure containing arguments to be passed to device functions computing element indices"""
element_index: wp.Function
"""Device function for retrieving an ElementIndex from a linearized index"""
ElementArg: warp.codegen.Struct
"""Structure containing arguments to be passed to device functions computing element geometry"""
element_measure: wp.Function
"""Device function returning the measure determinant (e.g. volume, area) at a given point"""
element_measure_ratio: wp.Function
"""Device function returning the ratio of the measure of a side to that of its neighbour cells"""
element_position: wp.Function
"""Device function returning the element position at a sample point"""
element_normal: wp.Function
"""Device function returning the element normal at a sample point"""
element_lookup: wp.Function
"""Device function returning the sample point corresponding to a world position"""
class Cells(GeometryDomain):
"""A Domain containing all cells of the geometry or geometry partition"""
def __init__(self, geometry: GeometryOrPartition):
super().__init__(geometry)
@property
def element_kind(self) -> GeometryDomain.ElementKind:
return GeometryDomain.ElementKind.CELL
def dimension(self) -> int:
return self.geometry.dimension
def reference_element(self) -> Element:
return self.geometry.reference_cell()
def element_count(self) -> int:
return self.geometry_partition.cell_count()
def geometry_element_count(self) -> int:
return self.geometry.cell_count()
@property
def ElementIndexArg(self) -> warp.codegen.Struct:
return self.geometry_partition.CellArg
def element_index_arg_value(self, device: warp.context.Devicelike) -> warp.codegen.StructInstance:
return self.geometry_partition.cell_arg_value(device)
@property
def element_index(self) -> wp.Function:
return self.geometry_partition.cell_index
def element_arg_value(self, device: warp.context.Devicelike) -> warp.codegen.StructInstance:
return self.geometry.cell_arg_value(device)
@property
def ElementArg(self) -> warp.codegen.Struct:
return self.geometry.CellArg
@property
def element_position(self) -> wp.Function:
return self.geometry.cell_position
@property
def element_measure(self) -> wp.Function:
return self.geometry.cell_measure
@property
def element_measure_ratio(self) -> wp.Function:
return self.geometry.cell_measure_ratio
@property
def eval_normal(self) -> wp.Function:
return self.geometry.cell_normal
@property
def element_lookup(self) -> wp.Function:
return self.geometry.cell_lookup
class Sides(GeometryDomain):
"""A Domain containing all (interior and boundary) sides of the geometry or geometry partition"""
def __init__(self, geometry: GeometryOrPartition):
self.geometry = geometry
super().__init__(geometry)
@property
def element_kind(self) -> GeometryDomain.ElementKind:
return GeometryDomain.ElementKind.SIDE
def dimension(self) -> int:
return self.geometry.dimension - 1
def reference_element(self) -> Element:
return self.geometry.reference_side()
def element_count(self) -> int:
return self.geometry_partition.side_count()
def geometry_element_count(self) -> int:
return self.geometry.side_count()
@property
def ElementIndexArg(self) -> warp.codegen.Struct:
return self.geometry_partition.SideArg
def element_index_arg_value(self, device: warp.context.Devicelike) -> warp.codegen.StructInstance:
return self.geometry_partition.side_arg_value(device)
@property
def element_index(self) -> wp.Function:
return self.geometry_partition.side_index
@property
def ElementArg(self) -> warp.codegen.Struct:
return self.geometry.SideArg
def element_arg_value(self, device: warp.context.Devicelike) -> warp.codegen.StructInstance:
return self.geometry.side_arg_value(device)
@property
def element_position(self) -> wp.Function:
return self.geometry.side_position
@property
def element_measure(self) -> wp.Function:
return self.geometry.side_measure
@property
def element_measure_ratio(self) -> wp.Function:
return self.geometry.side_measure_ratio
@property
def eval_normal(self) -> wp.Function:
return self.geometry.side_normal
class BoundarySides(Sides):
"""A Domain containing boundary sides of the geometry or geometry partition"""
def __init__(self, geometry: GeometryOrPartition):
super().__init__(geometry)
def element_count(self) -> int:
return self.geometry_partition.boundary_side_count()
def geometry_element_count(self) -> int:
return self.geometry.boundary_side_count()
@property
def element_index(self) -> wp.Function:
return self.geometry_partition.boundary_side_index
class FrontierSides(Sides):
"""A Domain containing frontier sides of the geometry partition (sides shared with at least another partition)"""
def __init__(self, geometry: GeometryOrPartition):
super().__init__(geometry)
def element_count(self) -> int:
return self.geometry_partition.frontier_side_count()
def geometry_element_count(self) -> int:
raise RuntimeError("Frontier sides not defined at the geometry level")
@property
def element_index(self) -> wp.Function:
return self.geometry_partition.frontier_side_index
| warp-main | warp/fem/domain.py |
import inspect
from typing import Callable, Any
import warp as wp
from warp.fem.types import Domain, Field, Sample
from warp.fem import utils
class Integrand:
"""An integrand is a device function containing arbitrary expressions over Field and Domain variables.
It will get transformed to a proper warp.Function by resolving concrete Field types at call time.
"""
def __init__(self, func: Callable):
self.func = func
self.name = wp.codegen.make_full_qualified_name(self.func)
self.module = wp.get_module(self.func.__module__)
self.argspec = inspect.getfullargspec(self.func)
class Operator:
"""
Operators provide syntaxic sugar over Field and Domain evaluation functions and arguments
"""
def __init__(self, func: Callable, resolver: Callable):
self.func = func
self.resolver = resolver
def integrand(func: Callable):
"""Decorator for functions to be integrated (or interpolated) using warp.fem"""
itg = Integrand(func)
itg.__doc__ = func.__doc__
return itg
def operator(resolver: Callable):
"""Decorator for functions operating on Field-like or Domain-like data inside warp.fem integrands"""
def wrap_operator(func: Callable):
op = Operator(func, resolver)
op.__doc__ = func.__doc__
return op
return wrap_operator
# Domain operators
@operator(resolver=lambda dmn: dmn.element_position)
def position(domain: Domain, x: Sample):
"""Evaluates the world position of the sample point x"""
pass
@operator(resolver=lambda dmn: dmn.eval_normal)
def normal(domain: Domain, x: Sample):
"""Evaluates the element normal at the sample point x. Null for interior points."""
pass
@operator(resolver=lambda dmn: dmn.element_lookup)
def lookup(domain: Domain, x: Any):
"""Look-ups a sample point from a world position, projecting to the closest point on the domain"""
pass
@operator(resolver=lambda dmn: dmn.element_measure)
def measure(domain: Domain, sample: Sample):
"""Returns the measure (volume, area, or length) of an element"""
pass
@operator(resolver=lambda dmn: dmn.element_measure_ratio)
def measure_ratio(domain: Domain, sample: Sample):
"""Returns the maximum ratio between the measure of this element and that of higher-dimensional neighbours."""
pass
# Field operators
# On a side, inner and outer are such that normal goes from inner to outer
@operator(resolver=lambda f: f.eval_inner)
def inner(f: Field, x: Sample):
"""Evaluates the field at a sample point x. On oriented sides, use the inner element"""
pass
@operator(resolver=lambda f: f.eval_grad_inner)
def grad(f: Field, x: Sample):
"""Evaluates the field gradient at a sample point x. On oriented sides, use the inner element"""
pass
@operator(resolver=lambda f: f.eval_outer)
def outer(f: Field, x: Sample):
"""Evaluates the field at a sample point x. On oriented sides, use the outer element. On interior points and on domain boundaries, this is equivalent to inner."""
pass
@operator(resolver=lambda f: f.eval_grad_outer)
def grad_outer(f: Field, x: Sample):
"""Evaluates the field gradient at a sample point x. On oriented sides, use the outer element. On interior points and on domain boundaries, this is equivalent to grad."""
pass
@operator(resolver=lambda f: f.eval_degree)
def degree(f: Field):
"""Polynomial degree of a field"""
pass
@operator(resolver=lambda f: f.at_node)
def at_node(f: Field, s: Sample):
"""For a Test or Trial field, returns a copy of the Sample `s` moved to the coordinates of the node being evaluated"""
pass
# Common derived operators, for convenience
@integrand
def D(f: Field, x: Sample):
"""Symmetric part of the (inner) gradient of the field at x"""
return utils.symmetric_part(grad(f, x))
@integrand
def div(f: Field, x: Sample):
"""(Inner) divergence of the field at x"""
return wp.trace(grad(f, x))
@integrand
def jump(f: Field, x: Sample):
"""Jump between inner and outer element values on an interior side. Zero for interior points or domain boundaries"""
return inner(f, x) - outer(f, x)
@integrand
def average(f: Field, x: Sample):
"""Average between inner and outer element values"""
return 0.5 * (inner(f, x) + outer(f, x))
@integrand
def grad_jump(f: Field, x: Sample):
"""Jump between inner and outer element gradients on an interior side. Zero for interior points or domain boundaries"""
return grad(f, x) - grad_outer(f, x)
@integrand
def grad_average(f: Field, x: Sample):
"""Average between inner and outer element gradients"""
return 0.5 * (grad(f, x) + grad_outer(f, x))
# Set default call operators for argument types, so that field(s) = inner(field, s) and domain(s) = position(domain, s)
Field.call_operator = inner
Domain.call_operator = position
| warp-main | warp/fem/operator.py |
from typing import Callable, Optional
import warp as wp
from warp.fem.operator import Integrand
import re
_kernel_cache = dict()
_struct_cache = dict()
_func_cache = dict()
_key_re = re.compile("[^0-9a-zA-Z_]+")
def get_func(func, suffix=""):
key = f"{func.__name__}_{suffix}"
key = _key_re.sub("", key)
if key not in _func_cache:
_func_cache[key] = wp.Function(
func=func,
key=key,
namespace="",
module=wp.get_module(
func.__module__,
),
)
return _func_cache[key]
def get_kernel(func, suffix=""):
module = wp.get_module(func.__module__)
key = func.__name__ + "_" + suffix
key = _key_re.sub("", key)
if key not in _kernel_cache:
_kernel_cache[key] = wp.Kernel(func=func, key=key, module=module)
return _kernel_cache[key]
def get_struct(Fields):
module = wp.get_module(Fields.__module__)
key = _key_re.sub("", Fields.__qualname__)
if key not in _struct_cache:
_struct_cache[key] = wp.codegen.Struct(
cls=Fields,
key=key,
module=module,
)
return _struct_cache[key]
def get_integrand_function(
integrand: Integrand,
suffix: str,
annotations=None,
code_transformers=[],
):
key = integrand.name + suffix
key = _key_re.sub("", key)
if key not in _func_cache:
_func_cache[key] = wp.Function(
func=integrand.func,
key=key,
namespace="",
module=integrand.module,
overloaded_annotations=annotations,
code_transformers=code_transformers,
)
return _func_cache[key]
def get_integrand_kernel(
integrand: Integrand,
suffix: str,
kernel_fn: Optional[Callable] = None,
code_transformers=[],
):
module = wp.get_module(f"{integrand.module.name}.{integrand.name}")
module.options = integrand.module.options
key = integrand.name + "_" + suffix
key = _key_re.sub("", key)
if key not in _kernel_cache:
if kernel_fn is None:
return None
_kernel_cache[key] = wp.Kernel(func=kernel_fn, key=key, module=module, code_transformers=code_transformers)
return _kernel_cache[key]
| warp-main | warp/fem/cache.py |
# Shared DOFs : vertices or edges (sides in 3D)
# DG: Interior DOFs only
# Unique identifier -> vertex or edge, side
# Element -> DOF id
| warp-main | warp/fem/__init__.py |
import warp as wp
vec1i = wp.types.vector(length=1, dtype=wp.int32)
vec2i = wp.types.vector(length=2, dtype=wp.int32)
vec3i = wp.types.vector(length=3, dtype=wp.int32)
vec4i = wp.types.vector(length=4, dtype=wp.int32)
vec8i = wp.types.vector(length=8, dtype=wp.int32)
vec6 = wp.types.vector(length=6, dtype=wp.float32)
Coords = wp.vec3
OUTSIDE = wp.constant(-1.0e8)
ElementIndex = int
QuadraturePointIndex = int
NodeIndex = int
NULL_ELEMENT_INDEX = wp.constant(-1)
NULL_QP_INDEX = wp.constant(-1)
NULL_NODE_INDEX = wp.constant(-1)
DofIndex = vec2i
"""Opaque descriptor for indexing degrees of freedom within elements"""
NULL_DOF_INDEX = wp.constant(DofIndex(-1, -1))
@wp.func
def get_node_index_in_element(dof_idx: DofIndex):
return dof_idx[0]
@wp.func
def get_node_coord(dof_idx: DofIndex):
return dof_idx[1]
@wp.struct
class NodeElementIndex:
domain_element_index: ElementIndex
node_index_in_element: int
@wp.struct
class Sample:
"""Per-sample point context for evaluating fields and related operators in integrands"""
element_index: ElementIndex
"""Index of the geometry element the sample point is in"""
element_coords: Coords
"""Coordinates of the sample point inside the element"""
qp_index: QuadraturePointIndex = NULL_QP_INDEX
"""If the sample corresponds to a quadrature point, its global index"""
qp_weight: float = 0.0
"""If the sample corresponds to a quadrature point, its weight"""
test_dof: DofIndex = NULL_DOF_INDEX
"""For linear of bilinear form assembly, index of the test degree-of-freedom currently being considered"""
trial_dof: DofIndex = NULL_DOF_INDEX
"""For bilinear form assembly, index of the trial degree-of-freedom currently being considered"""
class Field:
"""
Tag for field-like integrand arguments
"""
call_operator: "wp.fem.Operator" = None # Set in operator.py
class Domain:
"""
Tag for domain-like integrand arguments
"""
call_operator: "wp.fem.Operator" = None # Set in operator.py
| warp-main | warp/fem/types.py |
from typing import List, Dict, Set, Optional, Any, Union
import warp as wp
import re
import ast
from warp.sparse import BsrMatrix, bsr_zeros, bsr_set_from_triplets, bsr_copy, bsr_diag
from warp.types import type_length
from warp.utils import array_cast
from warp.codegen import get_annotations
from warp.fem.domain import GeometryDomain
from warp.fem.space import SpaceRestriction
from warp.fem.field import (
TestField,
TrialField,
FieldLike,
DiscreteField,
FieldRestriction,
make_restriction,
)
from warp.fem.quadrature import Quadrature, RegularQuadrature
from warp.fem.operator import Operator, Integrand
from warp.fem import cache
from warp.fem.types import Domain, Field, Sample, DofIndex, NULL_DOF_INDEX, OUTSIDE
def _resolve_path(func, node):
"""
Resolves variable and path from ast node/attribute (adapted from warp.codegen)
"""
modules = []
while isinstance(node, ast.Attribute):
modules.append(node.attr)
node = node.value
if isinstance(node, ast.Name):
modules.append(node.id)
# reverse list since ast presents it backward order
path = [*reversed(modules)]
if len(path) == 0:
return None, path
# try and evaluate object path
try:
# Look up the closure info and append it to adj.func.__globals__
# in case you want to define a kernel inside a function and refer
# to varibles you've declared inside that function:
capturedvars = dict(
zip(
func.__code__.co_freevars,
[c.cell_contents for c in (func.__closure__ or [])],
)
)
vars_dict = {**func.__globals__, **capturedvars}
func = eval(".".join(path), vars_dict)
return func, path
except (NameError, AttributeError):
pass
return None, path
def _path_to_ast_attribute(name: str) -> ast.Attribute:
path = name.split(".")
path.reverse()
node = ast.Name(id=path.pop(), ctx=ast.Load())
while len(path):
node = ast.Attribute(
value=node,
attr=path.pop(),
ctx=ast.Load(),
)
return node
class IntegrandTransformer(ast.NodeTransformer):
def __init__(self, integrand: Integrand, field_args: Dict[str, FieldLike]):
self._integrand = integrand
self._field_args = field_args
def visit_Call(self, call: ast.Call):
call = self.generic_visit(call)
callee = getattr(call.func, "id", None)
if callee in self._field_args:
# Shortcut for evaluating fields as f(x...)
field = self._field_args[callee]
arg_type = self._integrand.argspec.annotations[callee]
operator = arg_type.call_operator
call.func = ast.Attribute(
value=_path_to_ast_attribute(arg_type.__qualname__),
attr="call_operator",
ctx=ast.Load(),
)
call.args = [ast.Name(id=callee, ctx=ast.Load())] + call.args
self._replace_call_func(call, operator, field)
return call
func, _ = _resolve_path(self._integrand.func, call.func)
if isinstance(func, Operator) and len(call.args) > 0:
# Evaluating operators as op(field, x, ...)
callee = getattr(call.args[0], "id", None)
if callee in self._field_args:
field = self._field_args[callee]
self._replace_call_func(call, func, field)
if isinstance(func, Integrand):
key = self._translate_callee(func, call.args)
call.func = ast.Attribute(
value=call.func,
attr=key,
ctx=ast.Load(),
)
# print(ast.dump(call, indent=4))
return call
def _replace_call_func(self, call: ast.Call, operator: Operator, field: FieldLike):
try:
pointer = operator.resolver(field)
setattr(operator, pointer.key, pointer)
except AttributeError:
raise ValueError(f"Operator {operator.func.__name__} is not defined for field {field.name}")
call.func = ast.Attribute(value=call.func, attr=pointer.key, ctx=ast.Load())
def _translate_callee(self, callee: Integrand, args: List[ast.AST]):
# Get field types for call site arguments
call_site_field_args = []
for arg in args:
name = getattr(arg, "id", None)
if name in self._field_args:
call_site_field_args.append(self._field_args[name])
call_site_field_args.reverse()
# Pass to callee in same order
callee_field_args = {}
for arg in callee.argspec.args:
arg_type = callee.argspec.annotations[arg]
if arg_type in (Field, Domain):
callee_field_args[arg] = call_site_field_args.pop()
return _translate_integrand(callee, callee_field_args).key
def _translate_integrand(integrand: Integrand, field_args: Dict[str, FieldLike]) -> wp.Function:
# Specialize field argument types
argspec = integrand.argspec
annotations = {}
for arg in argspec.args:
arg_type = argspec.annotations[arg]
if arg_type == Field:
annotations[arg] = field_args[arg].EvalArg
elif arg_type == Domain:
annotations[arg] = field_args[arg].ElementArg
else:
annotations[arg] = arg_type
# Transform field evaluation calls
transformer = IntegrandTransformer(integrand, field_args)
def is_field_like(f):
# WAR for isinstance not supporting Union in Python < 3.10
return any(isinstance(f, field_class) for field_class in FieldLike.__args__)
suffix = "_".join([f.name for f in field_args.values() if is_field_like(f)])
key = integrand.name + suffix
func = cache.get_integrand_function(
integrand=integrand,
suffix=suffix,
annotations=annotations,
code_transformers=[transformer],
)
key = func.key
setattr(integrand, key, integrand.module.functions[key])
return getattr(integrand, key)
def _get_integrand_field_arguments(
integrand: Integrand,
fields: Dict[str, FieldLike],
domain: GeometryDomain = None,
):
# parse argument types
field_args = {}
value_args = {}
domain_name = None
sample_name = None
argspec = integrand.argspec
for arg in argspec.args:
arg_type = argspec.annotations[arg]
if arg_type == Field:
if arg not in fields:
raise ValueError(f"Missing field for argument '{arg}'")
field_args[arg] = fields[arg]
elif arg_type == Domain:
domain_name = arg
field_args[arg] = domain
elif arg_type == Sample:
sample_name = arg
else:
value_args[arg] = arg_type
return field_args, value_args, domain_name, sample_name
def _get_test_and_trial_fields(
fields: Dict[str, FieldLike],
):
test = None
trial = None
test_name = None
trial_name = None
for name, field in fields.items():
if isinstance(field, TestField):
if test is not None:
raise ValueError("Duplicate test field argument")
test = field
test_name = name
elif isinstance(field, TrialField):
if trial is not None:
raise ValueError("Duplicate test field argument")
trial = field
trial_name = name
if trial is not None:
if test is None:
raise ValueError("A trial field cannot be provided without a test field")
if test.domain != trial.domain:
raise ValueError("Incompatible test and trial domains")
return test, test_name, trial, trial_name
def _gen_field_struct(field_args: Dict[str, FieldLike]):
class Fields:
pass
annotations = get_annotations(Fields)
for name, arg in field_args.items():
if isinstance(arg, GeometryDomain):
continue
setattr(Fields, name, arg.EvalArg())
annotations[name] = arg.EvalArg
Fields.__qualname__ = (
Fields.__name__
+ "_"
+ "_".join([f"{name}_{arg_struct.cls.__qualname__}" for name, arg_struct in annotations.items()])
)
try:
Fields.__annotations__ = annotations
except AttributeError:
setattr(Fields.__dict__, "__annotations__", annotations)
return cache.get_struct(Fields)
def _gen_value_struct(value_args: Dict[str, type]):
class Values:
pass
annotations = get_annotations(Values)
for name, arg_type in value_args.items():
setattr(Values, name, None)
annotations[name] = arg_type
def arg_type_name(arg_type):
if isinstance(arg_type, wp.codegen.Struct):
return arg_type_name(arg_type.cls)
return getattr(arg_type, "__name__", str(arg_type))
def arg_type_name(arg_type):
if isinstance(arg_type, wp.codegen.Struct):
return arg_type_name(arg_type.cls)
return getattr(arg_type, "__name__", str(arg_type))
Values.__qualname__ = (
Values.__name__
+ "_"
+ "_".join([f"{name}_{arg_type_name(arg_type)}" for name, arg_type in annotations.items()])
)
try:
Values.__annotations__ = annotations
except AttributeError:
setattr(Values.__dict__, "__annotations__", annotations)
return cache.get_struct(Values)
def _get_trial_arg():
pass
def _get_test_arg():
pass
class PassFieldArgsToIntegrand(ast.NodeTransformer):
def __init__(
self,
arg_names: List[str],
field_args: Set[str],
value_args: Set[str],
sample_name: str,
domain_name: str,
test_name: str = None,
trial_name: str = None,
func_name: str = "integrand_func",
fields_var_name: str = "fields",
values_var_name: str = "values",
domain_var_name: str = "domain_arg",
sample_var_name: str = "sample",
):
self._arg_names = arg_names
self._field_args = field_args
self._value_args = value_args
self._domain_name = domain_name
self._sample_name = sample_name
self._func_name = func_name
self._test_name = test_name
self._trial_name = trial_name
self._fields_var_name = fields_var_name
self._values_var_name = values_var_name
self._domain_var_name = domain_var_name
self._sample_var_name = sample_var_name
def visit_Call(self, call: ast.Call):
call = self.generic_visit(call)
callee = getattr(call.func, "id", None)
if callee == self._func_name:
# Replace function arguments with ours generated structs
call.args.clear()
for arg in self._arg_names:
if arg == self._domain_name:
call.args.append(
ast.Name(id=self._domain_var_name, ctx=ast.Load()),
)
elif arg == self._sample_name:
call.args.append(
ast.Name(id=self._sample_var_name, ctx=ast.Load()),
)
elif arg in self._field_args:
call.args.append(
ast.Attribute(
value=ast.Name(id=self._fields_var_name, ctx=ast.Load()),
attr=arg,
ctx=ast.Load(),
)
)
elif arg in self._value_args:
call.args.append(
ast.Attribute(
value=ast.Name(id=self._values_var_name, ctx=ast.Load()),
attr=arg,
ctx=ast.Load(),
)
)
else:
raise RuntimeError(f"Unhandled argument {arg}")
# print(ast.dump(call, indent=4))
elif callee == _get_test_arg.__name__:
# print(ast.dump(call, indent=4))
call = ast.Attribute(
value=ast.Name(id=self._fields_var_name, ctx=ast.Load()),
attr=self._test_name,
ctx=ast.Load(),
)
elif callee == _get_trial_arg.__name__:
# print(ast.dump(call, indent=4))
call = ast.Attribute(
value=ast.Name(id=self._fields_var_name, ctx=ast.Load()),
attr=self._trial_name,
ctx=ast.Load(),
)
return call
def get_integrate_null_kernel(
integrand_func: wp.Function,
domain: GeometryDomain,
quadrature: Quadrature,
FieldStruct: wp.codegen.Struct,
ValueStruct: wp.codegen.Struct,
):
def integrate_kernel_fn(
qp_arg: quadrature.Arg,
domain_arg: domain.ElementArg,
domain_index_arg: domain.ElementIndexArg,
fields: FieldStruct,
values: ValueStruct,
):
element_index = domain.element_index(domain_index_arg, wp.tid())
test_dof_index = NULL_DOF_INDEX
trial_dof_index = NULL_DOF_INDEX
qp_point_count = quadrature.point_count(qp_arg, element_index)
for k in range(qp_point_count):
qp_index = quadrature.point_index(qp_arg, element_index, k)
qp_coords = quadrature.point_coords(qp_arg, element_index, k)
qp_weight = quadrature.point_weight(qp_arg, element_index, k)
sample = Sample(element_index, qp_coords, qp_index, qp_weight, test_dof_index, trial_dof_index)
integrand_func(sample, fields, values)
return integrate_kernel_fn
def get_integrate_constant_kernel(
integrand_func: wp.Function,
domain: GeometryDomain,
quadrature: Quadrature,
FieldStruct: wp.codegen.Struct,
ValueStruct: wp.codegen.Struct,
accumulate_dtype,
):
def integrate_kernel_fn(
qp_arg: quadrature.Arg,
domain_arg: domain.ElementArg,
domain_index_arg: domain.ElementIndexArg,
fields: FieldStruct,
values: ValueStruct,
result: wp.array(dtype=accumulate_dtype),
):
element_index = domain.element_index(domain_index_arg, wp.tid())
elem_sum = accumulate_dtype(0.0)
test_dof_index = NULL_DOF_INDEX
trial_dof_index = NULL_DOF_INDEX
qp_point_count = quadrature.point_count(qp_arg, element_index)
for k in range(qp_point_count):
qp_index = quadrature.point_index(qp_arg, element_index, k)
coords = quadrature.point_coords(qp_arg, element_index, k)
qp_weight = quadrature.point_weight(qp_arg, element_index, k)
vol = domain.element_measure(domain_arg, element_index, coords)
sample = Sample(element_index, coords, qp_index, qp_weight, test_dof_index, trial_dof_index)
val = integrand_func(sample, fields, values)
elem_sum += accumulate_dtype(qp_weight * vol * val)
wp.atomic_add(result, 0, elem_sum)
return integrate_kernel_fn
def get_integrate_linear_kernel(
integrand_func: wp.Function,
domain: GeometryDomain,
quadrature: Quadrature,
FieldStruct: wp.codegen.Struct,
ValueStruct: wp.codegen.Struct,
test_space: SpaceRestriction,
accumulate_dtype,
):
def integrate_kernel_fn(
qp_arg: quadrature.Arg,
domain_arg: domain.ElementArg,
domain_index_arg: domain.ElementIndexArg,
test_arg: test_space.NodeArg,
fields: FieldStruct,
values: ValueStruct,
result: wp.array2d(dtype=accumulate_dtype),
):
local_node_index = wp.tid()
node_index = test_space.node_partition_index(test_arg, local_node_index)
element_count = test_space.node_element_count(test_arg, local_node_index)
trial_dof_index = NULL_DOF_INDEX
for n in range(element_count):
node_element_index = test_space.node_element_index(test_arg, local_node_index, n)
element_index = domain.element_index(domain_index_arg, node_element_index.domain_element_index)
qp_point_count = quadrature.point_count(qp_arg, element_index)
for k in range(qp_point_count):
qp_index = quadrature.point_index(qp_arg, element_index, k)
coords = quadrature.point_coords(qp_arg, element_index, k)
qp_weight = quadrature.point_weight(qp_arg, element_index, k)
vol = domain.element_measure(domain_arg, element_index, coords)
for i in range(test_space.space.VALUE_DOF_COUNT):
test_dof_index = DofIndex(node_element_index.node_index_in_element, i)
sample = Sample(element_index, coords, qp_index, qp_weight, test_dof_index, trial_dof_index)
val = integrand_func(sample, fields, values)
result[node_index, i] = result[node_index, i] + accumulate_dtype(qp_weight * vol * val)
return integrate_kernel_fn
def get_integrate_linear_nodal_kernel(
integrand_func: wp.Function,
domain: GeometryDomain,
FieldStruct: wp.codegen.Struct,
ValueStruct: wp.codegen.Struct,
test: TestField,
accumulate_dtype,
):
def integrate_kernel_fn(
domain_arg: domain.ElementArg,
domain_index_arg: domain.ElementIndexArg,
test_restriction_arg: test.space_restriction.NodeArg,
fields: FieldStruct,
values: ValueStruct,
result: wp.array2d(dtype=accumulate_dtype),
):
local_node_index, dof = wp.tid()
node_index = test.space_restriction.node_partition_index(test_restriction_arg, local_node_index)
element_count = test.space_restriction.node_element_count(test_restriction_arg, local_node_index)
trial_dof_index = NULL_DOF_INDEX
val_sum = accumulate_dtype(0.0)
for n in range(element_count):
node_element_index = test.space_restriction.node_element_index(test_restriction_arg, local_node_index, n)
element_index = domain.element_index(domain_index_arg, node_element_index.domain_element_index)
coords = test.space.node_coords_in_element(
_get_test_arg(),
element_index,
node_element_index.node_index_in_element,
)
if coords[0] != OUTSIDE:
node_weight = test.space.node_quadrature_weight(
_get_test_arg(),
element_index,
node_element_index.node_index_in_element,
)
vol = domain.element_measure(domain_arg, element_index, coords)
test_dof_index = DofIndex(node_element_index.node_index_in_element, dof)
sample = Sample(
element_index,
coords,
node_index,
node_weight,
test_dof_index,
trial_dof_index,
)
val = integrand_func(sample, fields, values)
val_sum += accumulate_dtype(node_weight * vol * val)
result[node_index, dof] = val_sum
return integrate_kernel_fn
def get_integrate_bilinear_kernel(
integrand_func: wp.Function,
domain: GeometryDomain,
quadrature: Quadrature,
FieldStruct: wp.codegen.Struct,
ValueStruct: wp.codegen.Struct,
test_space: SpaceRestriction,
trial: TrialField,
accumulate_dtype,
):
NODES_PER_ELEMENT = trial.space.NODES_PER_ELEMENT
def integrate_kernel_fn(
qp_arg: quadrature.Arg,
domain_arg: domain.ElementArg,
domain_index_arg: domain.ElementIndexArg,
test_arg: test_space.NodeArg,
trial_partition_arg: trial.space_partition.PartitionArg,
fields: FieldStruct,
values: ValueStruct,
row_offsets: wp.array(dtype=int),
triplet_rows: wp.array(dtype=int),
triplet_cols: wp.array(dtype=int),
triplet_values: wp.array3d(dtype=accumulate_dtype),
):
test_local_node_index = wp.tid()
element_count = test_space.node_element_count(test_arg, test_local_node_index)
test_node_index = test_space.node_partition_index(test_arg, test_local_node_index)
for element in range(element_count):
test_element_index = test_space.node_element_index(test_arg, test_local_node_index, element)
element_index = domain.element_index(domain_index_arg, test_element_index.domain_element_index)
qp_point_count = quadrature.point_count(qp_arg, element_index)
start_offset = (row_offsets[test_node_index] + element) * NODES_PER_ELEMENT
for k in range(qp_point_count):
qp_index = quadrature.point_index(qp_arg, element_index, k)
coords = quadrature.point_coords(qp_arg, element_index, k)
qp_weight = quadrature.point_weight(qp_arg, element_index, k)
vol = domain.element_measure(domain_arg, element_index, coords)
offset_cur = start_offset
for trial_n in range(NODES_PER_ELEMENT):
for i in range(test_space.space.VALUE_DOF_COUNT):
for j in range(trial.space.VALUE_DOF_COUNT):
test_dof_index = DofIndex(
test_element_index.node_index_in_element,
i,
)
trial_dof_index = DofIndex(trial_n, j)
sample = Sample(
element_index,
coords,
qp_index,
qp_weight,
test_dof_index,
trial_dof_index,
)
val = integrand_func(sample, fields, values)
triplet_values[offset_cur, i, j] = triplet_values[offset_cur, i, j] + accumulate_dtype(
qp_weight * vol * val
)
offset_cur += 1
# Set column indices
offset_cur = start_offset
for trial_n in range(NODES_PER_ELEMENT):
trial_node_index = trial.space_partition.partition_node_index(
trial_partition_arg,
trial.space.element_node_index(_get_trial_arg(), element_index, trial_n),
)
triplet_rows[offset_cur] = test_node_index
triplet_cols[offset_cur] = trial_node_index
offset_cur += 1
return integrate_kernel_fn
def get_integrate_bilinear_nodal_kernel(
integrand_func: wp.Function,
domain: GeometryDomain,
FieldStruct: wp.codegen.Struct,
ValueStruct: wp.codegen.Struct,
test: TestField,
accumulate_dtype,
):
def integrate_kernel_fn(
domain_arg: domain.ElementArg,
domain_index_arg: domain.ElementIndexArg,
test_restriction_arg: test.space_restriction.NodeArg,
fields: FieldStruct,
values: ValueStruct,
triplet_rows: wp.array(dtype=int),
triplet_cols: wp.array(dtype=int),
triplet_values: wp.array3d(dtype=accumulate_dtype),
):
local_node_index, test_dof, trial_dof = wp.tid()
element_count = test.space_restriction.node_element_count(test_restriction_arg, local_node_index)
node_index = test.space_restriction.node_partition_index(test_restriction_arg, local_node_index)
val_sum = accumulate_dtype(0.0)
for n in range(element_count):
node_element_index = test.space_restriction.node_element_index(test_restriction_arg, local_node_index, n)
element_index = domain.element_index(domain_index_arg, node_element_index.domain_element_index)
coords = test.space.node_coords_in_element(
_get_test_arg(),
element_index,
node_element_index.node_index_in_element,
)
if coords[0] != OUTSIDE:
node_weight = test.space.node_quadrature_weight(
_get_test_arg(),
element_index,
node_element_index.node_index_in_element,
)
vol = domain.element_measure(domain_arg, element_index, coords)
test_dof_index = DofIndex(node_element_index.node_index_in_element, test_dof)
trial_dof_index = DofIndex(node_element_index.node_index_in_element, trial_dof)
sample = Sample(
element_index,
coords,
node_index,
node_weight,
test_dof_index,
trial_dof_index,
)
val = integrand_func(sample, fields, values)
val_sum += accumulate_dtype(node_weight * vol * val)
triplet_values[local_node_index, test_dof, trial_dof] = val_sum
triplet_rows[local_node_index] = node_index
triplet_cols[local_node_index] = node_index
return integrate_kernel_fn
def _generate_integrate_kernel(
integrand: Integrand,
domain: GeometryDomain,
nodal: bool,
quadrature: Quadrature,
test: Optional[TestField],
test_name: str,
trial: Optional[TrialField],
trial_name: str,
fields: Dict[str, FieldLike],
accumulate_dtype: type,
) -> wp.Kernel:
# Extract field arguments from integrand
field_args, value_args, domain_name, sample_name = _get_integrand_field_arguments(
integrand, fields=fields, domain=domain
)
FieldStruct = _gen_field_struct(field_args)
ValueStruct = _gen_value_struct(value_args)
# Check if kernel exist in cache
kernel_suffix = f"_itg_{domain.name}_{FieldStruct.key}"
if nodal:
kernel_suffix += "_nodal"
else:
kernel_suffix += quadrature.name
if test:
kernel_suffix += f"_test_{test.space_partition.name}_{test.space.name}"
if trial:
kernel_suffix += f"_trial_{trial.space_partition.name}_{trial.space.name}"
kernel = cache.get_integrand_kernel(
integrand=integrand,
suffix=kernel_suffix,
)
if kernel is not None:
return kernel, FieldStruct, ValueStruct
# Not found in cache, trasnform integrand and generate kernel
integrand_func = _translate_integrand(
integrand,
field_args,
)
if test is None and trial is None:
integrate_kernel_fn = get_integrate_constant_kernel(
integrand_func,
domain,
quadrature,
FieldStruct,
ValueStruct,
accumulate_dtype=accumulate_dtype,
)
elif trial is None:
if nodal:
integrate_kernel_fn = get_integrate_linear_nodal_kernel(
integrand_func,
domain,
FieldStruct,
ValueStruct,
test=test,
accumulate_dtype=accumulate_dtype,
)
else:
integrate_kernel_fn = get_integrate_linear_kernel(
integrand_func,
domain,
quadrature,
FieldStruct,
ValueStruct,
test_space=test.space_restriction,
accumulate_dtype=accumulate_dtype,
)
else:
if nodal:
integrate_kernel_fn = get_integrate_bilinear_nodal_kernel(
integrand_func,
domain,
FieldStruct,
ValueStruct,
test=test,
accumulate_dtype=accumulate_dtype,
)
else:
integrate_kernel_fn = get_integrate_bilinear_kernel(
integrand_func,
domain,
quadrature,
FieldStruct,
ValueStruct,
test_space=test.space_restriction,
trial=trial,
accumulate_dtype=accumulate_dtype,
)
kernel = cache.get_integrand_kernel(
integrand=integrand,
kernel_fn=integrate_kernel_fn,
suffix=kernel_suffix,
code_transformers=[
PassFieldArgsToIntegrand(
arg_names=integrand.argspec.args,
field_args=field_args.keys(),
value_args=value_args.keys(),
sample_name=sample_name,
domain_name=domain_name,
test_name=test_name,
trial_name=trial_name
)
],
)
return kernel, FieldStruct, ValueStruct
def _launch_integrate_kernel(
kernel: wp.kernel,
FieldStruct: wp.codegen.Struct,
ValueStruct: wp.codegen.Struct,
domain: GeometryDomain,
nodal: bool,
quadrature: Quadrature,
test: Optional[TestField],
trial: Optional[TrialField],
fields: Dict[str, FieldLike],
values: Dict[str, Any],
accumulate_dtype: type,
output_dtype: type,
output: Optional[Union[wp.array, BsrMatrix]],
device,
) -> wp.Kernel:
if output_dtype is None:
if output is not None:
output_dtype = output.dtype
else:
output_dtype = accumulate_dtype
# Set-up launch arguments
domain_elt_arg = domain.element_arg_value(device=device)
domain_elt_index_arg = domain.element_index_arg_value(device=device)
if quadrature is not None:
qp_arg = quadrature.arg_value(device=device)
field_arg_values = FieldStruct()
for k, v in fields.items():
setattr(field_arg_values, k, v.eval_arg_value(device=device))
value_struct_values = ValueStruct()
for k, v in values.items():
setattr(value_struct_values, k, v)
# Constant
if test is None and trial is None:
if output is None or output.dtype != accumulate_dtype:
result = wp.zeros(shape=(1), device=device, dtype=output_dtype)
else:
result = output
result.zero_()
wp.launch(
kernel=kernel,
dim=domain.element_count(),
inputs=[
qp_arg,
domain_elt_arg,
domain_elt_index_arg,
field_arg_values,
value_struct_values,
result,
],
device=device,
)
if output is None:
return output_dtype(result.numpy()[0])
else:
if output != result:
array_cast(in_array=result, out_array=output)
return output
test_arg = test.space_restriction.node_arg(device=device)
# Linear form
if trial is None:
if test.space.VALUE_DOF_COUNT == 1:
result_dtype = accumulate_dtype
else:
result_dtype = wp.vec(length=test.space.VALUE_DOF_COUNT, dtype=accumulate_dtype)
result_array = wp.zeros(
shape=test.space_partition.node_count(),
dtype=result_dtype,
device=device,
)
# Launch the integration on the kernel on a 2d scalar view of the actual array
result_2d_view = wp.array(
data=None,
ptr=result_array.ptr,
capacity=result_array.capacity,
owner=False,
device=result_array.device,
shape=(test.space_partition.node_count(), test.space.VALUE_DOF_COUNT),
dtype=accumulate_dtype,
)
if nodal:
wp.launch(
kernel=kernel,
dim=(test.space_restriction.node_count(), test.space.VALUE_DOF_COUNT),
inputs=[
domain_elt_arg,
domain_elt_index_arg,
test_arg,
field_arg_values,
value_struct_values,
result_2d_view,
],
device=device,
)
else:
wp.launch(
kernel=kernel,
dim=test.space_restriction.node_count(),
inputs=[
qp_arg,
domain_elt_arg,
domain_elt_index_arg,
test_arg,
field_arg_values,
value_struct_values,
result_2d_view,
],
device=device,
)
if output_dtype == result_array.dtype:
return result_array
output_type_length = type_length(output_dtype)
if output_type_length == test.space.VALUE_DOF_COUNT:
cast_result = wp.empty(dtype=output_dtype, shape=result_array.shape)
else:
cast_result = wp.empty(dtype=output_dtype, shape=result_2d_view.shape)
array_cast(in_array=result_array, out_array=cast_result)
return cast_result
# Bilinear form
if test.space.VALUE_DOF_COUNT == 1 and trial.space.VALUE_DOF_COUNT == 1:
block_type = accumulate_dtype
else:
block_type = wp.types.matrix(
shape=(test.space.VALUE_DOF_COUNT, trial.space.VALUE_DOF_COUNT), dtype=accumulate_dtype
)
bsr_matrix = bsr_zeros(
rows_of_blocks=test.space_partition.node_count(),
cols_of_blocks=trial.space_partition.node_count(),
block_type=block_type,
device=device,
)
if nodal:
nnz = test.space_restriction.node_count()
else:
nnz = test.space_restriction.total_node_element_count() * trial.space.NODES_PER_ELEMENT
triplet_rows = wp.empty(n=nnz, dtype=int, device=device)
triplet_cols = wp.empty(n=nnz, dtype=int, device=device)
triplet_values = wp.zeros(
shape=(
nnz,
test.space.VALUE_DOF_COUNT,
trial.space.VALUE_DOF_COUNT,
),
dtype=accumulate_dtype,
device=device,
)
if nodal:
wp.launch(
kernel=kernel,
dim=triplet_values.shape,
inputs=[
domain_elt_arg,
domain_elt_index_arg,
test_arg,
field_arg_values,
value_struct_values,
triplet_rows,
triplet_cols,
triplet_values,
],
device=device,
)
else:
offsets = test.space_restriction.partition_element_offsets()
trial_partition_arg = trial.space_partition.partition_arg_value(device)
wp.launch(
kernel=kernel,
dim=test.space_restriction.node_count(),
inputs=[
qp_arg,
domain_elt_arg,
domain_elt_index_arg,
test_arg,
trial_partition_arg,
field_arg_values,
value_struct_values,
offsets,
triplet_rows,
triplet_cols,
triplet_values,
],
device=device,
)
bsr_set_from_triplets(bsr_matrix, triplet_rows, triplet_cols, triplet_values)
return bsr_matrix if output_dtype == accumulate_dtype else bsr_copy(bsr_matrix, scalar_type=output_dtype)
def integrate(
integrand: Integrand,
domain: GeometryDomain = None,
quadrature: Quadrature = None,
nodal: bool = False,
fields={},
values={},
device=None,
accumulate_dtype=wp.float64,
output_dtype=None,
output=None,
):
"""
Integrates a constant, linear or bilinear form, and returns a scalar, array, or sparse matrix, respectively.
Args:
integrand: Form to be integrated, must have `wp.integrand` decorator
domain: Integration domain. If None, deduced from fields
quadrature: Quadrature formula. If None, deduced from domain and fields degree.
nodal: For linear or bilinear form only, use the test function nodes as the quadrature points. Assumes Lagrange interpolation functions are used, and no differential or DG operator is evaluated on the test or trial functions.
fields: Discrete, test, and trial fields to be passed to the integrand. Keys in the dictionary must match integrand parameter names.
values: Additional variable values to be passed to the integrand, can by of any type accepted by warp kernel launchs. Keys in the dictionary must match integrand parameter names.
device: Device on which to perform the integration
accumulate_dtype: Scalar type to be used for accumulating integration samples
output_dtype: Scalar type for returned results. If None, defaults to accumulate_dtype
"""
if not isinstance(integrand, Integrand):
raise ValueError("integrand must be tagged with @integrand decorator")
test, test_name, trial, trial_name = _get_test_and_trial_fields(fields)
if domain is None:
if quadrature is not None:
domain = quadrature.domain
elif test is not None:
domain = test.domain
if domain is None:
raise ValueError("Must provide at least one of domain, quadrature, or test field")
if test is not None and domain != test.domain:
raise NotImplementedError("Mixing integration and test domain is not supported yet")
if nodal:
if quadrature is not None:
raise ValueError("Cannot specify quadrature for nodal integration")
if test is None:
raise ValueError("Nodal integration requires specifying a test function")
if trial is not None and test.space_partition != trial.space_partition:
raise ValueError(
"Bilinear nodal integration requires test and trial to be defined on the same function space"
)
else:
if quadrature is None:
order = 0
if test is not None:
order += test.space.degree
if trial is not None:
order += trial.space.degree
quadrature = RegularQuadrature(domain=domain, order=order)
elif domain != quadrature.domain:
raise ValueError("Incompatible integration and quadrature domain")
kernel, FieldStruct, ValueStruct = _generate_integrate_kernel(
integrand=integrand,
domain=domain,
nodal=nodal,
quadrature=quadrature,
test=test,
test_name=test_name,
trial=trial,
trial_name=trial_name,
fields=fields,
accumulate_dtype=accumulate_dtype,
)
return _launch_integrate_kernel(
kernel=kernel,
FieldStruct=FieldStruct,
ValueStruct=ValueStruct,
domain=domain,
nodal=nodal,
quadrature=quadrature,
test=test,
trial=trial,
fields=fields,
values=values,
accumulate_dtype=accumulate_dtype,
output_dtype=output_dtype,
output=output,
device=device,
)
def get_interpolate_kernel(
integrand_func: wp.Function,
domain: GeometryDomain,
FieldStruct: wp.codegen.Struct,
ValueStruct: wp.codegen.Struct,
dest: FieldRestriction,
):
value_type = dest.space.dtype
def interpolate_kernel_fn(
domain_arg: domain.ElementArg,
domain_index_arg: domain.ElementIndexArg,
dest_node_arg: dest.space_restriction.NodeArg,
dest_eval_arg: dest.field.EvalArg,
fields: FieldStruct,
values: ValueStruct,
):
local_node_index = wp.tid()
node_index = dest.space_restriction.node_partition_index(dest_node_arg, local_node_index)
element_count = dest.space_restriction.node_element_count(dest_node_arg, local_node_index)
if element_count == 0:
return
test_dof_index = NULL_DOF_INDEX
trial_dof_index = NULL_DOF_INDEX
node_weight = 1.0
# Volume-weighted average accross elements
# Superfluous if the function is continuous, but we might as well
val_sum = value_type(0.0)
vol_sum = float(0.0)
for n in range(element_count):
node_element_index = dest.space_restriction.node_element_index(dest_node_arg, local_node_index, n)
element_index = domain.element_index(domain_index_arg, node_element_index.domain_element_index)
coords = dest.space.node_coords_in_element(
dest_eval_arg.space_arg,
element_index,
node_element_index.node_index_in_element,
)
if coords[0] != OUTSIDE:
vol = domain.element_measure(domain_arg, element_index, coords)
sample = Sample(
element_index,
coords,
node_index,
node_weight,
test_dof_index,
trial_dof_index,
)
val = integrand_func(sample, fields, values)
vol_sum += vol
val_sum += vol * val
if vol_sum > 0.0:
dest.field.set_node_value(dest_eval_arg, node_index, val_sum / vol_sum)
return interpolate_kernel_fn
def _generate_interpolate_kernel(integrand: Integrand, dest: FieldLike, fields: Dict[str, FieldLike]) -> wp.Kernel:
domain = dest.domain
# Extract field arguments from integrand
field_args, value_args, domain_name, sample_name = _get_integrand_field_arguments(
integrand, fields=fields, domain=domain
)
# Generate field struct
integrand_func = _translate_integrand(
integrand,
field_args,
)
FieldStruct = _gen_field_struct(field_args)
ValueStruct = _gen_value_struct(value_args)
# Check if kernel exist in cache
kernel_suffix = f"_itp_{FieldStruct.key}_{dest.domain.name}_{dest.space_restriction.space_partition.name}_{dest.space.name}"
kernel = cache.get_integrand_kernel(
integrand=integrand,
suffix=kernel_suffix,
)
if kernel is not None:
return kernel, FieldStruct, ValueStruct
# Generate interpolation kernel
interpolate_kernel_fn = get_interpolate_kernel(
integrand_func,
domain,
dest=dest,
FieldStruct=FieldStruct,
ValueStruct=ValueStruct,
)
kernel = cache.get_integrand_kernel(
integrand=integrand,
kernel_fn=interpolate_kernel_fn,
suffix=kernel_suffix,
code_transformers=[
PassFieldArgsToIntegrand(
arg_names=integrand.argspec.args,
field_args=field_args.keys(),
value_args=value_args.keys(),
sample_name=sample_name,
domain_name=domain_name,
)
],
)
return kernel, FieldStruct, ValueStruct
def _launch_interpolate_kernel(
kernel: wp.kernel,
FieldStruct: wp.codegen.Struct,
ValueStruct: wp.codegen.Struct,
dest: FieldLike,
fields: Dict[str, FieldLike],
values: Dict[str, Any],
device,
) -> wp.Kernel:
# Set-up launch arguments
elt_arg = dest.domain.element_arg_value(device=device)
elt_index_arg = dest.domain.element_index_arg_value(device=device)
dest_node_arg = dest.space_restriction.node_arg(device=device)
dest_eval_arg = dest.field.eval_arg_value(device=device)
field_arg_values = FieldStruct()
for k, v in fields.items():
setattr(field_arg_values, k, v.eval_arg_value(device=device))
value_struct_values = ValueStruct()
for k, v in values.items():
setattr(value_struct_values, k, v)
wp.launch(
kernel=kernel,
dim=dest.space_restriction.node_count(),
inputs=[
elt_arg,
elt_index_arg,
dest_node_arg,
dest_eval_arg,
field_arg_values,
value_struct_values,
],
device=device,
)
def interpolate(
integrand: Integrand,
dest: Union[DiscreteField, FieldRestriction],
fields={},
values={},
device=None,
):
"""
Interpolates a function and assigns the result to a discrete field.
Args:
integrand: Function to be interpolated, must have `wp.integrand` decorator
dest: Discrete field, or restriction of a discrete field to a domain, to which the interpolation result will be assigned
fields: Discrete fields to be passed to the integrand. Keys in the dictionary must match integrand parameters names.
values: Additional variable values to be passed to the integrand, can by of any type accepted by warp kernel launchs. Keys in the dictionary must match integrand parameter names.
device: Device on which to perform the interpolation
"""
if not isinstance(integrand, Integrand):
raise ValueError("integrand must be tagged with @integrand decorator")
test, _, trial, __ = _get_test_and_trial_fields(fields)
if test is not None or trial is not None:
raise ValueError("Test or Trial fields should not be used for interpolation")
if not isinstance(dest, FieldRestriction):
dest = make_restriction(dest)
kernel, FieldStruct, ValueStruct = _generate_interpolate_kernel(
integrand=integrand,
dest=dest,
fields=fields,
)
return _launch_interpolate_kernel(
kernel=kernel,
FieldStruct=FieldStruct,
ValueStruct=ValueStruct,
dest=dest,
fields=fields,
values=values,
device=device,
)
| warp-main | warp/fem/integrate.py |
from typing import Any, Tuple
import warp as wp
from warp.utils import radix_sort_pairs, runlength_encode, array_scan
from .types import vec6
@wp.func
def generalized_outer(x: Any, y: wp.vec2):
return wp.outer(x, y)
@wp.func
def generalized_outer(x: Any, y: wp.vec3):
return wp.outer(x, y)
@wp.func
def generalized_outer(x: Any, y: wp.float32):
return x * y
@wp.func
def unit_element(template_type: wp.float32, coord: int):
return 1.0
@wp.func
def unit_element(template_type: wp.vec2, coord: int):
t = wp.vec2(0.0)
t[coord] = 1.0
return t
@wp.func
def unit_element(template_type: wp.vec3, coord: int):
t = wp.vec3(0.0)
t[coord] = 1.0
return t
@wp.func
def unit_element(template_type: vec6, coord: int):
t = vec6(0.0)
t[coord] = 1.0
return t
@wp.func
def unit_element(template_type: wp.mat22, coord: int):
t = wp.mat22(0.0)
t[coord // 2, coord % 2] = 1.0
return t
@wp.func
def unit_element(template_type: wp.mat33, coord: int):
t = wp.mat22(0.0)
t[coord // 3, coord % 3] = 1.0
return t
@wp.func
def symmetric_part(x: wp.mat22):
off_diag = 0.5 * (x[0, 1] + x[1, 0])
return wp.mat22(x[0, 0], off_diag, off_diag, x[1, 1])
@wp.func
def symmetric_part(x: wp.mat33):
d = 0.5 * (x[1, 2] + x[2, 1])
e = 0.5 * (x[2, 0] + x[0, 2])
f = 0.5 * (x[0, 1] + x[1, 0])
return wp.mat33(x[0, 0], f, e, f, x[1, 1], d, e, d, x[2, 2])
def compress_node_indices(
node_count: int, node_indices: wp.array(dtype=int)
) -> Tuple[wp.array, wp.array, int, wp.array]:
"""
Compress an unsorted list of node indices into:
- a node_offsets array, giving for each node the start offset of corresponding indices in sorted_array_indices
- a sorted_array_indices array, listing the indices in the input array corresponding to each node
- the number of unique node indices
- a unique_node_indices array containg the sorted list of unique node indices (i.e. the list of indices i for which node_offsets[i] < node_offsets[i+1])
"""
index_count = node_indices.size
sorted_node_indices = wp.empty(2 * index_count, dtype=int, device=node_indices.device)
sorted_array_indices = wp.empty_like(sorted_node_indices)
wp.copy(dest=sorted_node_indices, src=node_indices, count=index_count)
indices_per_element = 1 if node_indices.ndim == 1 else node_indices.shape[-1]
wp.launch(
kernel=_iota_kernel,
dim=index_count,
inputs=[sorted_array_indices, indices_per_element],
device=sorted_array_indices.device,
)
# Sort indices
radix_sort_pairs(sorted_node_indices, sorted_array_indices, count=index_count)
# Build prefix sum of number of elements per node
unique_node_indices = wp.empty(n=index_count, dtype=int, device=node_indices.device)
node_element_counts = wp.empty(n=index_count, dtype=int, device=node_indices.device)
unique_node_count = runlength_encode(
sorted_node_indices, unique_node_indices, node_element_counts, value_count=index_count
)
# Scatter seen run counts to global array of element count per node
node_offsets = wp.zeros(shape=(node_count + 1), device=node_element_counts.device, dtype=int)
wp.launch(
kernel=_scatter_node_counts,
dim=unique_node_count,
inputs=[node_element_counts, unique_node_indices, node_offsets],
device=node_offsets.device,
)
# Prefix sum of number of elements per node
array_scan(node_offsets, node_offsets, inclusive=True)
return node_offsets, sorted_array_indices, unique_node_count, unique_node_indices
_pinned_temp_count_buffer = {}
def _get_pinned_temp_count_buffer(device):
device = str(device)
if device not in _pinned_temp_count_buffer:
_pinned_temp_count_buffer[device] = wp.empty(shape=(1,), dtype=int, pinned=True, device="cpu")
return _pinned_temp_count_buffer[device]
def masked_indices(mask: wp.array(dtype=int), missing_index=-1) -> Tuple[wp.array, wp.array]:
"""
From an array of boolean masks (must be either 0 or 1), returns:
- The list of indices for which the mask is 1
- A map associating to each element of the input mask array its local index if non-zero, or missing_index if zero.
"""
offsets = wp.empty_like(mask)
wp.utils.array_scan(mask, offsets, inclusive=True)
# Get back total counts on host
if offsets.device.is_cuda:
masked_count = _get_pinned_temp_count_buffer(offsets.device)
wp.copy(dest=masked_count, src=offsets, src_offset=offsets.shape[0] - 1, count=1)
wp.synchronize_stream(wp.get_stream())
masked_count = int(masked_count.numpy()[0])
else:
masked_count = int(offsets.numpy()[-1])
# Convert counts to indices
indices = wp.empty(n=masked_count, device=mask.device, dtype=int)
wp.launch(
kernel=_masked_indices_kernel,
dim=offsets.shape,
inputs=[missing_index, mask, offsets, indices, offsets],
device=mask.device,
)
return indices, offsets
def array_axpy(x: wp.array, y: wp.array, alpha: float = 1.0, beta: float = 1.0):
"""Performs y = alpha*x + beta*y"""
dtype = wp.types.type_scalar_type(x.dtype)
alpha = dtype(alpha)
beta = dtype(beta)
if x.dtype != y.dtype or x.shape != y.shape or x.device != y.device:
raise ValueError("x and y arrays must have same dat atype, shape and device")
wp.launch(kernel=_array_axpy_kernel, dim=x.shape, device=x.device, inputs=[x, y, alpha, beta])
@wp.kernel
def _iota_kernel(indices: wp.array(dtype=int), divisor: int):
indices[wp.tid()] = wp.tid() // divisor
@wp.kernel
def _scatter_node_counts(
unique_counts: wp.array(dtype=int), unique_node_indices: wp.array(dtype=int), node_counts: wp.array(dtype=int)
):
i = wp.tid()
node_counts[1 + unique_node_indices[i]] = unique_counts[i]
@wp.kernel
def _masked_indices_kernel(
missing_index: int,
mask: wp.array(dtype=int),
offsets: wp.array(dtype=int),
masked_to_global: wp.array(dtype=int),
global_to_masked: wp.array(dtype=int),
):
i = wp.tid()
if mask[i] == 0:
global_to_masked[i] = missing_index
else:
masked_idx = offsets[i] - 1
global_to_masked[i] = masked_idx
masked_to_global[masked_idx] = i
@wp.kernel
def _array_axpy_kernel(x: wp.array(dtype=Any), y: wp.array(dtype=Any), alpha: Any, beta: Any):
i = wp.tid()
y[i] = beta * y[i] + alpha * x[i]
| warp-main | warp/fem/utils.py |
import math
from enum import Enum
import numpy as np
class Polynomial(Enum):
GAUSS_LEGENDRE = 0
LOBATTO_GAUSS_LEGENDRE = 1
EQUISPACED_CLOSED = 2
EQUISPACED_OPEN = 3
def is_closed(family: Polynomial):
"""Whether the polynomial roots include interval endpoints"""
return family == Polynomial.LOBATTO_GAUSS_LEGENDRE or family == Polynomial.EQUISPACED_CLOSED
def _gauss_legendre_quadrature_1d(n: int):
if n == 1:
coords = [0.0]
weights = [2.0]
elif n == 2:
coords = [-math.sqrt(1.0 / 3), math.sqrt(1.0 / 3)]
weights = [1.0, 1.0]
elif n == 3:
coords = [0.0, -math.sqrt(3.0 / 5.0), math.sqrt(3.0 / 5.0)]
weights = [8.0 / 9.0, 5.0 / 9.0, 5.0 / 9.0]
elif n == 4:
c_a = math.sqrt(3.0 / 7.0 - 2.0 / 7.0 * math.sqrt(6.0 / 5.0))
c_b = math.sqrt(3.0 / 7.0 + 2.0 / 7.0 * math.sqrt(6.0 / 5.0))
w_a = (18.0 + math.sqrt(30.0)) / 36.0
w_b = (18.0 - math.sqrt(30.0)) / 36.0
coords = [c_a, -c_a, c_b, -c_b]
weights = [w_a, w_a, w_b, w_b]
elif n == 5:
c_a = 1.0 / 3.0 * math.sqrt(5.0 - 2.0 * math.sqrt(10.0 / 7.0))
c_b = 1.0 / 3.0 * math.sqrt(5.0 + 2.0 * math.sqrt(10.0 / 7.0))
w_a = (322.0 + 13.0 * math.sqrt(70.0)) / 900.0
w_b = (322.0 - 13.0 * math.sqrt(70.0)) / 900.0
coords = [0.0, c_a, -c_a, c_b, -c_b]
weights = [128.0 / 225.0, w_a, w_a, w_b, w_b]
else:
raise NotImplementedError
# Shift from [-1, 1] to [0, 1]
weights = 0.5 * np.array(weights)
coords = 0.5 * np.array(coords) + 0.5
return coords, weights
def _lobatto_gauss_legendre_quadrature_1d(n: int):
if n == 2:
coords = [-1.0, 1.0]
weights = [1.0, 1.0]
elif n == 3:
coords = [-1.0, 0.0, 1.0]
weights = [1.0 / 3.0, 4.0 / 3.0, 1.0 / 3.0]
elif n == 4:
coords = [-1.0, -1.0 / math.sqrt(5.0), 1.0 / math.sqrt(5.0), 1.0]
weights = [1.0 / 6.0, 5.0 / 6.0, 5.0 / 6.0, 1.0 / 6.0]
elif n == 5:
coords = [-1.0, -math.sqrt(3.0 / 7.0), 0.0, math.sqrt(3.0 / 7.0), 1.0]
weights = [1.0 / 10.0, 49.0 / 90.0, 32.0 / 45.0, 49.0 / 90.0, 1.0 / 10.0]
else:
raise NotImplementedError
# Shift from [-1, 1] to [0, 1]
weights = 0.5 * np.array(weights)
coords = 0.5 * np.array(coords) + 0.5
return coords, weights
def _uniform_open_quadrature_1d(n: int):
step = 1.0 / (n + 1)
coords = np.linspace(step, 1.0 - step, n)
weights = np.full(n, 1.0 / (n + 1))
# Boundaries have 3/2 the weight
weights[0] = 1.5 / (n + 1)
weights[-1] = 1.5 / (n + 1)
return coords, weights
def _uniform_closed_quadrature_1d(n: int):
coords = np.linspace(0.0, 1.0, n)
weights = np.full(n, 1.0 / (n - 1))
# Boundaries have half the weight
weights[0] = 0.5 / (n - 1)
weights[-1] = 0.5 / (n - 1)
return coords, weights
def _open_newton_cotes_quadrature_1d(n: int):
step = 1.0 / (n + 1)
coords = np.linspace(step, 1.0 - step, n)
# Weisstein, Eric W. "Newton-Cotes Formulas." From MathWorld--A Wolfram Web Resource.
# https://mathworld.wolfram.com/Newton-CotesFormulas.html
if n == 1:
weights = np.array([1.0])
elif n == 2:
weights = np.array([0.5, 0.5])
elif n == 3:
weights = np.array([2.0, -1.0, 2.0]) / 3.0
elif n == 4:
weights = np.array([11.0, 1.0, 1.0, 11.0]) / 24.0
elif n == 5:
weights = np.array([11.0, -14.0, 26.0, -14.0, 11.0]) / 20.0
elif n == 6:
weights = np.array([611.0, -453.0, 562.0, 562.0, -453.0, 611.0]) / 1440.0
elif n == 7:
weights = np.array([460.0, -954.0, 2196.0, -2459.0, 2196.0, -954.0, 460.0]) / 945.0
else:
raise NotImplementedError
return coords, weights
def _closed_newton_cotes_quadrature_1d(n: int):
coords = np.linspace(0.0, 1.0, n)
# OEIS: A093735, A093736
if n == 2:
weights = np.array([1.0, 1.0]) / 2.0
elif n == 3:
weights = np.array([1.0, 4.0, 1.0]) / 3.0
elif n == 4:
weights = np.array([3.0, 9.0, 9.0, 3.0]) / 8.0
elif n == 5:
weights = np.array([14.0, 64.0, 24.0, 64.0, 14.0]) / 45.0
elif n == 6:
weights = np.array([95.0 / 288.0, 125.0 / 96.0, 125.0 / 144.0, 125.0 / 144.0, 125.0 / 96.0, 95.0 / 288.0])
elif n == 7:
weights = np.array([41, 54, 27, 68, 27, 54, 41], dtype=float) / np.array(
[140, 35, 140, 35, 140, 35, 140], dtype=float
)
elif n == 8:
weights = np.array(
[
5257,
25039,
343,
20923,
20923,
343,
25039,
5257,
]
) / np.array(
[
17280,
17280,
640,
17280,
17280,
640,
17280,
17280,
],
dtype=float,
)
else:
raise NotImplementedError
# Normalize with interval length
weights = weights / (n - 1)
return coords, weights
def quadrature_1d(point_count: int, family: Polynomial):
"""Return quadrature points and weights for the given family and point count"""
if family == Polynomial.GAUSS_LEGENDRE:
return _gauss_legendre_quadrature_1d(point_count)
if family == Polynomial.LOBATTO_GAUSS_LEGENDRE:
return _lobatto_gauss_legendre_quadrature_1d(point_count)
if family == Polynomial.EQUISPACED_CLOSED:
return _closed_newton_cotes_quadrature_1d(point_count)
if family == Polynomial.EQUISPACED_OPEN:
return _open_newton_cotes_quadrature_1d(point_count)
raise NotImplementedError
def lagrange_scales(coords: np.array):
"""Return the scaling factors for Lagrange polynomials with roots at coords"""
lagrange_scale = np.empty_like(coords)
for i in range(len(coords)):
deltas = coords[i] - coords
deltas[i] = 1.0
lagrange_scale[i] = 1.0 / np.prod(deltas)
return lagrange_scale
| warp-main | warp/fem/polynomial.py |
from typing import Any
import warp as wp
from warp.fem import domain
from warp.fem.types import ElementIndex, Coords
from ..polynomial import Polynomial
class Quadrature:
"""Interface class for quadrature rules"""
Arg: wp.codegen.Struct
"""Structure containing arguments to be passed to device functions"""
def __init__(self, domain: domain.GeometryDomain):
self._domain = domain
@property
def domain(self):
"""Domain over which this quadrature is defined"""
return self._domain
def eval_arg_value(self, device) -> wp.codegen.StructInstance:
"""
Value of the argument to be passed to device
"""
pass
def total_point_count(self):
"""Total number of quadrature points over the domain"""
pass
def point_count(arg: Any, element_index: ElementIndex):
"""Number of quadrature points for a given element"""
pass
def point_coords(arg: Any, element_index: ElementIndex, qp_index: int):
"""Coordinates in element of the qp_index'th quadrature point"""
pass
def point_weight(arg: Any, element_index: ElementIndex, qp_index: int):
"""Weight of the qp_index'th quadrature point"""
pass
def __str__(self) -> str:
return self.name
class RegularQuadrature(Quadrature):
"""Regular quadrature formula, using a constant set of quadrature points per element"""
def __init__(
self,
domain: domain.GeometryDomain,
order: int,
family: Polynomial = None,
):
super().__init__(domain)
self.family = family
self.order = order
self._element_quadrature = domain.reference_element().instantiate_quadrature(order, family)
N = wp.constant(len(self.points))
WeightVec = wp.vec(length=N, dtype=wp.float32)
CoordMat = wp.mat(shape=(N, 3), dtype=wp.float32)
POINTS = wp.constant(CoordMat(self.points))
WEIGHTS = wp.constant(WeightVec(self.weights))
self.point_count = self._make_point_count(N)
self.point_index = self._make_point_index(N)
self.point_coords = self._make_point_coords(POINTS, self.name)
self.point_weight = self._make_point_weight(WEIGHTS, self.name)
@property
def name(self):
return (
f"{self.__class__.__name__}_{self.domain.reference_element().__class__.__name__}_{self.family}_{self.order}"
)
def __str__(self) -> str:
return self.name
def total_point_count(self):
return len(self.points) * self.domain.geometry_element_count()
@property
def points(self):
return self._element_quadrature[0]
@property
def weights(self):
return self._element_quadrature[1]
@wp.struct
class Arg:
pass
def arg_value(self, device) -> Arg:
arg = RegularQuadrature.Arg()
return arg
@staticmethod
def _make_point_count(N):
def point_count(arg: RegularQuadrature.Arg, element_index: ElementIndex):
return N
from warp.fem.cache import get_func
return get_func(point_count, str(N))
@staticmethod
def _make_point_coords(POINTS, name):
def point_coords(arg: RegularQuadrature.Arg, element_index: ElementIndex, index: int):
return Coords(POINTS[index, 0], POINTS[index, 1], POINTS[index, 2])
from warp.fem.cache import get_func
return get_func(point_coords, name)
@staticmethod
def _make_point_weight(WEIGHTS, name):
def point_weight(arg: RegularQuadrature.Arg, element_index: ElementIndex, index: int):
return WEIGHTS[index]
from warp.fem.cache import get_func
return get_func(point_weight, name)
@staticmethod
def _make_point_index(N):
def point_index(arg: RegularQuadrature.Arg, element_index: ElementIndex, index: int):
return N * element_index + index
from warp.fem.cache import get_func
return get_func(point_index, str(N))
| warp-main | warp/fem/quadrature/quadrature.py |
from .quadrature import Quadrature, RegularQuadrature
from .pic_quadrature import PicQuadrature
| warp-main | warp/fem/quadrature/__init__.py |
import warp as wp
from warp.fem.domain import GeometryDomain
from warp.fem.types import ElementIndex, Coords
from warp.fem.utils import compress_node_indices
from .quadrature import Quadrature
wp.set_module_options({"enable_backward": False})
class PicQuadrature(Quadrature):
"""Particle-based quadrature formula, using a global set of points irregularely spread out over geometry elements.
Useful for Particle-In-Cell and derived methods.
"""
def __init__(
self,
domain: GeometryDomain,
positions: "wp.array()",
measures: "wp.array(dtype=float)",
):
super().__init__(domain)
self.positions = positions
self.measures = measures
self._bin_particles()
@property
def name(self):
return f"{self.__class__.__name__}"
@Quadrature.domain.setter
def domain(self, domain: GeometryDomain):
# Allow changing the quadrature domain as long as underlying geometry and element kind are the same
if self.domain is not None and (
domain.geometry != self.domain.geometry or domain.element_kind != self.domain.element_kind
):
raise RuntimeError(
"Cannot change the domain to that of a different Geometry and/or using different element kinds."
)
self._domain = domain
@wp.struct
class Arg:
cell_particle_offsets: wp.array(dtype=int)
cell_particle_indices: wp.array(dtype=int)
particle_fraction: wp.array(dtype=float)
particle_coords: wp.array(dtype=Coords)
def arg_value(self, device) -> Arg:
arg = PicQuadrature.Arg()
arg.cell_particle_offsets = self._cell_particle_offsets.to(device)
arg.cell_particle_indices = self._cell_particle_indices.to(device)
arg.particle_fraction = self._particle_fraction.to(device)
arg.particle_coords = self._particle_coords.to(device)
return arg
def total_point_count(self):
return self.positions.shape[0]
@wp.func
def point_count(arg: Arg, element_index: ElementIndex):
return arg.cell_particle_offsets[element_index + 1] - arg.cell_particle_offsets[element_index]
@wp.func
def point_coords(arg: Arg, element_index: ElementIndex, index: int):
particle_index = arg.cell_particle_indices[arg.cell_particle_offsets[element_index] + index]
return arg.particle_coords[particle_index]
@wp.func
def point_weight(arg: Arg, element_index: ElementIndex, index: int):
particle_index = arg.cell_particle_indices[arg.cell_particle_offsets[element_index] + index]
return arg.particle_fraction[particle_index]
@wp.func
def point_index(arg: Arg, element_index: ElementIndex, index: int):
particle_index = arg.cell_particle_indices[arg.cell_particle_offsets[element_index] + index]
return particle_index
def fill_element_mask(self, mask: "wp.array(dtype=int)"):
"""Fills a mask array such that all non-empty elements are set to 1, all empty elements to zero.
Args:
mask: Int warp array with size at least equal to `self.domain.geometry_element_count()`
"""
wp.launch(
kernel=PicQuadrature._fill_mask_kernel,
dim=self.domain.geometry_element_count(),
device=mask.device,
inputs=[self._cell_particle_offsets, mask],
)
@wp.kernel
def _fill_mask_kernel(
element_particle_offsets: wp.array(dtype=int),
element_mask: wp.array(dtype=int),
):
i = wp.tid()
element_mask[i] = wp.select(element_particle_offsets[i] == element_particle_offsets[i + 1], 1, 0)
def _bin_particles(self):
from warp.fem import cache
def bin_particles_fn(
cell_arg_value: self.domain.ElementArg,
positions: wp.array(dtype=self.positions.dtype),
measures: wp.array(dtype=float),
cell_index: wp.array(dtype=ElementIndex),
cell_coords: wp.array(dtype=Coords),
cell_fraction: wp.array(dtype=float),
):
p = wp.tid()
sample = self.domain.element_lookup(cell_arg_value, positions[p])
cell_index[p] = sample.element_index
cell_coords[p] = sample.element_coords
cell_fraction[p] = measures[p] / self.domain.element_measure(cell_arg_value, sample)
bin_particles = cache.get_kernel(
bin_particles_fn,
suffix=f"{self.domain.name}",
)
device = self.positions.device
cell_index = wp.empty(shape=self.positions.shape, dtype=int, device=device)
self._particle_coords = wp.empty(shape=self.positions.shape, dtype=Coords, device=device)
self._particle_fraction = wp.empty(shape=self.positions.shape, dtype=float, device=device)
wp.launch(
dim=self.positions.shape[0],
kernel=bin_particles,
inputs=[
self.domain.element_arg_value(device),
self.positions,
self.measures,
cell_index,
self._particle_coords,
self._particle_fraction,
],
device=device,
)
self._cell_particle_offsets, self._cell_particle_indices, self._cell_count, _ = compress_node_indices(
self.domain.geometry_element_count(), cell_index
)
| warp-main | warp/fem/quadrature/pic_quadrature.py |
import warp as wp
from warp.fem.domain import GeometryDomain
from warp.fem.space import FunctionSpace, SpacePartition
from warp.fem.types import Sample, get_node_index_in_element
from warp.fem import utils, cache
class TrialField:
"""Field defined over a domain that can be used as a trial function"""
def __init__(
self,
space: FunctionSpace,
space_partition: SpacePartition,
domain: GeometryDomain,
):
if domain.dimension() == space.DIMENSION - 1:
space = space.trace()
if domain.dimension() != space.DIMENSION:
raise ValueError("Incompatible space and domain dimensions")
self.space = space
self.domain = domain
self.space_partition = space_partition
self.name = self.space.name + "Trial"
self.eval_degree = TrialField._make_eval_degree(self.space)
self.eval_inner = TrialField._make_eval_inner(self.space)
self.eval_grad_inner = TrialField._make_eval_grad_inner(self.space)
self.eval_outer = TrialField._make_eval_outer(self.space)
self.eval_grad_outer = TrialField._make_eval_grad_outer(self.space)
self.at_node = TrialField._make_at_node(self.space)
def partition_node_count(self) -> int:
return self.space_partition.node_count()
@property
def EvalArg(self) -> wp.codegen.Struct:
return self.space.SpaceArg
def eval_arg_value(self, device) -> wp.codegen.StructInstance:
return self.space.space_arg_value(device)
@staticmethod
def _make_eval_degree(space: FunctionSpace):
ORDER = space.ORDER
def degree(args: space.SpaceArg):
return ORDER
return cache.get_func(degree, space)
@staticmethod
def _make_eval_inner(space: FunctionSpace):
def eval_trial(args: space.SpaceArg, s: Sample):
weight = space.element_inner_weight(
args,
s.element_index,
s.element_coords,
get_node_index_in_element(s.trial_dof),
)
return weight * space.unit_dof_value(args, s.trial_dof)
return cache.get_func(eval_trial, space.name)
@staticmethod
def _make_eval_grad_inner(space: FunctionSpace):
if wp.types.type_is_matrix(space.dtype):
# There is no Warp high-order tensor type to represent matrix gradients
return None
def eval_nabla_trial(args: space.SpaceArg, s: Sample):
nabla_weight = space.element_inner_weight_gradient(
args,
s.element_index,
s.element_coords,
get_node_index_in_element(s.trial_dof),
)
return utils.generalized_outer(
nabla_weight,
space.unit_dof_value(args, s.trial_dof),
)
return cache.get_func(eval_nabla_trial, space.name)
@staticmethod
def _make_eval_outer(space: FunctionSpace):
def eval_trial_outer(args: space.SpaceArg, s: Sample):
weight = space.element_outer_weight(
args,
s.element_index,
s.element_coords,
get_node_index_in_element(s.trial_dof),
)
return weight * space.unit_dof_value(args, s.trial_dof)
return cache.get_func(eval_trial_outer, space.name)
@staticmethod
def _make_eval_grad_outer(space: FunctionSpace):
if wp.types.type_is_matrix(space.dtype):
# There is no Warp high-order tensor type to represent matrix gradients
return None
def eval_nabla_trial_outer(args: space.SpaceArg, s: Sample):
nabla_weight = space.element_outer_weight_gradient(
args,
s.element_index,
s.element_coords,
get_node_index_in_element(s.trial_dof),
)
return utils.generalized_outer(
nabla_weight,
space.unit_dof_value(args, s.trial_dof),
)
return cache.get_func(eval_nabla_trial_outer, space.name)
@staticmethod
def _make_at_node(space: FunctionSpace):
def at_node(args: space.SpaceArg, s: Sample):
node_coords = space.node_coords_in_element(args, s.element_index, get_node_index_in_element(s.trial_dof))
return Sample(s.element_index, node_coords, s.qp_index, s.qp_weight, s.test_dof, s.trial_dof)
return cache.get_func(at_node, space.name)
| warp-main | warp/fem/field/trial.py |
from typing import Union, Optional
from warp.fem.domain import GeometryDomain, Cells
from warp.fem.space import FunctionSpace, SpaceRestriction, SpacePartition, make_space_partition, make_space_restriction
from .discrete_field import DiscreteField
from .restriction import FieldRestriction
from .test import TestField
from .trial import TrialField
from .nodal_field import NodalField
FieldLike = Union[DiscreteField, FieldRestriction, TestField, TrialField]
def make_restriction(
field: DiscreteField,
space_restriction: Optional[SpaceRestriction] = None,
domain: Optional[GeometryDomain] = None,
device=None,
) -> FieldRestriction:
"""
Restricts a discrete field to a subset of elements.
Args:
field: the discrete field to restrict
space_restriction: the function space restriction defining the subset of elements to consider
domain: if ``space_restriction`` is not provided, the :py:class:`Domain` defining the subset of elements to consider
device: Warp device on which to perform and store computations
Returns:
the field restriction
"""
if space_restriction is None:
space_restriction = make_space_restriction(
space=field.space, space_partition=field.space_partition, domain=domain, device=device
)
return FieldRestriction(field=field, space_restriction=space_restriction)
def make_test(
space: Union[FunctionSpace, SpaceRestriction] = None,
space_partition: SpacePartition = None,
domain: GeometryDomain = None,
device=None,
) -> TestField:
"""
Constructs a test field over a function space or its restriction
Args:
space: the function space or function space restriction
space_partition: if ``space`` is a whole function space, the optional subset of node indices to consider
domain: if ``space`` is a whole function space, the optional subset of elements to consider
device: Warp device on which to perform and store computations
Returns:
the test field
"""
if not isinstance(space, SpaceRestriction):
if space is None:
space = space_partition.space
if domain is None:
domain = Cells(geometry=space.geometry)
if space_partition is None:
space_partition = make_space_partition(space, domain.geometry_partition)
space = make_space_restriction(space=space, space_partition=space_partition, domain=domain, device=device)
return TestField(space)
def make_trial(
space: Union[FunctionSpace, SpaceRestriction] = None,
space_partition: SpacePartition = None,
domain: GeometryDomain = None,
) -> TrialField:
"""
Constructs a trial field over a function space or partition
Args:
space: the function space or function space restriction
space_partition: if ``space`` is a whole function space, the optional subset of node indices to consider
domain: if ``space`` is a whole function space, the optional subset of elements to consider
device: Warp device on which to perform and store computations
Returns:
the trial field
"""
if isinstance(space, SpaceRestriction):
domain = space.domain
space = space.space
space_partition = space.space_partition
if space is None:
space = space_partition.space
if domain is None:
domain = Cells(geometry=space.geometry)
if space_partition is None:
space_partition = make_space_partition(space, domain.geometry_partition)
return TrialField(space, space_partition, domain)
| warp-main | warp/fem/field/__init__.py |
import warp as wp
from warp.fem.space import SpaceRestriction, FunctionSpace
from warp.fem.types import Sample, get_node_index_in_element
from warp.fem import utils, cache
class TestField:
"""Field defined over a space restriction that can be used as a test function"""
def __init__(self, space_restriction: SpaceRestriction):
self.space_restriction = space_restriction
self.space_partition = self.space_restriction.space_partition
self.space = self.space_restriction.space
self.domain = self.space_restriction.domain
self.name = self.space.name + "Test"
self.eval_degree = TestField._make_eval_degree(self.space)
self.eval_inner = TestField._make_eval_inner(self.space)
self.eval_grad_inner = TestField._make_eval_grad_inner(self.space)
self.eval_outer = TestField._make_eval_outer(self.space)
self.eval_grad_outer = TestField._make_eval_grad_outer(self.space)
self.at_node = TestField._make_at_node(self.space)
@property
def EvalArg(self) -> wp.codegen.Struct:
return self.space.SpaceArg
def eval_arg_value(self, device) -> wp.codegen.StructInstance:
return self.space.space_arg_value(device)
@staticmethod
def _make_eval_degree(space: FunctionSpace):
ORDER = space.ORDER
def degree(args: space.SpaceArg):
return ORDER
return cache.get_func(degree, space)
@staticmethod
def _make_eval_inner(space: FunctionSpace):
def eval_test(args: space.SpaceArg, s: Sample):
weight = space.element_inner_weight(
args,
s.element_index,
s.element_coords,
get_node_index_in_element(s.test_dof),
)
return weight * space.unit_dof_value(args, s.test_dof)
return cache.get_func(eval_test, space.name)
@staticmethod
def _make_eval_grad_inner(space: FunctionSpace):
if wp.types.type_is_matrix(space.dtype):
# There is no Warp high-order tensor type to represent matrix gradients
return None
def eval_nabla_test_inner(args: space.SpaceArg, s: Sample):
nabla_weight = space.element_inner_weight_gradient(
args,
s.element_index,
s.element_coords,
get_node_index_in_element(s.test_dof),
)
return utils.generalized_outer(
nabla_weight,
space.unit_dof_value(args, s.test_dof),
)
return cache.get_func(eval_nabla_test_inner, space.name)
@staticmethod
def _make_eval_outer(space: FunctionSpace):
def eval_test_outer(args: space.SpaceArg, s: Sample):
weight = space.element_outer_weight(
args,
s.element_index,
s.element_coords,
get_node_index_in_element(s.test_dof),
)
return weight * space.unit_dof_value(args, s.test_dof)
return cache.get_func(eval_test_outer, space.name)
@staticmethod
def _make_eval_grad_outer(space: FunctionSpace):
if wp.types.type_is_matrix(space.dtype):
# There is no Warp high-order tensor type to represent matrix gradients
return None
def eval_nabla_test(args: space.SpaceArg, s: Sample):
nabla_weight = space.element_outer_weight_gradient(
args,
s.element_index,
s.element_coords,
get_node_index_in_element(s.test_dof),
)
return utils.generalized_outer(
nabla_weight,
space.unit_dof_value(args, s.test_dof),
)
return cache.get_func(eval_nabla_test, space.name)
@staticmethod
def _make_at_node(space: FunctionSpace):
def at_node(args: space.SpaceArg, s: Sample):
node_coords = space.node_coords_in_element(args, s.element_index, get_node_index_in_element(s.test_dof))
return Sample(s.element_index, node_coords, s.qp_index, s.qp_weight, s.test_dof, s.trial_dof)
return cache.get_func(at_node, space.name)
| warp-main | warp/fem/field/test.py |
from typing import Any
import warp as wp
from warp.fem.types import Sample
from warp.fem.space import FunctionSpace, SpacePartition
class DiscreteField:
"""Field defined over a partition of a discrete function space"""
EvalArg: wp.codegen.Struct
"""Structure containing arguments passed to device functions for field evaluation"""
def __init__(self, space: FunctionSpace, space_partition: SpacePartition):
self.space = space
self.space_partition = space_partition
self.dtype = self.space.dtype
self.dof_dtype = self.space.dof_dtype
def eval_arg_value(self, device) -> wp.codegen.StructInstance:
raise NotImplementedError
@property
def dof_values(self) -> wp.array:
"""Array of degrees of freedom values"""
raise NotImplementedError
@dof_values.setter
def dof_values(self, values: wp.array):
"""Sets degrees of freedom values from an array"""
raise NotImplementedError
@property
def name(self) -> str:
return f"{self.__class__.__qualname__}_{self.space.name}_{self.space_partition.name}"
@property
def __str__(self) -> str:
return self.name
def trace(self) -> FunctionSpace:
"""Trace of this field over a lower-dimensional function space"""
raise NotImplementedError
def eval_arg_value(self, device):
"""Value of arguments to be passed to device functions"""
raise NotImplementedError
def set_node_value(args: Any, node_index: int, value: Any):
"""Device function setting the value at given node"""
raise NotImplementedError
def eval_inner(args: Any, s: "Sample"):
"""Device function evaluating the inner field value at a sample point"""
raise NotImplementedError
def eval_grad_inner(args: Any, s: "Sample"):
"""Device function evaluating the inner field gradient at a sample point"""
raise NotImplementedError
def eval_outer(args: Any, s: "Sample"):
"""Device function evaluating the outer field value at a sample point"""
raise NotImplementedError
def eval_grad_outer(args: Any, s: "Sample"):
"""Device function evaluating the outer field gradient at a sample point"""
raise NotImplementedError
@staticmethod
def _make_eval_degree(EvalArg, space: FunctionSpace):
ORDER = space.ORDER
def degree(args: EvalArg):
return ORDER
from warp.fem import cache
return cache.get_func(degree, space)
| warp-main | warp/fem/field/discrete_field.py |
from warp.fem.space import SpaceRestriction
from .discrete_field import DiscreteField
class FieldRestriction:
"""Restriction of a space to a given GeometryDomain"""
def __init__(self, space_restriction: SpaceRestriction, field: DiscreteField):
if field.space.DIMENSION - 1 == space_restriction.space.DIMENSION:
field = field.trace()
if field.space.DIMENSION != space_restriction.space.DIMENSION:
raise ValueError("Incompatible space and field dimensions")
self.space_restriction = space_restriction
self.space = self.space_restriction.space
self.domain = self.space_restriction.domain
self.field = field
| warp-main | warp/fem/field/restriction.py |
import warp as wp
from warp.fem.space import NodalFunctionSpace, SpacePartition
from warp.fem import cache, utils
from warp.fem.types import Sample, ElementIndex, NULL_NODE_INDEX
from .discrete_field import DiscreteField
class NodalField(DiscreteField):
def __init__(self, space_partition: SpacePartition, space: NodalFunctionSpace = None):
if space is None:
space = space_partition.space
super().__init__(space, space_partition)
self._dof_values = wp.zeros(n=self.space_partition.node_count(), dtype=self.dof_dtype)
self.EvalArg = NodalField._make_eval_arg(self.space, self.space_partition)
self.eval_degree = DiscreteField._make_eval_degree(self.EvalArg, self.space)
self.set_node_value = NodalField._make_set_node_value(self.EvalArg, self.space)
read_node_value = NodalField._make_read_node_value(self.EvalArg, self.space, self.space_partition)
self.eval_inner = NodalField._make_eval_inner(self.EvalArg, self.space, read_node_value)
self.eval_outer = NodalField._make_eval_outer(self.EvalArg, self.space, read_node_value)
self.eval_grad_inner = NodalField._make_eval_grad_inner(self.EvalArg, self.space, read_node_value)
self.eval_grad_outer = NodalField._make_eval_grad_outer(self.EvalArg, self.space, read_node_value)
def eval_arg_value(self, device):
arg = self.EvalArg()
arg.space_arg = self.space.space_arg_value(device)
arg.partition_arg = self.space_partition.partition_arg_value(device)
arg.dof_values = self._dof_values.to(device)
return arg
@property
def dof_values(self):
return self._dof_values
@dof_values.setter
def dof_values(self, values):
if isinstance(values, wp.array):
self._dof_values = values
else:
self._dof_values = wp.array(values, dtype=self.dof_dtype)
class Trace(DiscreteField):
def __init__(self, field):
self._field = field
super().__init__(field.space.trace(), field.space_partition)
self.EvalArg = field.EvalArg
self.eval_degree = DiscreteField._make_eval_degree(self.EvalArg, self.space)
self.eval_arg_value = field.eval_arg_value
self.set_node_value = field.set_node_value
read_node_value = NodalField._make_read_node_value(self.EvalArg, self.space, self.space_partition)
self.eval_inner = NodalField._make_eval_inner(self.EvalArg, self.space, read_node_value)
self.eval_outer = NodalField._make_eval_outer(self.EvalArg, self.space, read_node_value)
self.eval_grad_inner = NodalField._make_eval_grad_inner(self.EvalArg, self.space, read_node_value)
self.eval_grad_outer = NodalField._make_eval_grad_outer(self.EvalArg, self.space, read_node_value)
def trace(self) -> Trace:
trace_field = NodalField.Trace(self)
return trace_field
@staticmethod
def _make_eval_arg(space: NodalFunctionSpace, space_partition: SpacePartition):
from warp.fem import cache
class EvalArg:
space_arg: space.SpaceArg
partition_arg: space_partition.PartitionArg
dof_values: wp.array(dtype=space.dof_dtype)
EvalArg.__qualname__ = f"{space.name}_{space_partition.name}_FieldEvalArg"
return cache.get_struct(EvalArg)
@staticmethod
def _make_set_node_value(EvalArg, space: NodalFunctionSpace):
def set_node_value(args: EvalArg, partition_node_index: int, value: space.dtype):
args.dof_values[partition_node_index] = space.dof_mapper.value_to_dof(value)
return cache.get_func(set_node_value, space)
@staticmethod
def _make_read_node_value(EvalArg, space: NodalFunctionSpace, space_partition: SpacePartition):
def read_node_value(args: EvalArg, geo_element_index: ElementIndex, node_index_in_elt: int):
nidx = space.element_node_index(args.space_arg, geo_element_index, node_index_in_elt)
pidx = space_partition.partition_node_index(args.partition_arg, nidx)
if pidx == NULL_NODE_INDEX:
return space.dtype(0.0)
return space.dof_mapper.dof_to_value(args.dof_values[pidx])
return cache.get_func(read_node_value, f"{space}_{space_partition}")
@staticmethod
def _make_eval_inner(
EvalArg,
space: NodalFunctionSpace,
read_node_value: wp.Function,
):
NODES_PER_ELEMENT = space.NODES_PER_ELEMENT
def eval_inner(args: EvalArg, s: Sample):
res = space.element_inner_weight(args.space_arg, s.element_index, s.element_coords, 0) * read_node_value(
args, s.element_index, 0
)
for k in range(1, NODES_PER_ELEMENT):
res += space.element_inner_weight(
args.space_arg, s.element_index, s.element_coords, k
) * read_node_value(args, s.element_index, k)
return res
return cache.get_func(eval_inner, read_node_value.key)
@staticmethod
def _make_eval_grad_inner(
EvalArg,
space: NodalFunctionSpace,
read_node_value: wp.Function,
):
NODES_PER_ELEMENT = space.NODES_PER_ELEMENT
if wp.types.type_is_matrix(space.dtype):
# There is no Warp high-order tensor type to represent matrix gradients
return None
def eval_grad_inner(args: EvalArg, s: Sample):
res = utils.generalized_outer(
space.element_inner_weight_gradient(args.space_arg, s.element_index, s.element_coords, 0),
read_node_value(args, s.element_index, 0),
)
for k in range(1, NODES_PER_ELEMENT):
res += utils.generalized_outer(
space.element_inner_weight_gradient(args.space_arg, s.element_index, s.element_coords, k),
read_node_value(args, s.element_index, k),
)
return res
return cache.get_func(eval_grad_inner, read_node_value.key)
@staticmethod
def _make_eval_outer(
EvalArg,
space: NodalFunctionSpace,
read_node_value: wp.Function,
):
NODES_PER_ELEMENT = space.NODES_PER_ELEMENT
def eval_outer(args: EvalArg, s: Sample):
res = space.element_outer_weight(args.space_arg, s.element_index, s.element_coords, 0) * read_node_value(
args, s.element_index, 0
)
for k in range(1, NODES_PER_ELEMENT):
res += space.element_outer_weight(
args.space_arg, s.element_index, s.element_coords, k
) * read_node_value(args, s.element_index, k)
return res
return cache.get_func(eval_outer, read_node_value.key)
@staticmethod
def _make_eval_grad_outer(
EvalArg,
space: NodalFunctionSpace,
read_node_value: wp.Function,
):
NODES_PER_ELEMENT = space.NODES_PER_ELEMENT
if wp.types.type_is_matrix(space.dtype):
# There is no Warp high-order tensor type to represent matrix gradients
return None
def eval_grad_outer(args: EvalArg, s: Sample):
res = utils.generalized_outer(
space.element_outer_weight_gradient(args.space_arg, s.element_index, s.element_coords, 0),
read_node_value(args, s.element_index, 0),
)
for k in range(1, NODES_PER_ELEMENT):
res += utils.generalized_outer(
space.element_outer_weight_gradient(args.space_arg, s.element_index, s.element_coords, k),
read_node_value(args, s.element_index, k),
)
return res
return cache.get_func(eval_grad_outer, read_node_value.key)
| warp-main | warp/fem/field/nodal_field.py |
from typing import Any
import warp as wp
from warp.fem.types import ElementIndex, NULL_ELEMENT_INDEX
from warp.fem.utils import masked_indices
from .geometry import Geometry
wp.set_module_options({"enable_backward": False})
class GeometryPartition:
"""Base class for geometry partitions, i.e. subset of cells and sides"""
def __init__(self, geometry: Geometry):
self.geometry = geometry
def cell_count(self) -> int:
"""Number of cells that are 'owned' by this partition"""
raise NotImplementedError()
def side_count(self) -> int:
"""Number of sides that are 'owned' by this partition"""
raise NotImplementedError()
def boundary_side_count(self) -> int:
"""Number of geo-boundary sides that are 'owned' by this partition"""
raise NotImplementedError()
def frontier_side_count(self) -> int:
"""Number of sides with neighbors owned by this and another partition"""
raise NotImplementedError()
@property
def name(self) -> str:
return f"{self.geometry.name}_{self.__class__.__name__}"
def __str__(self) -> str:
return self.name
class WholeGeometryPartition(GeometryPartition):
"""Trivial (NOP) partition"""
def __init__(
self,
geometry: Geometry,
):
super().__init__(geometry)
self.SideArg = geometry.SideIndexArg
self.side_arg_value = geometry.side_index_arg_value
self.cell_index = WholeGeometryPartition._identity_element_index
self.partition_cell_index = WholeGeometryPartition._identity_element_index
self.side_index = WholeGeometryPartition._identity_element_index
self.boundary_side_index = geometry.boundary_side_index
self.frontier_side_index = WholeGeometryPartition._identity_element_index
def __eq__(self, other: GeometryPartition) -> bool:
# Ensures that two whole partition instances of the same geometry are considered equal
return isinstance(other, WholeGeometryPartition) and self.geometry == other.geometry
def cell_count(self) -> int:
return self.geometry.cell_count()
def side_count(self) -> int:
return self.geometry.side_count()
def boundary_side_count(self) -> int:
return self.geometry.boundary_side_count()
def frontier_side_count(self) -> int:
return 0
@wp.struct
class CellArg:
pass
def cell_arg_value(self, device):
arg = WholeGeometryPartition.CellArg()
return arg
@wp.func
def _identity_element_index(args: Any, idx: ElementIndex):
return idx
class CellBasedGeometryPartition(GeometryPartition):
"""Geometry partition based on a subset of cells. Interior, boundary and frontier sides are automatically categorized."""
def __init__(
self,
geometry: Geometry,
device=None,
):
super().__init__(geometry)
@wp.struct
class SideArg:
partition_side_indices: wp.array(dtype=int)
boundary_side_indices: wp.array(dtype=int)
frontier_side_indices: wp.array(dtype=int)
def side_count(self) -> int:
return self._partition_side_indices.shape[0]
def boundary_side_count(self) -> int:
return self._boundary_side_indices.shape[0]
def frontier_side_count(self) -> int:
return self._frontier_side_indices.shape[0]
def side_arg_value(self, device):
arg = LinearGeometryPartition.SideArg()
arg.partition_side_indices = self._partition_side_indices.to(device)
arg.boundary_side_indices = self._boundary_side_indices.to(device)
arg.frontier_side_indices = self._frontier_side_indices.to(device)
return arg
@wp.func
def side_index(args: SideArg, partition_side_index: int):
"""partition side to side index"""
return args.partition_side_indices[partition_side_index]
@wp.func
def boundary_side_index(args: SideArg, boundary_side_index: int):
"""Boundary side to side index"""
return args.boundary_side_indices[boundary_side_index]
@wp.func
def frontier_side_index(args: SideArg, frontier_side_index: int):
"""Frontier side to side index"""
return args.frontier_side_indices[frontier_side_index]
def compute_side_indices_from_cells(
self,
cell_arg_value: Any,
cell_inclusion_test_func: wp.Function,
device,
):
from warp.fem import cache
def count_side_fn(
geo_arg: self.geometry.SideArg,
cell_arg_value: Any,
partition_side_mask: wp.array(dtype=int),
boundary_side_mask: wp.array(dtype=int),
frontier_side_mask: wp.array(dtype=int),
):
side_index = wp.tid()
inner_cell_index = self.geometry.side_inner_cell_index(geo_arg, side_index)
outer_cell_index = self.geometry.side_outer_cell_index(geo_arg, side_index)
inner_in = cell_inclusion_test_func(cell_arg_value, inner_cell_index)
outer_in = cell_inclusion_test_func(cell_arg_value, outer_cell_index)
if inner_in:
# Inner neighbor in partition; count as partition side
partition_side_mask[side_index] = 1
# Inner and outer element as the same -- this is a boundary side
if inner_cell_index == outer_cell_index:
boundary_side_mask[side_index] = 1
if inner_in != outer_in:
# Exactly one neighbor in partition; count as frontier side
frontier_side_mask[side_index] = 1
count_sides = cache.get_kernel(
count_side_fn,
suffix=f"{self.geometry.name}_{cell_inclusion_test_func.key}",
)
partition_side_mask = wp.zeros(
shape=(self.geometry.side_count(),),
dtype=int,
device=device,
)
boundary_side_mask = wp.zeros(
shape=(self.geometry.side_count(),),
dtype=int,
device=device,
)
frontier_side_mask = wp.zeros(
shape=(self.geometry.side_count(),),
dtype=int,
device=device,
)
wp.launch(
dim=partition_side_mask.shape[0],
kernel=count_sides,
inputs=[
self.geometry.side_arg_value(device),
cell_arg_value,
partition_side_mask,
boundary_side_mask,
frontier_side_mask,
],
device=device,
)
# Convert counts to indices
self._partition_side_indices, _ = masked_indices(partition_side_mask)
self._boundary_side_indices, _ = masked_indices(boundary_side_mask)
self._frontier_side_indices, _ = masked_indices(frontier_side_mask)
class LinearGeometryPartition(CellBasedGeometryPartition):
def __init__(
self,
geometry: Geometry,
partition_rank: int,
partition_count: int,
device=None,
):
"""Creates a geometry partition by uniformly partionning cell indices
Args:
geometry: the geometry to partition
partition_rank: the index of the partition being created
partition_count: the number of partitions that will be created over the geometry
device: Warp device on which to perform and store computations
"""
super().__init__(geometry)
total_cell_count = geometry.cell_count()
cells_per_partition = (total_cell_count + partition_count - 1) // partition_count
self.cell_begin = cells_per_partition * partition_rank
self.cell_end = min(self.cell_begin + cells_per_partition, total_cell_count)
super().compute_side_indices_from_cells(
self.cell_arg_value(device),
LinearGeometryPartition._cell_inclusion_test,
device,
)
def cell_count(self) -> int:
return self.cell_end - self.cell_begin
@wp.struct
class CellArg:
cell_begin: int
cell_end: int
def cell_arg_value(self, device):
arg = LinearGeometryPartition.CellArg()
arg.cell_begin = self.cell_begin
arg.cell_end = self.cell_end
return arg
@wp.func
def cell_index(args: CellArg, partition_cell_index: int):
"""Partition cell to cell index"""
return args.cell_begin + partition_cell_index
@wp.func
def partition_cell_index(args: CellArg, cell_index: int):
"""Partition cell to cell index"""
if cell_index > args.cell_end:
return NULL_ELEMENT_INDEX
partition_cell_index = cell_index - args.cell_begin
if partition_cell_index < 0:
return NULL_ELEMENT_INDEX
return partition_cell_index
@wp.func
def _cell_inclusion_test(arg: CellArg, cell_index: int):
return cell_index >= arg.cell_begin and cell_index < arg.cell_end
class ExplicitGeometryPartition(CellBasedGeometryPartition):
def __init__(self, geometry: Geometry, cell_mask: "wp.array(dtype=int)"):
"""Creates a geometry partition by uniformly partionning cell indices
Args:
geometry: the geometry to partition
cell_mask: warp array of length ``geometry.cell_count()`` indicating which cells are selected. Array values must be either ``1`` (selected) or ``0`` (not selected).
"""
super().__init__(geometry)
self._cell_mask = cell_mask
self._cells, self._partition_cells = masked_indices(self._cell_mask)
super().compute_side_indices_from_cells(
self._cell_mask,
ExplicitGeometryPartition._cell_inclusion_test,
self._cell_mask.device,
)
def cell_count(self) -> int:
return self._cells.shape[0]
@wp.struct
class CellArg:
cell_index: wp.array(dtype=int)
partition_cell_index: wp.array(dtype=int)
def cell_arg_value(self, device):
arg = ExplicitGeometryPartition.CellArg()
arg.cell_index = self._cells.to(device)
arg.partition_cell_index = self._partition_cells.to(device)
return arg
@wp.func
def cell_index(args: CellArg, partition_cell_index: int):
return args.cell_index[partition_cell_index]
@wp.func
def partition_cell_index(args: CellArg, cell_index: int):
return args.partition_cell_index[cell_index]
@wp.func
def _cell_inclusion_test(mask: wp.array(dtype=int), cell_index: int):
return mask[cell_index] > 0
| warp-main | warp/fem/geometry/partition.py |
import warp as wp
from warp.fem.types import ElementIndex, Coords, vec2i, Sample, NULL_QP_INDEX, NULL_DOF_INDEX
from .geometry import Geometry
from .element import Square, LinearEdge
@wp.struct
class Grid2DCellArg:
res: vec2i
cell_size: wp.vec2
origin: wp.vec2
class Grid2D(Geometry):
"""Two-dimensional regular grid geometry"""
Permutation = wp.types.matrix(shape=(2, 2), dtype=int)
ROTATION = wp.constant(Permutation(0, 1, 1, 0))
def __init__(self, res: vec2i, bounds_lo: wp.vec2 = wp.vec2(0.0), bounds_hi: wp.vec2 = wp.vec2(1.0)):
"""Constructs a dense 2D grid
Args:
res: Resolution of the grid along each dimension
bounds_lo: Position of the lower bound of the axis-aligned grid
bounds_up: Position of the upper bound of the axis-aligned grid
"""
self.dimension = 2
self.bounds_lo = bounds_lo
self.bounds_hi = bounds_hi
self._res = res
@property
def extents(self) -> wp.vec2:
return self.bounds_hi - self.bounds_lo
@property
def cell_size(self) -> wp.vec2:
ex = self.extents
return wp.vec2(
ex[0] / self.res[0],
ex[1] / self.res[1],
)
def cell_count(self):
return self.res[0] * self.res[1]
def vertex_count(self):
return (self.res[0] + 1) * (self.res[1] + 1)
def side_count(self):
return 2 * self.cell_count() + self.res[0] + self.res[1]
def boundary_side_count(self):
return 2 * (self.res[0] + self.res[1])
def reference_cell(self) -> Square:
return Square()
def reference_side(self) -> LinearEdge:
return LinearEdge()
@property
def res(self):
return self._res
@property
def origin(self):
return self.bounds_lo
@property
def strides(self):
return vec2i(self.res[1], 1)
# Utility device functions
CellArg = Grid2DCellArg
Cell = vec2i
@wp.func
def _to_2d_index(x_stride: int, index: int):
x = index // x_stride
y = index - x_stride * x
return vec2i(x, y)
@wp.func
def _from_2d_index(x_stride: int, index: vec2i):
return x_stride * index[0] + index[1]
@wp.func
def cell_index(res: vec2i, cell: Cell):
return Grid2D._from_2d_index(res[1], cell)
@wp.func
def get_cell(res: vec2i, cell_index: ElementIndex):
return Grid2D._to_2d_index(res[1], cell_index)
@wp.struct
class Side:
axis: int # normal; 0: horizontal, 1: vertical
origin: vec2i # index of vertex at corner (0,0)
@wp.struct
class SideArg:
cell_count: int
axis_offsets: vec2i
cell_arg: Grid2DCellArg
SideIndexArg = SideArg
@wp.func
def _rotate(axis: int, vec: vec2i):
return vec2i(
vec[Grid2D.ROTATION[axis, 0]],
vec[Grid2D.ROTATION[axis, 1]],
)
@wp.func
def _rotate(axis: int, vec: wp.vec2):
return wp.vec2(
vec[Grid2D.ROTATION[axis, 0]],
vec[Grid2D.ROTATION[axis, 1]],
)
@wp.func
def side_index(arg: SideArg, side: Side):
alt_axis = Grid2D.ROTATION[side.axis, 0]
if side.origin[0] == arg.cell_arg.res[alt_axis]:
# Upper-boundary side
longitude = side.origin[1]
return 2 * arg.cell_count + arg.axis_offsets[side.axis] + longitude
cell_index = Grid2D.cell_index(arg.cell_arg.res, Grid2D._rotate(side.axis, side.origin))
return side.axis * arg.cell_count + cell_index
@wp.func
def get_side(arg: SideArg, side_index: ElementIndex):
if side_index < 2 * arg.cell_count:
axis = side_index // arg.cell_count
cell_index = side_index - axis * arg.cell_count
origin = Grid2D._rotate(axis, Grid2D.get_cell(arg.cell_arg.res, cell_index))
return Grid2D.Side(axis, origin)
axis_side_index = side_index - 2 * arg.cell_count
if axis_side_index < arg.axis_offsets[1]:
axis = 0
else:
axis = 1
altitude = arg.cell_arg.res[Grid2D.ROTATION[axis, 0]]
longitude = axis_side_index - arg.axis_offsets[axis]
origin_loc = vec2i(altitude, longitude)
return Grid2D.Side(axis, origin_loc)
# Geometry device interface
def cell_arg_value(self, device) -> CellArg:
args = self.CellArg()
args.res = self.res
args.cell_size = self.cell_size
args.origin = self.bounds_lo
return args
@wp.func
def cell_position(args: CellArg, s: Sample):
cell = Grid2D.get_cell(args.res, s.element_index)
return (
wp.vec2(
(float(cell[0]) + s.element_coords[0]) * args.cell_size[0],
(float(cell[1]) + s.element_coords[1]) * args.cell_size[1],
)
+ args.origin
)
@wp.func
def cell_lookup(args: CellArg, pos: wp.vec2):
loc_pos = wp.cw_div(pos - args.origin, args.cell_size)
x = wp.clamp(loc_pos[0], 0.0, float(args.res[0]))
y = wp.clamp(loc_pos[1], 0.0, float(args.res[1]))
x_cell = wp.min(wp.floor(x), float(args.res[0]) - 1.0)
y_cell = wp.min(wp.floor(y), float(args.res[1]) - 1.0)
coords = Coords(x - x_cell, y - y_cell, 0.0)
cell_index = Grid2D.cell_index(args.res, Grid2D.Cell(int(x_cell), int(y_cell)))
return Sample(cell_index, coords, NULL_QP_INDEX, 0.0, NULL_DOF_INDEX, NULL_DOF_INDEX)
@wp.func
def cell_lookup(args: CellArg, pos: wp.vec2, guess: Sample):
return Grid2D.cell_lookup(args, pos)
@wp.func
def cell_measure(args: CellArg, cell_index: ElementIndex, coords: Coords):
return args.cell_size[0] * args.cell_size[1]
@wp.func
def cell_measure(args: CellArg, s: Sample):
return Grid2D.cell_measure(args, s.element_index, s.element_coords)
@wp.func
def cell_measure_ratio(args: CellArg, s: Sample):
return 1.0
@wp.func
def cell_normal(args: CellArg, s: Sample):
return wp.vec2(0.0)
def side_arg_value(self, device) -> SideArg:
args = self.SideArg()
args.axis_offsets = vec2i(
0,
self.res[0],
)
args.cell_count = self.cell_count()
args.cell_arg = self.cell_arg_value(device)
return args
def side_index_arg_value(self, device) -> SideIndexArg:
return self.side_arg_value(device)
@wp.func
def boundary_side_index(args: SideArg, boundary_side_index: int):
"""Boundary side to side index"""
axis_side_index = boundary_side_index // 2
border = boundary_side_index - 2 * axis_side_index
if axis_side_index < args.axis_offsets[1]:
axis = 0
else:
axis = 1
longitude = axis_side_index - args.axis_offsets[axis]
altitude = border * args.cell_arg.res[axis]
side = Grid2D.Side(axis, vec2i(altitude, longitude))
return Grid2D.side_index(args, side)
@wp.func
def side_position(args: SideArg, s: Sample):
side = Grid2D.get_side(args, s.element_index)
local_pos = wp.vec2(
float(side.origin[0]),
float(side.origin[1]) + s.element_coords[0],
)
pos = args.cell_arg.origin + wp.cw_mul(Grid2D._rotate(side.axis, local_pos), args.cell_arg.cell_size)
return pos
@wp.func
def side_measure(args: SideArg, side_index: ElementIndex, coords: Coords):
side = Grid2D.get_side(args, side_index)
long_axis = Grid2D.ROTATION[side.axis, 1]
return args.cell_arg.cell_size[long_axis]
@wp.func
def side_measure(args: SideArg, s: Sample):
return args.cell_arg.cell_size
@wp.func
def side_measure_ratio(args: SideArg, s: Sample):
side = Grid2D.get_side(args, s.element_index)
alt_axis = Grid2D.ROTATION[side.axis, 0]
return 1.0 / args.cell_arg.cell_size[alt_axis]
@wp.func
def side_normal(args: SideArg, s: Sample):
side = Grid2D.get_side(args, s.element_index)
if side.origin[0] == 0:
sign = -1.0
else:
sign = 1.0
local_n = wp.vec2(sign, 0.0)
return Grid2D._rotate(side.axis, local_n)
@wp.func
def side_inner_cell_index(arg: SideArg, side_index: ElementIndex):
side = Grid2D.get_side(arg, side_index)
if side.origin[0] == 0:
inner_alt = 0
else:
inner_alt = side.origin[0] - 1
inner_origin = vec2i(inner_alt, side.origin[1])
cell = Grid2D._rotate(side.axis, inner_origin)
return Grid2D.cell_index(arg.cell_arg.res, cell)
@wp.func
def side_outer_cell_index(arg: SideArg, side_index: ElementIndex):
side = Grid2D.get_side(arg, side_index)
alt_axis = Grid2D.ROTATION[side.axis, 0]
if side.origin[0] == arg.cell_arg.res[alt_axis]:
outer_alt = arg.cell_arg.res[alt_axis] - 1
else:
outer_alt = side.origin[0]
outer_origin = vec2i(outer_alt, side.origin[1])
cell = Grid2D._rotate(side.axis, outer_origin)
return Grid2D.cell_index(arg.cell_arg.res, cell)
| warp-main | warp/fem/geometry/grid_2d.py |
from .element import Element
from .geometry import Geometry
from .partition import (
GeometryPartition,
WholeGeometryPartition,
LinearGeometryPartition,
ExplicitGeometryPartition,
)
from .grid_2d import Grid2D
from .grid_3d import Grid3D
from .trimesh_2d import Trimesh2D
from .tetmesh import Tetmesh | warp-main | warp/fem/geometry/__init__.py |
import warp as wp
from warp.fem.types import ElementIndex, Coords, Sample, NULL_QP_INDEX, NULL_DOF_INDEX
from warp.fem.types import vec2i, vec3i
from .geometry import Geometry
from .element import Square, Cube
@wp.struct
class Grid3DCellArg:
res: vec3i
cell_size: wp.vec3
origin: wp.vec3
class Grid3D(Geometry):
"""Three-dimensional regular grid geometry"""
Permutation = wp.types.matrix(shape=(3, 3), dtype=int)
LOC_TO_WORLD = wp.constant(Permutation(0, 1, 2, 1, 2, 0, 2, 0, 1))
WORLD_TO_LOC = wp.constant(Permutation(0, 1, 2, 2, 0, 1, 1, 2, 0))
def __init__(self, res: vec3i, bounds_lo: wp.vec3 = wp.vec3(0.0), bounds_hi: wp.vec3 = wp.vec3(1.0)):
"""Constructs a dense 3D grid
Args:
res: Resolution of the grid along each dimension
bounds_lo: Position of the lower bound of the axis-aligned grid
bounds_up: Position of the upper bound of the axis-aligned grid
"""
self.dimension = 3
self.bounds_lo = bounds_lo
self.bounds_hi = bounds_hi
self._res = res
@property
def extents(self) -> wp.vec3:
return self.bounds_hi - self.bounds_lo
@property
def cell_size(self) -> wp.vec3:
ex = self.extents
return wp.vec3(
ex[0] / self.res[0],
ex[1] / self.res[1],
ex[2] / self.res[2],
)
def cell_count(self):
return self.res[0] * self.res[1] * self.res[2]
def vertex_count(self):
return (self.res[0] + 1) * (self.res[1] + 1) * (self.res[2] + 1)
def side_count(self):
return (
(self.res[0] + 1) * (self.res[1]) * (self.res[2])
+ (self.res[0]) * (self.res[1] + 1) * (self.res[2])
+ (self.res[0]) * (self.res[1]) * (self.res[2] + 1)
)
def boundary_side_count(self):
return 2 * (self.res[1]) * (self.res[2]) + (self.res[0]) * 2 * (self.res[2]) + (self.res[0]) * (self.res[1]) * 2
def reference_cell(self) -> Cube:
return Cube()
def reference_side(self) -> Square:
return Square()
@property
def res(self):
return self._res
@property
def origin(self):
return self.bounds_lo
@property
def strides(self):
return vec3i(self.res[1] * self.res[2], self.res[2], 1)
# Utility device functions
CellArg = Grid3DCellArg
Cell = vec3i
@wp.func
def _to_3d_index(strides: vec2i, index: int):
x = index // strides[0]
y = (index - strides[0] * x) // strides[1]
z = index - strides[0] * x - strides[1] * y
return vec3i(x, y, z)
@wp.func
def _from_3d_index(strides: vec2i, index: vec3i):
return strides[0] * index[0] + strides[1] * index[1] + index[2]
@wp.func
def cell_index(res: vec3i, cell: Cell):
strides = vec2i(res[1] * res[2], res[2])
return Grid3D._from_3d_index(strides, cell)
@wp.func
def get_cell(res: vec3i, cell_index: ElementIndex):
strides = vec2i(res[1] * res[2], res[2])
return Grid3D._to_3d_index(strides, cell_index)
@wp.struct
class Side:
axis: int # normal
origin: vec3i # index of vertex at corner (0,0,0)
@wp.struct
class SideArg:
cell_count: int
axis_offsets: vec3i
cell_arg: Grid3DCellArg
SideIndexArg = SideArg
@wp.func
def _world_to_local(axis: int, vec: vec3i):
return vec3i(
vec[Grid3D.LOC_TO_WORLD[axis, 0]],
vec[Grid3D.LOC_TO_WORLD[axis, 1]],
vec[Grid3D.LOC_TO_WORLD[axis, 2]],
)
@wp.func
def _local_to_world(axis: int, vec: vec3i):
return vec3i(
vec[Grid3D.WORLD_TO_LOC[axis, 0]],
vec[Grid3D.WORLD_TO_LOC[axis, 1]],
vec[Grid3D.WORLD_TO_LOC[axis, 2]],
)
@wp.func
def _local_to_world(axis: int, vec: wp.vec3):
return wp.vec3(
vec[Grid3D.WORLD_TO_LOC[axis, 0]],
vec[Grid3D.WORLD_TO_LOC[axis, 1]],
vec[Grid3D.WORLD_TO_LOC[axis, 2]],
)
@wp.func
def side_index(arg: SideArg, side: Side):
alt_axis = Grid3D.LOC_TO_WORLD[side.axis, 0]
if side.origin[0] == arg.cell_arg.res[alt_axis]:
# Upper-boundary side
longitude = side.origin[1]
latitude = side.origin[2]
latitude_res = arg.cell_arg.res[Grid3D.LOC_TO_WORLD[side.axis, 2]]
lat_long = latitude_res * longitude + latitude
return 3 * arg.cell_count + arg.axis_offsets[side.axis] + lat_long
cell_index = Grid3D.cell_index(arg.cell_arg.res, Grid3D._local_to_world(side.axis, side.origin))
return side.axis * arg.cell_count + cell_index
@wp.func
def get_side(arg: SideArg, side_index: ElementIndex):
if side_index < 3 * arg.cell_count:
axis = side_index // arg.cell_count
cell_index = side_index - axis * arg.cell_count
origin = Grid3D._world_to_local(axis, Grid3D.get_cell(arg.cell_arg.res, cell_index))
return Grid3D.Side(axis, origin)
axis_side_index = side_index - 3 * arg.cell_count
if axis_side_index < arg.axis_offsets[1]:
axis = 0
elif axis_side_index < arg.axis_offsets[2]:
axis = 1
else:
axis = 2
altitude = arg.cell_arg.res[Grid3D.LOC_TO_WORLD[axis, 0]]
lat_long = axis_side_index - arg.axis_offsets[axis]
latitude_res = arg.cell_arg.res[Grid3D.LOC_TO_WORLD[axis, 2]]
longitude = lat_long // latitude_res
latitude = lat_long - longitude * latitude_res
origin_loc = vec3i(altitude, longitude, latitude)
return Grid3D.Side(axis, origin_loc)
# Geometry device interface
def cell_arg_value(self, device) -> CellArg:
args = self.CellArg()
args.res = self.res
args.cell_size = self.cell_size
args.origin = self.bounds_lo
return args
@wp.func
def cell_position(args: CellArg, s: Sample):
cell = Grid3D.get_cell(args.res, s.element_index)
return (
wp.vec3(
(float(cell[0]) + s.element_coords[0]) * args.cell_size[0],
(float(cell[1]) + s.element_coords[1]) * args.cell_size[1],
(float(cell[2]) + s.element_coords[2]) * args.cell_size[2],
)
+ args.origin
)
@wp.func
def cell_lookup(args: CellArg, pos: wp.vec3):
loc_pos = wp.cw_div(pos - args.origin, args.cell_size)
x = wp.clamp(loc_pos[0], 0.0, float(args.res[0]))
y = wp.clamp(loc_pos[1], 0.0, float(args.res[1]))
z = wp.clamp(loc_pos[2], 0.0, float(args.res[2]))
x_cell = wp.min(wp.floor(x), float(args.res[0]) - 1.0)
y_cell = wp.min(wp.floor(y), float(args.res[1]) - 1.0)
z_cell = wp.min(wp.floor(z), float(args.res[2]) - 1.0)
coords = Coords(x - x_cell, y - y_cell, z - z_cell)
cell_index = Grid3D.cell_index(args.res, Grid3D.Cell(int(x_cell), int(y_cell), int(z_cell)))
return Sample(cell_index, coords, NULL_QP_INDEX, 0.0, NULL_DOF_INDEX, NULL_DOF_INDEX)
@wp.func
def cell_lookup(args: CellArg, pos: wp.vec3, guess: Sample):
return Grid3D.cell_lookup(args, pos)
@wp.func
def cell_measure(args: CellArg, cell_index: ElementIndex, coords: Coords):
return args.cell_size[0] * args.cell_size[1] * args.cell_size[2]
@wp.func
def cell_measure(args: CellArg, s: Sample):
return Grid3D.cell_measure(args, s.element_index, s.element_coords)
@wp.func
def cell_measure_ratio(args: CellArg, s: Sample):
return 1.0
@wp.func
def cell_normal(args: CellArg, s: Sample):
return wp.vec3(0.0)
def side_arg_value(self, device) -> SideArg:
args = self.SideArg()
axis_dims = vec3i(
self.res[1] * self.res[2],
self.res[2] * self.res[0],
self.res[0] * self.res[1],
)
args.axis_offsets = vec3i(
0,
axis_dims[0],
axis_dims[0] + axis_dims[1],
)
args.cell_count = self.cell_count()
args.cell_arg = self.cell_arg_value(device)
return args
def side_index_arg_value(self, device) -> SideIndexArg:
return self.side_arg_value(device)
@wp.func
def boundary_side_index(args: SideArg, boundary_side_index: int):
"""Boundary side to side index"""
axis_side_index = boundary_side_index // 2
border = boundary_side_index - 2 * axis_side_index
if axis_side_index < args.axis_offsets[1]:
axis = 0
elif axis_side_index < args.axis_offsets[2]:
axis = 1
else:
axis = 2
lat_long = axis_side_index - args.axis_offsets[axis]
latitude_res = args.cell_arg.res[Grid3D.LOC_TO_WORLD[axis, 2]]
longitude = lat_long // latitude_res
latitude = lat_long - longitude * latitude_res
altitude = border * args.cell_arg.res[axis]
side = Grid3D.Side(axis, vec3i(altitude, longitude, latitude))
return Grid3D.side_index(args, side)
@wp.func
def side_position(args: SideArg, s: Sample):
side = Grid3D.get_side(args, s.element_index)
local_pos = wp.vec3(
float(side.origin[0]),
float(side.origin[1]) + s.element_coords[0],
float(side.origin[2]) + s.element_coords[1],
)
pos = args.cell_arg.origin + wp.cw_mul(Grid3D._local_to_world(side.axis, local_pos), args.cell_arg.cell_size)
return pos
@wp.func
def side_measure(args: SideArg, side_index: ElementIndex, coords: Coords):
side = Grid3D.get_side(args, side_index)
long_axis = Grid3D.LOC_TO_WORLD[side.axis, 1]
lat_axis = Grid3D.LOC_TO_WORLD[side.axis, 2]
return args.cell_arg.cell_size[long_axis] * args.cell_arg.cell_size[lat_axis]
@wp.func
def side_measure(args: SideArg, s: Sample):
return Grid3D.side_measure(args, s.element_index, s.element_coords)
@wp.func
def side_measure_ratio(args: SideArg, s: Sample):
side = Grid3D.get_side(args, s.element_index)
alt_axis = Grid3D.LOC_TO_WORLD[side.axis, 0]
return 1.0 / args.cell_arg.cell_size[alt_axis]
@wp.func
def side_normal(args: SideArg, s: Sample):
side = Grid3D.get_side(args, s.element_index)
if side.origin[0] == 0:
sign = -1.0
else:
sign = 1.0
local_n = wp.vec3(sign, 0.0, 0.0)
return Grid3D._local_to_world(side.axis, local_n)
@wp.func
def side_inner_cell_index(arg: SideArg, side_index: ElementIndex):
side = Grid3D.get_side(arg, side_index)
if side.origin[0] == 0:
inner_alt = 0
else:
inner_alt = side.origin[0] - 1
inner_origin = vec3i(inner_alt, side.origin[1], side.origin[2])
cell = Grid3D._local_to_world(side.axis, inner_origin)
return Grid3D.cell_index(arg.cell_arg.res, cell)
@wp.func
def side_outer_cell_index(arg: SideArg, side_index: ElementIndex):
side = Grid3D.get_side(arg, side_index)
alt_axis = Grid3D.LOC_TO_WORLD[side.axis, 0]
if side.origin[0] == arg.cell_arg.res[alt_axis]:
outer_alt = arg.cell_arg.res[alt_axis] - 1
else:
outer_alt = side.origin[0]
outer_origin = vec3i(outer_alt, side.origin[1], side.origin[2])
cell = Grid3D._local_to_world(side.axis, outer_origin)
return Grid3D.cell_index(arg.cell_arg.res, cell)
| warp-main | warp/fem/geometry/grid_3d.py |
from typing import Tuple, List
from warp.fem.types import Coords
from warp.fem.polynomial import Polynomial, quadrature_1d
class Element:
@staticmethod
def instantiate_quadrature(order: int, family: Polynomial) -> Tuple[List[Coords], List[float]]:
"""Returns a quadrature of a given order for a prototypical element"""
raise NotImplementedError
def _point_count_from_order(order: int, family: Polynomial):
if family == Polynomial.GAUSS_LEGENDRE:
point_count = max(1, order // 2 + 1)
elif family == Polynomial.LOBATTO_GAUSS_LEGENDRE:
point_count = max(2, order // 2 + 2)
elif family == Polynomial.EQUISPACED_CLOSED:
point_count = max(2, 2 * (order // 2) + 1)
elif family == Polynomial.EQUISPACED_OPEN:
point_count = max(1, 2 * (order // 2) + 1)
return point_count
class Cube(Element):
@staticmethod
def instantiate_quadrature(order: int, family: Polynomial):
if family is None:
family = Polynomial.GAUSS_LEGENDRE
point_count = _point_count_from_order(order=order, family=family)
gauss_1d, weights_1d = quadrature_1d(point_count=point_count, family=family)
coords = [Coords(x, y, z) for x in gauss_1d for y in gauss_1d for z in gauss_1d]
weights = [wx * wy * wz for wx in weights_1d for wy in weights_1d for wz in weights_1d]
return coords, weights
class Square(Element):
@staticmethod
def instantiate_quadrature(order: int, family: Polynomial):
if family is None:
family = Polynomial.GAUSS_LEGENDRE
point_count = _point_count_from_order(order=order, family=family)
gauss_1d, weights_1d = quadrature_1d(point_count=point_count, family=family)
coords = [Coords(x, y, 0.0) for x in gauss_1d for y in gauss_1d]
weights = [wx * wy for wx in weights_1d for wy in weights_1d]
return coords, weights
class LinearEdge(Element):
@staticmethod
def instantiate_quadrature(order: int, family: Polynomial):
if family is None:
family = Polynomial.GAUSS_LEGENDRE
point_count = _point_count_from_order(order=order, family=family)
gauss_1d, weights_1d = quadrature_1d(point_count=point_count, family=family)
coords = [Coords(x, 0.0, 0.0) for x in gauss_1d]
return coords, weights_1d
class Triangle(Element):
@staticmethod
def instantiate_quadrature(order: int, family: Polynomial):
if family is not None:
# Duffy transformation from square to triangle
point_count = _point_count_from_order(order=order + 1, family=family)
gauss_1d, weights_1d = quadrature_1d(point_count=point_count, family=family)
coords = [Coords(1.0 - x - y + x * y, x, y * (1.0 - x)) for x in gauss_1d for y in gauss_1d]
# Scale weight by 2.0 so that they sum up to 1
weights = [2.0 * wx * (1.0 - x) * wy for x, wx in zip(gauss_1d, weights_1d) for wy in weights_1d]
return coords, weights
if order <= 1:
weights = [1.0]
coords = [Coords(1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0)]
elif order <= 2:
weights = [1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0]
coords = [
Coords(2.0 / 3.0, 1.0 / 6.0, 1.0 / 6.0),
Coords(1.0 / 6.0, 2.0 / 3.0, 1.0 / 6.0),
Coords(1.0 / 6.0, 1.0 / 6.0, 2.0 / 3.0),
]
elif order <= 3:
# Hillion 1977,
# "Numerical Integration on a Triangle"
weights = [
3.18041381743977225049491153185954e-01,
3.18041381743977225049491153185954e-01,
1.81958618256022719439357615556219e-01,
1.81958618256022719439357615556219e-01,
]
coords = [
Coords(
6.66390246014701426169324349757517e-01,
1.78558728263616461884311092944699e-01,
1.55051025721682111946364557297784e-01,
),
Coords(
1.78558728263616461884311092944699e-01,
6.66390246014701426169324349757517e-01,
1.55051025721682056435213326039957e-01,
),
Coords(
2.80019915499074012465996474929852e-01,
7.50311102226081383381739442484104e-02,
6.44948974278317876951405196450651e-01,
),
Coords(
7.50311102226081383381739442484104e-02,
2.80019915499074012465996474929852e-01,
6.44948974278317876951405196450651e-01,
),
]
elif order <= 4:
# Witherden and Vincent 2015,
# "On the identification of symmetric quadrature rules for finite element methods"
# https://doi.org/10.1016/j.camwa.2015.03.017
weights = [
2.23381589678011471811203136894619e-01,
2.23381589678011471811203136894619e-01,
2.23381589678011471811203136894619e-01,
1.09951743655321870773988734981685e-01,
1.09951743655321870773988734981685e-01,
1.09951743655321870773988734981685e-01,
]
coords = [
Coords(
4.45948490915964890213274429697776e-01,
4.45948490915964890213274429697776e-01,
1.08103018168070219573451140604448e-01,
),
Coords(
4.45948490915964890213274429697776e-01,
1.08103018168070219573451140604448e-01,
4.45948490915964890213274429697776e-01,
),
Coords(
1.08103018168070219573451140604448e-01,
4.45948490915964890213274429697776e-01,
4.45948490915964890213274429697776e-01,
),
Coords(
9.15762135097707430375635340169538e-02,
9.15762135097707430375635340169538e-02,
8.16847572980458513924872931966092e-01,
),
Coords(
9.15762135097707430375635340169538e-02,
8.16847572980458513924872931966092e-01,
9.15762135097707430375635340169538e-02,
),
Coords(
8.16847572980458513924872931966092e-01,
9.15762135097707430375635340169538e-02,
9.15762135097707430375635340169538e-02,
),
]
elif order <= 5:
weights = [
2.25000000000000005551115123125783e-01,
1.25939180544827139529573400977824e-01,
1.25939180544827139529573400977824e-01,
1.25939180544827139529573400977824e-01,
1.32394152788506191953388224646915e-01,
1.32394152788506191953388224646915e-01,
1.32394152788506191953388224646915e-01,
]
coords = [
Coords(
3.33333333333333314829616256247391e-01,
3.33333333333333314829616256247391e-01,
3.33333333333333314829616256247391e-01,
),
Coords(
1.01286507323456342888334802410100e-01,
1.01286507323456342888334802410100e-01,
7.97426985353087314223330395179801e-01,
),
Coords(
1.01286507323456342888334802410100e-01,
7.97426985353087314223330395179801e-01,
1.01286507323456342888334802410100e-01,
),
Coords(
7.97426985353087314223330395179801e-01,
1.01286507323456342888334802410100e-01,
1.01286507323456342888334802410100e-01,
),
Coords(
4.70142064105115109473587153843255e-01,
4.70142064105115109473587153843255e-01,
5.97158717897697810528256923134904e-02,
),
Coords(
4.70142064105115109473587153843255e-01,
5.97158717897697810528256923134904e-02,
4.70142064105115109473587153843255e-01,
),
Coords(
5.97158717897697810528256923134904e-02,
4.70142064105115109473587153843255e-01,
4.70142064105115109473587153843255e-01,
),
]
elif order <= 6:
weights = [
5.08449063702068326797700592578622e-02,
5.08449063702068326797700592578622e-02,
5.08449063702068326797700592578622e-02,
1.16786275726379396022736045779311e-01,
1.16786275726379396022736045779311e-01,
1.16786275726379396022736045779311e-01,
8.28510756183735846969184990484791e-02,
8.28510756183735846969184990484791e-02,
8.28510756183735846969184990484791e-02,
8.28510756183735846969184990484791e-02,
8.28510756183735846969184990484791e-02,
8.28510756183735846969184990484791e-02,
]
coords = [
Coords(
6.30890144915022266225435032538371e-02,
6.30890144915022266225435032538371e-02,
8.73821971016995546754912993492326e-01,
),
Coords(
6.30890144915022266225435032538371e-02,
8.73821971016995546754912993492326e-01,
6.30890144915022266225435032538371e-02,
),
Coords(
8.73821971016995546754912993492326e-01,
6.30890144915022266225435032538371e-02,
6.30890144915022266225435032538371e-02,
),
Coords(
2.49286745170910428726074314909056e-01,
2.49286745170910428726074314909056e-01,
5.01426509658179142547851370181888e-01,
),
Coords(
2.49286745170910428726074314909056e-01,
5.01426509658179142547851370181888e-01,
2.49286745170910428726074314909056e-01,
),
Coords(
5.01426509658179142547851370181888e-01,
2.49286745170910428726074314909056e-01,
2.49286745170910428726074314909056e-01,
),
Coords(
5.31450498448169383891581674106419e-02,
3.10352451033784393352732422499685e-01,
6.36502499121398668258109410089673e-01,
),
Coords(
5.31450498448169383891581674106419e-02,
6.36502499121398668258109410089673e-01,
3.10352451033784393352732422499685e-01,
),
Coords(
3.10352451033784393352732422499685e-01,
5.31450498448169383891581674106419e-02,
6.36502499121398668258109410089673e-01,
),
Coords(
3.10352451033784393352732422499685e-01,
6.36502499121398668258109410089673e-01,
5.31450498448169383891581674106419e-02,
),
Coords(
6.36502499121398668258109410089673e-01,
5.31450498448169383891581674106419e-02,
3.10352451033784393352732422499685e-01,
),
Coords(
6.36502499121398668258109410089673e-01,
3.10352451033784393352732422499685e-01,
5.31450498448169383891581674106419e-02,
),
]
else:
# Order 8
weights = [
1.44315607677787172136163462710101e-01,
9.50916342672846193195823616406415e-02,
9.50916342672846193195823616406415e-02,
9.50916342672846193195823616406415e-02,
1.03217370534718244634575512463925e-01,
1.03217370534718244634575512463925e-01,
1.03217370534718244634575512463925e-01,
3.24584976231980792960030157701112e-02,
3.24584976231980792960030157701112e-02,
3.24584976231980792960030157701112e-02,
2.72303141744349927466650740370824e-02,
2.72303141744349927466650740370824e-02,
2.72303141744349927466650740370824e-02,
2.72303141744349927466650740370824e-02,
2.72303141744349927466650740370824e-02,
2.72303141744349927466650740370824e-02,
]
coords = [
Coords(
3.33333333333333314829616256247391e-01,
3.33333333333333314829616256247391e-01,
3.33333333333333314829616256247391e-01,
),
Coords(
4.59292588292723125142913431773195e-01,
4.59292588292723125142913431773195e-01,
8.14148234145537497141731364536099e-02,
),
Coords(
4.59292588292723125142913431773195e-01,
8.14148234145537497141731364536099e-02,
4.59292588292723125142913431773195e-01,
),
Coords(
8.14148234145537497141731364536099e-02,
4.59292588292723125142913431773195e-01,
4.59292588292723125142913431773195e-01,
),
Coords(
1.70569307751760212976677166807349e-01,
1.70569307751760212976677166807349e-01,
6.58861384496479574046645666385302e-01,
),
Coords(
1.70569307751760212976677166807349e-01,
6.58861384496479574046645666385302e-01,
1.70569307751760212976677166807349e-01,
),
Coords(
6.58861384496479574046645666385302e-01,
1.70569307751760212976677166807349e-01,
1.70569307751760212976677166807349e-01,
),
Coords(
5.05472283170309566457945038564503e-02,
5.05472283170309566457945038564503e-02,
8.98905543365938086708410992287099e-01,
),
Coords(
5.05472283170309566457945038564503e-02,
8.98905543365938086708410992287099e-01,
5.05472283170309566457945038564503e-02,
),
Coords(
8.98905543365938086708410992287099e-01,
5.05472283170309566457945038564503e-02,
5.05472283170309566457945038564503e-02,
),
Coords(
8.39477740995758781039626228448469e-03,
2.63112829634638112352718053443823e-01,
7.28492392955404355348036915529519e-01,
),
Coords(
8.39477740995758781039626228448469e-03,
7.28492392955404355348036915529519e-01,
2.63112829634638112352718053443823e-01,
),
Coords(
2.63112829634638112352718053443823e-01,
8.39477740995758781039626228448469e-03,
7.28492392955404355348036915529519e-01,
),
Coords(
2.63112829634638112352718053443823e-01,
7.28492392955404355348036915529519e-01,
8.39477740995758781039626228448469e-03,
),
Coords(
7.28492392955404355348036915529519e-01,
8.39477740995758781039626228448469e-03,
2.63112829634638112352718053443823e-01,
),
Coords(
7.28492392955404355348036915529519e-01,
2.63112829634638112352718053443823e-01,
8.39477740995758781039626228448469e-03,
),
]
return coords, weights
class Tetrahedron(Element):
@staticmethod
def instantiate_quadrature(order: int, family: Polynomial):
if family is not None:
# Duffy transformation from square to triangle
point_count = _point_count_from_order(order=order + 1, family=family)
gauss_1d, weights_1d = quadrature_1d(point_count=point_count, family=family)
coords = [
Coords(x, y * (1.0 - x), z * (1.0 - x) * (1.0 - y))
for x in gauss_1d
for y in gauss_1d
for z in gauss_1d
]
# Scale weight by 6.0 so that they sum up to 1
weights = [
6.0 * wx * wy * wz * (1.0 - x) * (1.0 - x) * (1.0 - y)
for x, wx in zip(gauss_1d, weights_1d)
for y, wy in zip(gauss_1d, weights_1d)
for wz in weights_1d
]
return coords, weights
# Shunn and Ham 2012
# "Symmetric quadrature rules for tetrahedra based on a cubic close-packed lattice arrangement"
# https://doi.org/10.1016/j.cam.2012.03.032
# TODO: add Witherden and Vincent 2015,
if order <= 1:
weights = [1.0]
coords = [Coords(1.0 / 4.0, 1.0 / 4.0, 1.0 / 4.0)]
elif order <= 2:
weights = [1.0 / 4.0, 1.0 / 4.0, 1.0 / 4.0, 1.0 / 4.0]
coords = [
Coords(0.1381966011250110, 0.1381966011250110, 0.1381966011250110),
Coords(0.5854101966249680, 0.1381966011250110, 0.1381966011250110),
Coords(0.1381966011250110, 0.5854101966249680, 0.1381966011250110),
Coords(0.1381966011250110, 0.1381966011250110, 0.5854101966249680),
]
elif order <= 3:
weights = [
0.0476331348432089,
0.0476331348432089,
0.0476331348432089,
0.0476331348432089,
0.1349112434378610,
0.1349112434378610,
0.1349112434378610,
0.1349112434378610,
0.1349112434378610,
0.1349112434378610,
]
coords = [
Coords(0.0738349017262234, 0.0738349017262234, 0.0738349017262234),
Coords(0.7784952948213300, 0.0738349017262234, 0.0738349017262234),
Coords(0.0738349017262234, 0.7784952948213300, 0.0738349017262234),
Coords(0.0738349017262234, 0.0738349017262234, 0.7784952948213300),
Coords(0.4062443438840510, 0.0937556561159491, 0.0937556561159491),
Coords(0.0937556561159491, 0.4062443438840510, 0.0937556561159491),
Coords(0.0937556561159491, 0.0937556561159491, 0.4062443438840510),
Coords(0.4062443438840510, 0.4062443438840510, 0.0937556561159491),
Coords(0.4062443438840510, 0.0937556561159491, 0.4062443438840510),
Coords(0.0937556561159491, 0.4062443438840510, 0.4062443438840510),
]
elif order <= 4:
weights = [
0.0070670747944695,
0.0070670747944695,
0.0070670747944695,
0.0070670747944695,
0.0469986689718877,
0.0469986689718877,
0.0469986689718877,
0.0469986689718877,
0.0469986689718877,
0.0469986689718877,
0.0469986689718877,
0.0469986689718877,
0.0469986689718877,
0.0469986689718877,
0.0469986689718877,
0.0469986689718877,
0.1019369182898680,
0.1019369182898680,
0.1019369182898680,
0.1019369182898680,
]
coords = [
Coords(0.0323525947272439, 0.0323525947272439, 0.0323525947272439),
Coords(0.9029422158182680, 0.0323525947272439, 0.0323525947272439),
Coords(0.0323525947272439, 0.9029422158182680, 0.0323525947272439),
Coords(0.0323525947272439, 0.0323525947272439, 0.9029422158182680),
Coords(0.6165965330619370, 0.0603604415251421, 0.0603604415251421),
Coords(0.2626825838877790, 0.0603604415251421, 0.0603604415251421),
Coords(0.0603604415251421, 0.6165965330619370, 0.0603604415251421),
Coords(0.0603604415251421, 0.2626825838877790, 0.0603604415251421),
Coords(0.0603604415251421, 0.0603604415251421, 0.6165965330619370),
Coords(0.0603604415251421, 0.0603604415251421, 0.2626825838877790),
Coords(0.2626825838877790, 0.6165965330619370, 0.0603604415251421),
Coords(0.6165965330619370, 0.2626825838877790, 0.0603604415251421),
Coords(0.2626825838877790, 0.0603604415251421, 0.6165965330619370),
Coords(0.6165965330619370, 0.0603604415251421, 0.2626825838877790),
Coords(0.0603604415251421, 0.2626825838877790, 0.6165965330619370),
Coords(0.0603604415251421, 0.6165965330619370, 0.2626825838877790),
Coords(0.3097693042728620, 0.3097693042728620, 0.0706920871814129),
Coords(0.3097693042728620, 0.0706920871814129, 0.3097693042728620),
Coords(0.0706920871814129, 0.3097693042728620, 0.3097693042728620),
Coords(0.3097693042728620, 0.3097693042728620, 0.3097693042728620),
]
elif order <= 5:
weights = [
0.0021900463965388,
0.0021900463965388,
0.0021900463965388,
0.0021900463965388,
0.0143395670177665,
0.0143395670177665,
0.0143395670177665,
0.0143395670177665,
0.0143395670177665,
0.0143395670177665,
0.0143395670177665,
0.0143395670177665,
0.0143395670177665,
0.0143395670177665,
0.0143395670177665,
0.0143395670177665,
0.0250305395686746,
0.0250305395686746,
0.0250305395686746,
0.0250305395686746,
0.0250305395686746,
0.0250305395686746,
0.0479839333057554,
0.0479839333057554,
0.0479839333057554,
0.0479839333057554,
0.0479839333057554,
0.0479839333057554,
0.0479839333057554,
0.0479839333057554,
0.0479839333057554,
0.0479839333057554,
0.0479839333057554,
0.0479839333057554,
0.0931745731195340,
]
coords = [
Coords(0.0267367755543735, 0.0267367755543735, 0.0267367755543735),
Coords(0.9197896733368800, 0.0267367755543735, 0.0267367755543735),
Coords(0.0267367755543735, 0.9197896733368800, 0.0267367755543735),
Coords(0.0267367755543735, 0.0267367755543735, 0.9197896733368800),
Coords(0.7477598884818090, 0.0391022406356488, 0.0391022406356488),
Coords(0.1740356302468940, 0.0391022406356488, 0.0391022406356488),
Coords(0.0391022406356488, 0.7477598884818090, 0.0391022406356488),
Coords(0.0391022406356488, 0.1740356302468940, 0.0391022406356488),
Coords(0.0391022406356488, 0.0391022406356488, 0.7477598884818090),
Coords(0.0391022406356488, 0.0391022406356488, 0.1740356302468940),
Coords(0.1740356302468940, 0.7477598884818090, 0.0391022406356488),
Coords(0.7477598884818090, 0.1740356302468940, 0.0391022406356488),
Coords(0.1740356302468940, 0.0391022406356488, 0.7477598884818090),
Coords(0.7477598884818090, 0.0391022406356488, 0.1740356302468940),
Coords(0.0391022406356488, 0.1740356302468940, 0.7477598884818090),
Coords(0.0391022406356488, 0.7477598884818090, 0.1740356302468940),
Coords(0.4547545999844830, 0.0452454000155172, 0.0452454000155172),
Coords(0.0452454000155172, 0.4547545999844830, 0.0452454000155172),
Coords(0.0452454000155172, 0.0452454000155172, 0.4547545999844830),
Coords(0.4547545999844830, 0.4547545999844830, 0.0452454000155172),
Coords(0.4547545999844830, 0.0452454000155172, 0.4547545999844830),
Coords(0.0452454000155172, 0.4547545999844830, 0.4547545999844830),
Coords(0.2232010379623150, 0.2232010379623150, 0.0504792790607720),
Coords(0.5031186450145980, 0.2232010379623150, 0.0504792790607720),
Coords(0.2232010379623150, 0.5031186450145980, 0.0504792790607720),
Coords(0.2232010379623150, 0.0504792790607720, 0.2232010379623150),
Coords(0.5031186450145980, 0.0504792790607720, 0.2232010379623150),
Coords(0.2232010379623150, 0.0504792790607720, 0.5031186450145980),
Coords(0.0504792790607720, 0.2232010379623150, 0.2232010379623150),
Coords(0.0504792790607720, 0.5031186450145980, 0.2232010379623150),
Coords(0.0504792790607720, 0.2232010379623150, 0.5031186450145980),
Coords(0.5031186450145980, 0.2232010379623150, 0.2232010379623150),
Coords(0.2232010379623150, 0.5031186450145980, 0.2232010379623150),
Coords(0.2232010379623150, 0.2232010379623150, 0.5031186450145980),
Coords(0.2500000000000000, 0.2500000000000000, 0.2500000000000000),
]
elif order <= 6:
weights = [
0.0010373112336140,
0.0010373112336140,
0.0010373112336140,
0.0010373112336140,
0.0096016645399480,
0.0096016645399480,
0.0096016645399480,
0.0096016645399480,
0.0096016645399480,
0.0096016645399480,
0.0096016645399480,
0.0096016645399480,
0.0096016645399480,
0.0096016645399480,
0.0096016645399480,
0.0096016645399480,
0.0164493976798232,
0.0164493976798232,
0.0164493976798232,
0.0164493976798232,
0.0164493976798232,
0.0164493976798232,
0.0164493976798232,
0.0164493976798232,
0.0164493976798232,
0.0164493976798232,
0.0164493976798232,
0.0164493976798232,
0.0153747766513310,
0.0153747766513310,
0.0153747766513310,
0.0153747766513310,
0.0153747766513310,
0.0153747766513310,
0.0153747766513310,
0.0153747766513310,
0.0153747766513310,
0.0153747766513310,
0.0153747766513310,
0.0153747766513310,
0.0293520118375230,
0.0293520118375230,
0.0293520118375230,
0.0293520118375230,
0.0293520118375230,
0.0293520118375230,
0.0293520118375230,
0.0293520118375230,
0.0293520118375230,
0.0293520118375230,
0.0293520118375230,
0.0293520118375230,
0.0366291366405108,
0.0366291366405108,
0.0366291366405108,
0.0366291366405108,
]
coords = [
Coords(0.0149520651530592, 0.0149520651530592, 0.0149520651530592),
Coords(0.9551438045408220, 0.0149520651530592, 0.0149520651530592),
Coords(0.0149520651530592, 0.9551438045408220, 0.0149520651530592),
Coords(0.0149520651530592, 0.0149520651530592, 0.9551438045408220),
Coords(0.1518319491659370, 0.0340960211962615, 0.0340960211962615),
Coords(0.7799760084415400, 0.0340960211962615, 0.0340960211962615),
Coords(0.0340960211962615, 0.1518319491659370, 0.0340960211962615),
Coords(0.0340960211962615, 0.7799760084415400, 0.0340960211962615),
Coords(0.0340960211962615, 0.0340960211962615, 0.1518319491659370),
Coords(0.0340960211962615, 0.0340960211962615, 0.7799760084415400),
Coords(0.7799760084415400, 0.1518319491659370, 0.0340960211962615),
Coords(0.1518319491659370, 0.7799760084415400, 0.0340960211962615),
Coords(0.7799760084415400, 0.0340960211962615, 0.1518319491659370),
Coords(0.1518319491659370, 0.0340960211962615, 0.7799760084415400),
Coords(0.0340960211962615, 0.7799760084415400, 0.1518319491659370),
Coords(0.0340960211962615, 0.1518319491659370, 0.7799760084415400),
Coords(0.5526556431060170, 0.0462051504150017, 0.0462051504150017),
Coords(0.3549340560639790, 0.0462051504150017, 0.0462051504150017),
Coords(0.0462051504150017, 0.5526556431060170, 0.0462051504150017),
Coords(0.0462051504150017, 0.3549340560639790, 0.0462051504150017),
Coords(0.0462051504150017, 0.0462051504150017, 0.5526556431060170),
Coords(0.0462051504150017, 0.0462051504150017, 0.3549340560639790),
Coords(0.3549340560639790, 0.5526556431060170, 0.0462051504150017),
Coords(0.5526556431060170, 0.3549340560639790, 0.0462051504150017),
Coords(0.3549340560639790, 0.0462051504150017, 0.5526556431060170),
Coords(0.5526556431060170, 0.0462051504150017, 0.3549340560639790),
Coords(0.0462051504150017, 0.3549340560639790, 0.5526556431060170),
Coords(0.0462051504150017, 0.5526556431060170, 0.3549340560639790),
Coords(0.2281904610687610, 0.2281904610687610, 0.0055147549744775),
Coords(0.5381043228880020, 0.2281904610687610, 0.0055147549744775),
Coords(0.2281904610687610, 0.5381043228880020, 0.0055147549744775),
Coords(0.2281904610687610, 0.0055147549744775, 0.2281904610687610),
Coords(0.5381043228880020, 0.0055147549744775, 0.2281904610687610),
Coords(0.2281904610687610, 0.0055147549744775, 0.5381043228880020),
Coords(0.0055147549744775, 0.2281904610687610, 0.2281904610687610),
Coords(0.0055147549744775, 0.5381043228880020, 0.2281904610687610),
Coords(0.0055147549744775, 0.2281904610687610, 0.5381043228880020),
Coords(0.5381043228880020, 0.2281904610687610, 0.2281904610687610),
Coords(0.2281904610687610, 0.5381043228880020, 0.2281904610687610),
Coords(0.2281904610687610, 0.2281904610687610, 0.5381043228880020),
Coords(0.3523052600879940, 0.3523052600879940, 0.0992057202494530),
Coords(0.1961837595745600, 0.3523052600879940, 0.0992057202494530),
Coords(0.3523052600879940, 0.1961837595745600, 0.0992057202494530),
Coords(0.3523052600879940, 0.0992057202494530, 0.3523052600879940),
Coords(0.1961837595745600, 0.0992057202494530, 0.3523052600879940),
Coords(0.3523052600879940, 0.0992057202494530, 0.1961837595745600),
Coords(0.0992057202494530, 0.3523052600879940, 0.3523052600879940),
Coords(0.0992057202494530, 0.1961837595745600, 0.3523052600879940),
Coords(0.0992057202494530, 0.3523052600879940, 0.1961837595745600),
Coords(0.1961837595745600, 0.3523052600879940, 0.3523052600879940),
Coords(0.3523052600879940, 0.1961837595745600, 0.3523052600879940),
Coords(0.3523052600879940, 0.3523052600879940, 0.1961837595745600),
Coords(0.1344783347929940, 0.1344783347929940, 0.1344783347929940),
Coords(0.5965649956210170, 0.1344783347929940, 0.1344783347929940),
Coords(0.1344783347929940, 0.5965649956210170, 0.1344783347929940),
Coords(0.1344783347929940, 0.1344783347929940, 0.5965649956210170),
]
else:
raise NotImplementedError
return coords, weights
| warp-main | warp/fem/geometry/element.py |
from typing import Any
import warp as wp
from warp.fem.types import Coords
@wp.func
def project_on_seg_at_origin(q: Any, seg: Any, len_sq: float):
s = wp.clamp(wp.dot(q, seg) / len_sq, 0.0, 1.0)
return wp.length_sq(q - s * seg), s
@wp.func
def project_on_tri_at_origin(q: Any, e1: Any, e2: Any):
e1e1 = wp.dot(e1, e1)
e1e2 = wp.dot(e1, e2)
e2e2 = wp.dot(e2, e2)
det = e1e1 * e2e2 - e1e2 * e1e2
if det > e1e1 * e2e2 * 1.0e-6:
e1p = wp.dot(e1, q)
e2p = wp.dot(e2, q)
s = (e2e2 * e1p - e1e2 * e2p) / det
t = (e1e1 * e2p - e1e2 * e1p) / det
if s >= 0.0 and t >= 0.0 and s + t <= 1.0:
# point inside triangle (distance can be non-zero in 3D case)
return wp.length_sq(q - s * e1 - t * e2), Coords(1.0 - s - t, s, t)
d1, s1 = project_on_seg_at_origin(q, e1, e1e1)
d2, s2 = project_on_seg_at_origin(q, e2, e2e2)
d12, s12 = project_on_seg_at_origin(q - e1, e2 - e1, wp.length_sq(e2 - e1))
if d1 <= d2:
if d1 <= d12:
return d1, Coords(1.0 - s1, s1, 0.0)
elif d2 <= d12:
return d2, Coords(1.0 - s2, 0.0, s2)
return d12, Coords(0.0, 1.0 - s12, s12)
@wp.func
def project_on_tet_at_origin(q: wp.vec3, e1: wp.vec3, e2: wp.vec3, e3: wp.vec3):
mat = wp.inverse(wp.mat33(e1, e2, e3))
coords = mat * q
if wp.min(coords) >= 0.0 and coords[0] + coords[1] + coords[2] <= 1.0:
return 0.0, coords
# Not inside tet, compare closest point on each tri
d12, s12 = project_on_tri_at_origin(q, e1, e2)
d23, s23 = project_on_tri_at_origin(q, e2, e3)
d31, s31 = project_on_tri_at_origin(q, e3, e1)
d123, s123 = project_on_tri_at_origin(q - e1, e2 - e1, e3 - e1)
dmin = wp.min(wp.vec4(d12, d23, d31, d123))
if dmin == d12:
return dmin, Coords(s12[1], s12[2], 0.0)
elif dmin == d23:
return dmin, Coords(0.0, s23[1], s23[2])
elif dmin == d31:
return dmin, Coords(s31[2], 0.0, s31[1])
else:
return dmin, s123
| warp-main | warp/fem/geometry/closest_point.py |
import warp as wp
from warp.fem.types import ElementIndex, Coords, vec2i, Sample
from warp.fem.types import NULL_ELEMENT_INDEX, OUTSIDE, NULL_DOF_INDEX, NULL_QP_INDEX
from .geometry import Geometry
from .element import Triangle, LinearEdge
from .closest_point import project_on_tri_at_origin
@wp.struct
class Trimesh2DArg:
tri_vertex_indices: wp.array2d(dtype=int)
positions: wp.array(dtype=wp.vec2)
vertex_tri_offsets: wp.array(dtype=int)
vertex_tri_indices: wp.array(dtype=int)
edge_vertex_indices: wp.array(dtype=vec2i)
edge_tri_indices: wp.array(dtype=vec2i)
class Trimesh2D(Geometry):
"""Two-dimensional triangular mesh geometry"""
def __init__(self, tri_vertex_indices: wp.array, positions: wp.array):
"""
Constructs a two-dimensional triangular mesh.
Args:
tri_vertex_indices: warp array of shape (num_tris, 3) containing vertex indices for each tri
positions: warp array of shape (num_vertices, 2) containing 2d position for each vertex
"""
self.dimension = 2
self.tri_vertex_indices = tri_vertex_indices
self.positions = positions
self._edge_vertex_indices: wp.array = None
self._edge_tri_indices: wp.array = None
self._vertex_tri_offsets: wp.array = None
self._vertex_tri_indices: wp.array = None
self._build_topology()
def cell_count(self):
return self.tri_vertex_indices.shape[0]
def vertex_count(self):
return self.positions.shape[0]
def side_count(self):
return self._edge_vertex_indices.shape[0]
def boundary_side_count(self):
return self._boundary_edge_indices.shape[0]
def reference_cell(self) -> Triangle:
return Triangle()
def reference_side(self) -> LinearEdge:
return LinearEdge()
CellArg = Trimesh2DArg
SideArg = Trimesh2DArg
@wp.struct
class SideIndexArg:
boundary_edge_indices: wp.array(dtype=int)
# Geometry device interface
def cell_arg_value(self, device) -> CellArg:
args = self.CellArg()
args.tri_vertex_indices = self.tri_vertex_indices.to(device)
args.positions = self.positions.to(device)
args.edge_vertex_indices = self._edge_vertex_indices.to(device)
args.edge_tri_indices = self._edge_tri_indices.to(device)
args.vertex_tri_offsets = self._vertex_tri_offsets.to(device)
args.vertex_tri_indices = self._vertex_tri_indices.to(device)
return args
@wp.func
def cell_position(args: CellArg, s: Sample):
tri_idx = args.tri_vertex_indices[s.element_index]
return (
s.element_coords[0] * args.positions[tri_idx[0]]
+ s.element_coords[1] * args.positions[tri_idx[1]]
+ s.element_coords[2] * args.positions[tri_idx[2]]
)
@wp.func
def _project_on_tri(args: CellArg, pos: wp.vec2, tri_index: int):
p0 = args.positions[args.tri_vertex_indices[tri_index, 0]]
q = pos - p0
e1 = args.positions[args.tri_vertex_indices[tri_index, 1]] - p0
e2 = args.positions[args.tri_vertex_indices[tri_index, 2]] - p0
dist, coords = project_on_tri_at_origin(q, e1, e2)
return dist, coords
@wp.func
def cell_lookup(args: CellArg, pos: wp.vec2, guess: Sample):
closest_tri = int(NULL_ELEMENT_INDEX)
closest_coords = Coords(OUTSIDE)
closest_dist = float(1.0e8)
for v in range(3):
vtx = args.tri_vertex_indices[guess.element_index, v]
tri_beg = args.vertex_tri_offsets[vtx]
tri_end = args.vertex_tri_offsets[vtx + 1]
for t in range(tri_beg, tri_end):
tri = args.vertex_tri_indices[t]
dist, coords = Trimesh2D._project_on_tri(args, pos, tri)
if dist <= closest_dist:
closest_dist = dist
closest_tri = tri
closest_coords = coords
return Sample(closest_tri, closest_coords, NULL_QP_INDEX, 0.0, NULL_DOF_INDEX, NULL_DOF_INDEX)
@wp.func
def cell_measure(args: CellArg, cell_index: ElementIndex, coords: Coords):
tri_idx = args.tri_vertex_indices[cell_index]
v0 = args.positions[tri_idx[0]]
v1 = args.positions[tri_idx[1]]
v2 = args.positions[tri_idx[2]]
e1 = v1 - v0
e2 = v2 - v0
return 0.5 * wp.abs(e1[0] * e2[1] - e1[1] * e2[0])
@wp.func
def cell_measure(args: CellArg, s: Sample):
return Trimesh2D.cell_measure(args, s.element_index, s.element_coords)
@wp.func
def cell_measure_ratio(args: CellArg, s: Sample):
return 1.0
@wp.func
def cell_normal(args: CellArg, s: Sample):
return wp.vec2(0.0)
def side_arg_value(self, device) -> SideArg:
return self.cell_arg_value(device)
def side_index_arg_value(self, device) -> SideIndexArg:
args = self.SideIndexArg()
args.boundary_edge_indices = self._boundary_edge_indices.to(device)
return args
@wp.func
def boundary_side_index(args: SideIndexArg, boundary_side_index: int):
"""Boundary side to side index"""
return args.boundary_edge_indices[boundary_side_index]
@wp.func
def side_position(args: SideArg, s: Sample):
edge_idx = args.edge_vertex_indices[s.element_index]
return (1.0 - s.element_coords[0]) * args.positions[edge_idx[0]] + s.element_coords[0] * args.positions[
edge_idx[1]
]
@wp.func
def side_measure(args: SideArg, side_index: ElementIndex, coords: Coords):
edge_idx = args.edge_vertex_indices[side_index]
v0 = args.positions[edge_idx[0]]
v1 = args.positions[edge_idx[1]]
return wp.length(v1 - v0)
@wp.func
def side_measure(args: SideArg, s: Sample):
return Trimesh2D.side_measure(args, s.element_index, s.element_coords)
@wp.func
def side_measure_ratio(args: SideArg, s: Sample):
inner = Trimesh2D.side_inner_cell_index(args, s.element_index)
outer = Trimesh2D.side_outer_cell_index(args, s.element_index)
return Trimesh2D.side_measure(args, s) / wp.min(
Trimesh2D.cell_measure(args, inner, Coords()),
Trimesh2D.cell_measure(args, outer, Coords()),
)
@wp.func
def side_normal(args: SideArg, s: Sample):
edge_idx = args.edge_vertex_indices[s.element_index]
v0 = args.positions[edge_idx[0]]
v1 = args.positions[edge_idx[1]]
e = v1 - v0
return wp.normalize(wp.vec2(-e[1], e[0]))
@wp.func
def side_inner_cell_index(arg: SideArg, side_index: ElementIndex):
return arg.edge_tri_indices[side_index][0]
@wp.func
def side_outer_cell_index(arg: SideArg, side_index: ElementIndex):
return arg.edge_tri_indices[side_index][1]
@wp.func
def edge_to_tri_coords(args: SideArg, side_index: ElementIndex, tri_index: ElementIndex, side_coords: Coords):
edge_vidx = args.edge_vertex_indices[side_index]
tri_vidx = args.tri_vertex_indices[tri_index]
v0 = tri_vidx[0]
v1 = tri_vidx[1]
cx = float(0.0)
cy = float(0.0)
cz = float(0.0)
if edge_vidx[0] == v0:
cx = 1.0 - side_coords[0]
elif edge_vidx[0] == v1:
cy = 1.0 - side_coords[0]
else:
cz = 1.0 - side_coords[0]
if edge_vidx[1] == v0:
cx = side_coords[0]
elif edge_vidx[1] == v1:
cy = side_coords[0]
else:
cz = side_coords[0]
return Coords(cx, cy, cz)
@wp.func
def tri_to_edge_coords(args: SideArg, side_index: ElementIndex, tri_index: ElementIndex, tri_coords: Coords):
edge_vidx = args.edge_vertex_indices[side_index]
tri_vidx = args.tri_vertex_indices[tri_index]
start = int(2)
end = int(2)
for k in range(2):
v = tri_vidx[k]
if edge_vidx[1] == v:
end = k
elif edge_vidx[0] == v:
start = k
return wp.select(
tri_coords[start] + tri_coords[end] > 0.999, Coords(OUTSIDE), Coords(tri_coords[end], 0.0, 0.0)
)
def _build_topology(self):
from warp.fem.utils import compress_node_indices, masked_indices, _get_pinned_temp_count_buffer
from warp.utils import array_scan
device = self.tri_vertex_indices.device
self._vertex_tri_offsets, self._vertex_tri_indices, _, __ = compress_node_indices(
self.vertex_count(), self.tri_vertex_indices
)
vertex_start_edge_count = wp.zeros(dtype=int, device=device, shape=self.vertex_count())
vertex_start_edge_offsets = wp.empty_like(vertex_start_edge_count)
vertex_edge_ends = wp.empty(dtype=int, device=device, shape=(3 * self.cell_count()))
vertex_edge_tris = wp.empty(dtype=int, device=device, shape=(3 * self.cell_count(), 2))
# Count face edges starting at each vertex
wp.launch(
kernel=Trimesh2D._count_starting_edges_kernel,
device=device,
dim=self.cell_count(),
inputs=[self.tri_vertex_indices, vertex_start_edge_count],
)
array_scan(in_array=vertex_start_edge_count, out_array=vertex_start_edge_offsets, inclusive=False)
# Count number of unique edges (deduplicate across faces)
vertex_unique_edge_count = vertex_start_edge_count
wp.launch(
kernel=Trimesh2D._count_unique_starting_edges_kernel,
device=device,
dim=self.vertex_count(),
inputs=[
self._vertex_tri_offsets,
self._vertex_tri_indices,
self.tri_vertex_indices,
vertex_start_edge_offsets,
vertex_unique_edge_count,
vertex_edge_ends,
vertex_edge_tris,
],
)
vertex_unique_edge_offsets = wp.empty_like(vertex_start_edge_offsets)
array_scan(in_array=vertex_start_edge_count, out_array=vertex_unique_edge_offsets, inclusive=False)
# Get back edge count to host
if device.is_cuda:
edge_count = _get_pinned_temp_count_buffer(device)
# Last vertex will not own any edge, so its count will be zero; just fetching last prefix count is ok
wp.copy(dest=edge_count, src=vertex_unique_edge_offsets, src_offset=self.vertex_count() - 1, count=1)
wp.synchronize_stream(wp.get_stream())
edge_count = int(edge_count.numpy()[0])
else:
edge_count = int(vertex_unique_edge_offsets.numpy()[self.vertex_count() - 1])
self._edge_vertex_indices = wp.empty(shape=(edge_count,), dtype=vec2i, device=device)
self._edge_tri_indices = wp.empty(shape=(edge_count,), dtype=vec2i, device=device)
boundary_mask = wp.empty(shape=(edge_count,), dtype=int, device=device)
# Compress edge data
wp.launch(
kernel=Trimesh2D._compress_edges_kernel,
device=device,
dim=self.vertex_count(),
inputs=[
vertex_start_edge_offsets,
vertex_unique_edge_offsets,
vertex_unique_edge_count,
vertex_edge_ends,
vertex_edge_tris,
self._edge_vertex_indices,
self._edge_tri_indices,
boundary_mask,
],
)
# Flip normals if necessary
wp.launch(
kernel=Trimesh2D._flip_edge_normals,
device=device,
dim=self.side_count(),
inputs=[self._edge_vertex_indices, self._edge_tri_indices, self.tri_vertex_indices, self.positions],
)
self._boundary_edge_indices, _ = masked_indices(boundary_mask)
@wp.kernel
def _count_starting_edges_kernel(
tri_vertex_indices: wp.array2d(dtype=int), vertex_start_edge_count: wp.array(dtype=int)
):
t = wp.tid()
for k in range(3):
v0 = tri_vertex_indices[t, k]
v1 = tri_vertex_indices[t, (k + 1) % 3]
if v0 < v1:
wp.atomic_add(vertex_start_edge_count, v0, 1)
else:
wp.atomic_add(vertex_start_edge_count, v1, 1)
@wp.func
def _find(
needle: int,
values: wp.array(dtype=int),
beg: int,
end: int,
):
for i in range(beg, end):
if values[i] == needle:
return i
return -1
@wp.kernel
def _count_unique_starting_edges_kernel(
vertex_tri_offsets: wp.array(dtype=int),
vertex_tri_indices: wp.array(dtype=int),
tri_vertex_indices: wp.array2d(dtype=int),
vertex_start_edge_offsets: wp.array(dtype=int),
vertex_start_edge_count: wp.array(dtype=int),
edge_ends: wp.array(dtype=int),
edge_tris: wp.array2d(dtype=int),
):
v = wp.tid()
edge_beg = vertex_start_edge_offsets[v]
tri_beg = vertex_tri_offsets[v]
tri_end = vertex_tri_offsets[v + 1]
edge_cur = edge_beg
for tri in range(tri_beg, tri_end):
t = vertex_tri_indices[tri]
for k in range(3):
v0 = tri_vertex_indices[t, k]
v1 = tri_vertex_indices[t, (k + 1) % 3]
if v == wp.min(v0, v1):
other_v = wp.max(v0, v1)
# Check if other_v has been seen
seen_idx = Trimesh2D._find(other_v, edge_ends, edge_beg, edge_cur)
if seen_idx == -1:
edge_ends[edge_cur] = other_v
edge_tris[edge_cur, 0] = t
edge_tris[edge_cur, 1] = t
edge_cur += 1
else:
edge_tris[seen_idx, 1] = t
vertex_start_edge_count[v] = edge_cur - edge_beg
@wp.kernel
def _compress_edges_kernel(
vertex_start_edge_offsets: wp.array(dtype=int),
vertex_unique_edge_offsets: wp.array(dtype=int),
vertex_unique_edge_count: wp.array(dtype=int),
uncompressed_edge_ends: wp.array(dtype=int),
uncompressed_edge_tris: wp.array2d(dtype=int),
edge_vertex_indices: wp.array(dtype=vec2i),
edge_tri_indices: wp.array(dtype=vec2i),
boundary_mask: wp.array(dtype=int),
):
v = wp.tid()
start_beg = vertex_start_edge_offsets[v]
unique_beg = vertex_unique_edge_offsets[v]
unique_count = vertex_unique_edge_count[v]
for e in range(unique_count):
src_index = start_beg + e
edge_index = unique_beg + e
edge_vertex_indices[edge_index] = vec2i(v, uncompressed_edge_ends[src_index])
t0 = uncompressed_edge_tris[src_index, 0]
t1 = uncompressed_edge_tris[src_index, 1]
edge_tri_indices[edge_index] = vec2i(t0, t1)
if t0 == t1:
boundary_mask[edge_index] = 1
else:
boundary_mask[edge_index] = 0
@wp.kernel
def _flip_edge_normals(
edge_vertex_indices: wp.array(dtype=vec2i),
edge_tri_indices: wp.array(dtype=vec2i),
tri_vertex_indices: wp.array2d(dtype=int),
positions: wp.array(dtype=wp.vec2),
):
e = wp.tid()
tri = edge_tri_indices[e][0]
tri_vidx = tri_vertex_indices[tri]
edge_vidx = edge_vertex_indices[e]
tri_centroid = (positions[tri_vidx[0]] + positions[tri_vidx[1]] + positions[tri_vidx[2]]) / 3.0
v0 = positions[edge_vidx[0]]
v1 = positions[edge_vidx[1]]
edge_center = 0.5 * (v1 + v0)
edge_vec = v1 - v0
edge_normal = wp.vec2(-edge_vec[1], edge_vec[0])
# if edge normal points toward first triangle centroid, flip indices
if wp.dot(tri_centroid - edge_center, edge_normal) > 0.0:
edge_vertex_indices[e] = vec2i(edge_vidx[1], edge_vidx[0])
| warp-main | warp/fem/geometry/trimesh_2d.py |
import warp as wp
from warp.fem.types import ElementIndex, Coords, vec2i, vec3i, Sample
from warp.fem.types import NULL_ELEMENT_INDEX, OUTSIDE, NULL_DOF_INDEX, NULL_QP_INDEX
from .geometry import Geometry
from .element import Triangle, Tetrahedron
from .closest_point import project_on_tet_at_origin
@wp.struct
class TetmeshArg:
tet_vertex_indices: wp.array2d(dtype=int)
positions: wp.array(dtype=wp.vec3)
vertex_tet_offsets: wp.array(dtype=int)
vertex_tet_indices: wp.array(dtype=int)
face_vertex_indices: wp.array(dtype=vec3i)
face_tet_indices: wp.array(dtype=vec2i)
class Tetmesh(Geometry):
"""Tetrahedral mesh geometry"""
def __init__(self, tet_vertex_indices: wp.array, positions: wp.array):
"""
Constructs a tetrahedral mesh.
Args:
tet_vertex_indices: warp array of shape (num_tets, 4) containing vertex indices for each tet
positions: warp array of shape (num_vertices, 3) containing 3d position for each vertex
"""
self.dimension = 3
self.tet_vertex_indices = tet_vertex_indices
self.positions = positions
self._face_vertex_indices: wp.array = None
self._face_tet_indices: wp.array = None
self._vertex_tet_offsets: wp.array = None
self._vertex_tet_indices: wp.array = None
self._build_topology()
def cell_count(self):
return self.tet_vertex_indices.shape[0]
def vertex_count(self):
return self.positions.shape[0]
def side_count(self):
return self._face_vertex_indices.shape[0]
def boundary_side_count(self):
return self._boundary_face_indices.shape[0]
def reference_cell(self) -> Triangle:
return Tetrahedron()
def reference_side(self) -> Triangle:
return Triangle()
CellArg = TetmeshArg
SideArg = TetmeshArg
@wp.struct
class SideIndexArg:
boundary_face_indices: wp.array(dtype=int)
# Geometry device interface
def cell_arg_value(self, device) -> CellArg:
args = self.CellArg()
args.tet_vertex_indices = self.tet_vertex_indices.to(device)
args.positions = self.positions.to(device)
args.face_vertex_indices = self._face_vertex_indices.to(device)
args.face_tet_indices = self._face_tet_indices.to(device)
args.vertex_tet_offsets = self._vertex_tet_offsets.to(device)
args.vertex_tet_indices = self._vertex_tet_indices.to(device)
return args
@wp.func
def cell_position(args: CellArg, s: Sample):
tet_idx = args.tet_vertex_indices[s.element_index]
w0 = 1.0 - s.element_coords[0] - s.element_coords[1] - s.element_coords[2]
return (
w0 * args.positions[tet_idx[0]]
+ s.element_coords[0] * args.positions[tet_idx[1]]
+ s.element_coords[1] * args.positions[tet_idx[2]]
+ s.element_coords[2] * args.positions[tet_idx[3]]
)
@wp.func
def _project_on_tet(args: CellArg, pos: wp.vec3, tet_index: int):
p0 = args.positions[args.tet_vertex_indices[tet_index, 0]]
q = pos - p0
e1 = args.positions[args.tet_vertex_indices[tet_index, 1]] - p0
e2 = args.positions[args.tet_vertex_indices[tet_index, 2]] - p0
e3 = args.positions[args.tet_vertex_indices[tet_index, 3]] - p0
dist, coords = project_on_tet_at_origin(q, e1, e2, e3)
return dist, coords
@wp.func
def cell_lookup(args: CellArg, pos: wp.vec3, guess: Sample):
closest_tet = int(NULL_ELEMENT_INDEX)
closest_coords = Coords(OUTSIDE)
closest_dist = float(1.0e8)
for v in range(4):
vtx = args.tet_vertex_indices[guess.element_index, v]
tet_beg = args.vertex_tet_offsets[vtx]
tet_end = args.vertex_tet_offsets[vtx + 1]
for t in range(tet_beg, tet_end):
tet = args.vertex_tet_indices[t]
dist, coords = Tetmesh._project_on_tet(args, pos, tet)
if dist <= closest_dist:
closest_dist = dist
closest_tet = tet
closest_coords = coords
return Sample(closest_tet, closest_coords, NULL_QP_INDEX, 0.0, NULL_DOF_INDEX, NULL_DOF_INDEX)
@wp.func
def cell_measure(args: CellArg, cell_index: ElementIndex, coords: Coords):
tet_idx = args.tet_vertex_indices[cell_index]
v0 = args.positions[tet_idx[0]]
v1 = args.positions[tet_idx[1]]
v2 = args.positions[tet_idx[2]]
v3 = args.positions[tet_idx[3]]
mat = wp.mat33(
v1 - v0,
v2 - v0,
v3 - v0,
)
return wp.abs(wp.determinant(mat)) / 6.0
@wp.func
def cell_measure(args: CellArg, s: Sample):
return Tetmesh.cell_measure(args, s.element_index, s.element_coords)
@wp.func
def cell_measure_ratio(args: CellArg, s: Sample):
return 1.0
@wp.func
def cell_normal(args: CellArg, s: Sample):
return wp.vec3(0.0)
def side_arg_value(self, device) -> SideArg:
return self.cell_arg_value(device)
def side_index_arg_value(self, device) -> SideIndexArg:
args = self.SideIndexArg()
args.boundary_face_indices = self._boundary_face_indices.to(device)
return args
@wp.func
def boundary_side_index(args: SideIndexArg, boundary_side_index: int):
"""Boundary side to side index"""
return args.boundary_face_indices[boundary_side_index]
@wp.func
def side_position(args: SideArg, s: Sample):
face_idx = args.face_vertex_indices[s.element_index]
return (
s.element_coords[0] * args.positions[face_idx[0]]
+ s.element_coords[1] * args.positions[face_idx[1]]
+ s.element_coords[2] * args.positions[face_idx[2]]
)
@wp.func
def side_measure(args: SideArg, side_index: ElementIndex, coords: Coords):
face_idx = args.face_vertex_indices[side_index]
v0 = args.positions[face_idx[0]]
v1 = args.positions[face_idx[1]]
v2 = args.positions[face_idx[2]]
return 0.5 * wp.length(wp.cross(v1 - v0, v2 - v0))
@wp.func
def side_measure(args: SideArg, s: Sample):
return Tetmesh.side_measure(args, s.element_index, s.element_coords)
@wp.func
def side_measure_ratio(args: SideArg, s: Sample):
inner = Tetmesh.side_inner_cell_index(args, s.element_index)
outer = Tetmesh.side_outer_cell_index(args, s.element_index)
return Tetmesh.side_measure(args, s) / wp.min(
Tetmesh.cell_measure(args, inner, Coords()),
Tetmesh.cell_measure(args, outer, Coords()),
)
@wp.func
def side_normal(args: SideArg, s: Sample):
face_idx = args.face_vertex_indices[s.element_index]
v0 = args.positions[face_idx[0]]
v1 = args.positions[face_idx[1]]
v2 = args.positions[face_idx[2]]
return wp.normalize(wp.cross(v1 - v0, v2 - v0))
@wp.func
def face_to_tet_coords(args: SideArg, side_index: ElementIndex, tet_index: ElementIndex, side_coords: Coords):
fvi = args.face_vertex_indices[side_index]
tv1 = args.tet_vertex_indices[tet_index, 1]
tv2 = args.tet_vertex_indices[tet_index, 2]
tv3 = args.tet_vertex_indices[tet_index, 3]
c1 = float(0.0)
c2 = float(0.0)
c3 = float(0.0)
for k in range(3):
if tv1 == fvi[k]:
c1 = side_coords[k]
elif tv2 == fvi[k]:
c2 = side_coords[k]
elif tv3 == fvi[k]:
c3 = side_coords[k]
return Coords(c1, c2, c3)
@wp.func
def tet_to_face_coords(args: SideArg, side_index: ElementIndex, tet_index: ElementIndex, tet_coords: Coords):
fvi = args.face_vertex_indices[side_index]
tv1 = args.tet_vertex_indices[tet_index, 1]
tv2 = args.tet_vertex_indices[tet_index, 2]
tv3 = args.tet_vertex_indices[tet_index, 3]
if tv1 == fvi[0]:
c0 = tet_coords[0]
elif tv2 == fvi[0]:
c0 = tet_coords[1]
elif tv3 == fvi[0]:
c0 = tet_coords[2]
else:
c0 = 1.0 - tet_coords[0] - tet_coords[1] - tet_coords[2]
if tv1 == fvi[1]:
c1 = tet_coords[0]
elif tv2 == fvi[1]:
c1 = tet_coords[1]
elif tv3 == fvi[1]:
c1 = tet_coords[2]
else:
c1 = 1.0 - tet_coords[0] - tet_coords[1] - tet_coords[2]
if tv1 == fvi[2]:
c2 = tet_coords[0]
elif tv2 == fvi[2]:
c2 = tet_coords[1]
elif tv3 == fvi[2]:
c2 = tet_coords[2]
else:
c2 = 1.0 - tet_coords[0] - tet_coords[1] - tet_coords[2]
return wp.select(c0 + c1 + c2 > 0.999, Coords(OUTSIDE), Coords(c0, c1, c2))
@wp.func
def side_inner_cell_index(arg: SideArg, side_index: ElementIndex):
return arg.face_tet_indices[side_index][0]
@wp.func
def side_outer_cell_index(arg: SideArg, side_index: ElementIndex):
return arg.face_tet_indices[side_index][1]
def _build_topology(self):
from warp.fem.utils import compress_node_indices, masked_indices, _get_pinned_temp_count_buffer
from warp.utils import array_scan
device = self.tet_vertex_indices.device
self._vertex_tet_offsets, self._vertex_tet_indices, _, __ = compress_node_indices(
self.vertex_count(), self.tet_vertex_indices
)
vertex_start_face_count = wp.zeros(dtype=int, device=device, shape=self.vertex_count())
vertex_start_face_offsets = wp.empty_like(vertex_start_face_count)
vertex_face_other_vs = wp.empty(dtype=vec2i, device=device, shape=(4 * self.cell_count()))
vertex_face_tets = wp.empty(dtype=int, device=device, shape=(4 * self.cell_count(), 2))
# Count face edges starting at each vertex
wp.launch(
kernel=Tetmesh._count_starting_faces_kernel,
device=device,
dim=self.cell_count(),
inputs=[self.tet_vertex_indices, vertex_start_face_count],
)
array_scan(in_array=vertex_start_face_count, out_array=vertex_start_face_offsets, inclusive=False)
# Count number of unique edges (deduplicate across faces)
vertex_unique_face_count = vertex_start_face_count
wp.launch(
kernel=Tetmesh._count_unique_starting_faces_kernel,
device=device,
dim=self.vertex_count(),
inputs=[
self._vertex_tet_offsets,
self._vertex_tet_indices,
self.tet_vertex_indices,
vertex_start_face_offsets,
vertex_unique_face_count,
vertex_face_other_vs,
vertex_face_tets,
],
)
vertex_unique_face_offsets = wp.empty_like(vertex_start_face_offsets)
array_scan(in_array=vertex_start_face_count, out_array=vertex_unique_face_offsets, inclusive=False)
# Get back edge count to host
if device.is_cuda:
face_count = _get_pinned_temp_count_buffer(device)
# Last vertex will not own any edge, so its count will be zero; just fetching last prefix count is ok
wp.copy(dest=face_count, src=vertex_unique_face_offsets, src_offset=self.vertex_count() - 1, count=1)
wp.synchronize_stream(wp.get_stream())
face_count = int(face_count.numpy()[0])
else:
face_count = int(vertex_unique_face_offsets.numpy()[self.vertex_count() - 1])
self._face_vertex_indices = wp.empty(shape=(face_count,), dtype=vec3i, device=device)
self._face_tet_indices = wp.empty(shape=(face_count,), dtype=vec2i, device=device)
boundary_mask = wp.empty(shape=(face_count,), dtype=int, device=device)
# Compress edge data
wp.launch(
kernel=Tetmesh._compress_faces_kernel,
device=device,
dim=self.vertex_count(),
inputs=[
vertex_start_face_offsets,
vertex_unique_face_offsets,
vertex_unique_face_count,
vertex_face_other_vs,
vertex_face_tets,
self._face_vertex_indices,
self._face_tet_indices,
boundary_mask,
],
)
# Flip normals if necessary
wp.launch(
kernel=Tetmesh._flip_face_normals,
device=device,
dim=self.side_count(),
inputs=[self._face_vertex_indices, self._face_tet_indices, self.tet_vertex_indices, self.positions],
)
self._boundary_face_indices, _ = masked_indices(boundary_mask)
@wp.kernel
def _count_starting_faces_kernel(
tet_vertex_indices: wp.array2d(dtype=int), vertex_start_face_count: wp.array(dtype=int)
):
t = wp.tid()
for k in range(4):
vi = vec3i(tet_vertex_indices[t, k], tet_vertex_indices[t, (k + 1) % 4], tet_vertex_indices[t, (k + 2) % 4])
vm = wp.min(vi)
for i in range(3):
if vm == vi[i]:
wp.atomic_add(vertex_start_face_count, vm, 1)
@wp.func
def _find(
needle: vec2i,
values: wp.array(dtype=vec2i),
beg: int,
end: int,
):
for i in range(beg, end):
if values[i] == needle:
return i
return -1
@wp.kernel
def _count_unique_starting_faces_kernel(
vertex_tet_offsets: wp.array(dtype=int),
vertex_tet_indices: wp.array(dtype=int),
tet_vertex_indices: wp.array2d(dtype=int),
vertex_start_face_offsets: wp.array(dtype=int),
vertex_start_face_count: wp.array(dtype=int),
face_other_vs: wp.array(dtype=vec2i),
face_tets: wp.array2d(dtype=int),
):
v = wp.tid()
face_beg = vertex_start_face_offsets[v]
tet_beg = vertex_tet_offsets[v]
tet_end = vertex_tet_offsets[v + 1]
face_cur = face_beg
for tet in range(tet_beg, tet_end):
t = vertex_tet_indices[tet]
for k in range(4):
vi = vec3i(
tet_vertex_indices[t, k], tet_vertex_indices[t, (k + 1) % 4], tet_vertex_indices[t, (k + 2) % 4]
)
min_v = wp.min(vi)
if v == min_v:
max_v = wp.max(vi)
mid_v = vi[0] + vi[1] + vi[2] - min_v - max_v
other_v = vec2i(mid_v, max_v)
# Check if other_v has been seen
seen_idx = Tetmesh._find(other_v, face_other_vs, face_beg, face_cur)
if seen_idx == -1:
face_other_vs[face_cur] = other_v
face_tets[face_cur, 0] = t
face_tets[face_cur, 1] = t
face_cur += 1
else:
face_tets[seen_idx, 1] = t
vertex_start_face_count[v] = face_cur - face_beg
@wp.kernel
def _compress_faces_kernel(
vertex_start_face_offsets: wp.array(dtype=int),
vertex_unique_face_offsets: wp.array(dtype=int),
vertex_unique_face_count: wp.array(dtype=int),
uncompressed_face_other_vs: wp.array(dtype=vec2i),
uncompressed_face_tets: wp.array2d(dtype=int),
face_vertex_indices: wp.array(dtype=vec3i),
face_tet_indices: wp.array(dtype=vec2i),
boundary_mask: wp.array(dtype=int),
):
v = wp.tid()
start_beg = vertex_start_face_offsets[v]
unique_beg = vertex_unique_face_offsets[v]
unique_count = vertex_unique_face_count[v]
for f in range(unique_count):
src_index = start_beg + f
face_index = unique_beg + f
face_vertex_indices[face_index] = vec3i(
v,
uncompressed_face_other_vs[src_index][0],
uncompressed_face_other_vs[src_index][1],
)
t0 = uncompressed_face_tets[src_index, 0]
t1 = uncompressed_face_tets[src_index, 1]
face_tet_indices[face_index] = vec2i(t0, t1)
if t0 == t1:
boundary_mask[face_index] = 1
else:
boundary_mask[face_index] = 0
@wp.kernel
def _flip_face_normals(
face_vertex_indices: wp.array(dtype=vec3i),
face_tet_indices: wp.array(dtype=vec2i),
tet_vertex_indices: wp.array2d(dtype=int),
positions: wp.array(dtype=wp.vec3),
):
e = wp.tid()
tet = face_tet_indices[e][0]
tet_vidx = tet_vertex_indices[tet]
face_vidx = face_vertex_indices[e]
tet_centroid = (
positions[tet_vidx[0]] + positions[tet_vidx[1]] + positions[tet_vidx[2]] + positions[tet_vidx[3]]
) / 4.0
v0 = positions[face_vidx[0]]
v1 = positions[face_vidx[1]]
v2 = positions[face_vidx[2]]
face_center = (v1 + v0 + v2) / 3.0
face_normal = wp.cross(v1 - v0, v2 - v0)
# if face normal points toward first tet centroid, flip indices
if wp.dot(tet_centroid - face_center, face_normal) > 0.0:
face_vertex_indices[e] = vec3i(face_vidx[0], face_vidx[2], face_vidx[1])
| warp-main | warp/fem/geometry/tetmesh.py |
from typing import Any
import warp as wp
from warp.fem.types import Sample, ElementIndex, Coords
from .element import Element
class Geometry:
"""
Interface class for discrete geometries
A geometry is composed of cells and sides. Sides may be boundary or interior (between cells).
"""
dimension: int = 0
def cell_count(self):
raise NotImplementedError
def side_count(self):
raise NotImplementedError
def boundary_side_count(self):
raise NotImplementedError
def reference_cell(self) -> Element:
"""Prototypical element for a cell"""
raise NotImplementedError
def reference_side(self) -> Element:
"""Prototypical element for a side"""
raise NotImplementedError
@property
def name(self) -> str:
return self.__class__.__name__
def __str__(self) -> str:
return self.name
CellArg: wp.codegen.Struct
"""Structure containing arguments to be passed to device function evaluating cell-related quantities"""
SideArg: wp.codegen.Struct
"""Structure containing arguments to be passed to device function evaluating side-related quantities"""
def cell_arg_value(self, device) -> "Geometry.CellArg":
"""Value of the arguments to be passed to cell-related device functions"""
raise NotImplementedError
def cell_position(args: "Geometry.CellArg", s: "Sample"):
"""Device function returning the cell position at a sample point"""
raise NotImplementedError
def cell_lookup(args: "Geometry.CellArg", pos: Any):
"""Device function returning the cell sample point corresponding to a world position"""
raise NotImplementedError
def cell_lookup(args: "Geometry.CellArg", pos: Any, guess: "Sample"):
"""Device function returning the cell sample point corresponding to a world position. Can use guess for faster lookup"""
raise NotImplementedError
def cell_measure(args: "Geometry.CellArg", cell_index: ElementIndex, coords: Coords):
"""Device function returning the measure determinant (e.g. volume, area) at a given point"""
raise NotImplementedError
def cell_measure(args: "Geometry.CellArg", s: "Sample"):
"""Device function returning the measure determinant (e.g. volume, area) at a given point"""
raise NotImplementedError
def cell_measure_ratio(args: "Geometry.CellArg", s: "Sample"):
"""Device function returning the ratio of the measure of a side to that of its neighbour cells"""
raise NotImplementedError
def cell_normal(args: "Geometry.CellArg", s: "Sample"):
"""Device function returning the element normal at a sample point"""
raise NotImplementedError
def side_arg_value(self, device) -> "Geometry.SideArg":
"""Value of the arguments to be passed to side-related device functions"""
raise NotImplementedError
def boundary_side_index(args: "Geometry.SideArg", boundary_side_index: int):
"""Device function returning the side index corresponding to a boundary side"""
raise NotImplementedError
def side_position(args: "Geometry.SideArg", s: "Sample"):
"""Device function returning the side position at a sample point"""
raise NotImplementedError
def side_measure(args: "Geometry.SideArg", cell_index: ElementIndex, coords: Coords):
"""Device function returning the measure determinant (e.g. volume, area) at a given point"""
raise NotImplementedError
def side_measure(args: "Geometry.SideArg", s: "Sample"):
"""Device function returning the measure determinant (e.g. volume, area) at a given point"""
raise NotImplementedError
def side_measure_ratio(args: "Geometry.SideArg", s: "Sample"):
"""Device function returning the ratio of the measure of a side to that of its neighbour cells"""
raise NotImplementedError
def side_normal(args: "Geometry.SideArg", s: "Sample"):
"""Device function returning the element normal at a sample point"""
raise NotImplementedError
def side_inner_cell_index(args: "Geometry.SideArg", side_index: ElementIndex):
"""Device function returning the inner cell index for a given side"""
raise NotImplementedError
def side_outer_cell_index(args: "Geometry.SideArg", side_index: ElementIndex):
"""Device function returning the outer cell index for a given side"""
raise NotImplementedError
| warp-main | warp/fem/geometry/geometry.py |
import warp as wp
import numpy as np
from warp.fem.types import ElementIndex, Coords, OUTSIDE
from warp.fem.types import vec2i, vec3i
from warp.fem.polynomial import Polynomial, lagrange_scales, quadrature_1d, is_closed
from warp.fem.geometry import Grid3D
from .dof_mapper import DofMapper
from .nodal_function_space import NodalFunctionSpace, NodalFunctionSpaceTrace
class Grid3DFunctionSpace(NodalFunctionSpace):
DIMENSION = wp.constant(3)
@wp.struct
class SpaceArg:
geo_arg: Grid3D.SideArg
inv_cell_size: wp.vec3
def __init__(self, grid: Grid3D, dtype: type = float, dof_mapper: DofMapper = None):
super().__init__(dtype, dof_mapper)
self._grid = grid
@property
def geometry(self) -> Grid3D:
return self._grid
def space_arg_value(self, device):
arg = self.SpaceArg()
arg.geo_arg = self.geometry.side_arg_value(device)
arg.inv_cell_size = wp.vec3(
1.0 / self.geometry.cell_size[0],
1.0 / self.geometry.cell_size[1],
1.0 / self.geometry.cell_size[2],
)
return arg
class Trace(NodalFunctionSpaceTrace):
def __init__(self, space: NodalFunctionSpace):
super().__init__(space)
self.ORDER = space.ORDER
@wp.func
def _inner_cell_index(args: SpaceArg, side_index: ElementIndex):
cell_index = Grid3D.side_inner_cell_index(args.geo_arg, side_index)
return cell_index
@wp.func
def _outer_cell_index(args: SpaceArg, side_index: ElementIndex):
return Grid3D.side_outer_cell_index(args.geo_arg, side_index)
@wp.func
def _inner_cell_coords(args: SpaceArg, side_index: ElementIndex, side_coords: Coords):
side = Grid3D.get_side(args.geo_arg, side_index)
if side.origin[0] == 0:
inner_alt = 0.0
else:
inner_alt = 1.0
return Grid3D._local_to_world(side.axis, wp.vec3(inner_alt, side_coords[0], side_coords[1]))
@wp.func
def _outer_cell_coords(args: SpaceArg, side_index: ElementIndex, side_coords: Coords):
side = Grid3D.get_side(args.geo_arg, side_index)
alt_axis = Grid3D.LOC_TO_WORLD[side.axis, 0]
if side.origin[0] == args.geo_arg.cell_arg.res[alt_axis]:
outer_alt = 1.0
else:
outer_alt = 0.0
return Grid3D._local_to_world(side.axis, wp.vec3(outer_alt, side_coords[0], side_coords[1]))
@wp.func
def _cell_to_side_coords(
args: SpaceArg,
side_index: ElementIndex,
element_index: ElementIndex,
element_coords: Coords,
):
side = Grid3D.get_side(args.geo_arg, side_index)
cell = Grid3D.get_cell(args.geo_arg.cell_arg.res, element_index)
if float(side.origin[0] - cell[side.axis]) == element_coords[side.axis]:
long_axis = Grid3D.LOC_TO_WORLD[side.axis, 1]
lat_axis = Grid3D.LOC_TO_WORLD[side.axis, 2]
return Coords(element_coords[long_axis], element_coords[lat_axis], 0.0)
return Coords(OUTSIDE)
@wp.func
def _vertex_coords(vidx_in_cell: int):
x = vidx_in_cell // 4
y = (vidx_in_cell - 4 * x) // 2
z = vidx_in_cell - 4 * x - 2 * y
return vec3i(x, y, z)
@wp.func
def _vertex_coords_f(vidx_in_cell: int):
x = vidx_in_cell // 4
y = (vidx_in_cell - 4 * x) // 2
z = vidx_in_cell - 4 * x - 2 * y
return wp.vec3(float(x), float(y), float(z))
@wp.func
def _vertex_index(args: SpaceArg, cell_index: ElementIndex, vidx_in_cell: int):
res = args.geo_arg.cell_arg.res
strides = vec2i((res[1] + 1) * (res[2] + 1), res[2] + 1)
corner = Grid3D.get_cell(res, cell_index) + Grid3DFunctionSpace._vertex_coords(vidx_in_cell)
return Grid3D._from_3d_index(strides, corner)
class Grid3DPiecewiseConstantSpace(Grid3DFunctionSpace):
ORDER = wp.constant(0)
NODES_PER_ELEMENT = wp.constant(1)
def __init__(self, grid: Grid3D, dtype: type = float, dof_mapper: DofMapper = None):
super().__init__(grid, dtype, dof_mapper)
self.element_outer_weight = self.element_inner_weight
self.element_outer_weight_gradient = self.element_inner_weight_gradient
def node_count(self) -> int:
return self._grid.cell_count()
def node_positions(self):
X = (np.arange(0, self.geometry.res[0], dtype=float) + 0.5) * self._grid.cell_size[0] + self._grid.bounds_lo[0]
Y = (np.arange(0, self.geometry.res[1], dtype=float) + 0.5) * self._grid.cell_size[1] + self._grid.bounds_lo[1]
Z = (np.arange(0, self.geometry.res[2], dtype=float) + 0.5) * self._grid.cell_size[2] + self._grid.bounds_lo[2]
return np.meshgrid(X, Y, Z, indexing="ij")
@wp.func
def element_node_index(
args: Grid3DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return element_index
@wp.func
def node_coords_in_element(
args: Grid3DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
if node_index_in_elt == 0:
return Coords(0.5, 0.5, 0.5)
return Coords(OUTSIDE)
@wp.func
def node_quadrature_weight(
args: Grid3DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return 1.0
@wp.func
def element_inner_weight(
args: Grid3DFunctionSpace.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
if node_index_in_elt == 0:
return 1.0
return 0.0
@wp.func
def element_inner_weight_gradient(
args: Grid3DFunctionSpace.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
return wp.vec3(0.0)
class Trace(Grid3DFunctionSpace.Trace):
NODES_PER_ELEMENT = wp.constant(2)
ORDER = wp.constant(0)
def __init__(self, space: "Grid3DPiecewiseConstantSpace"):
super().__init__(space)
self.element_node_index = self._make_element_node_index(space)
self.element_inner_weight = self._make_element_inner_weight(space)
self.element_inner_weight_gradient = self._make_element_inner_weight_gradient(space)
self.element_outer_weight = self._make_element_outer_weight(space)
self.element_outer_weight_gradient = self._make_element_outer_weight_gradient(space)
@wp.func
def node_coords_in_element(
args: Grid3DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_element: int,
):
if node_index_in_element >= 0:
return Coords(0.5, 0.5, 0.0)
elif node_index_in_element == 1:
return Coords(0.5, 0.5, 0.0)
return Coords(OUTSIDE)
@wp.func
def node_quadrature_weight(
args: Grid3DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return 1.0
def trace(self):
return Grid3DPiecewiseConstantSpace.Trace(self)
class GridTripolynomialShapeFunctions:
def __init__(self, degree: int, family: Polynomial):
self.family = family
self.ORDER = wp.constant(degree)
self.NODES_PER_ELEMENT = wp.constant((degree + 1) ** 3)
self.NODES_PER_SIDE = wp.constant(degree + 1)
lobatto_coords, lobatto_weight = quadrature_1d(point_count=degree + 1, family=family)
lagrange_scale = lagrange_scales(lobatto_coords)
NodeVec = wp.types.vector(length=degree + 1, dtype=wp.float32)
self.LOBATTO_COORDS = wp.constant(NodeVec(lobatto_coords))
self.LOBATTO_WEIGHT = wp.constant(NodeVec(lobatto_weight))
self.LAGRANGE_SCALE = wp.constant(NodeVec(lagrange_scale))
self._node_ijk = self._make_node_ijk()
@property
def name(self) -> str:
return f"{self.family}_{self.ORDER}"
def _make_node_ijk(self):
ORDER = self.ORDER
def node_ijk(
node_index_in_elt: int,
):
node_i = node_index_in_elt // ((ORDER + 1) * (ORDER + 1))
node_jk = node_index_in_elt - (ORDER + 1) * (ORDER + 1) * node_i
node_j = node_jk // (ORDER + 1)
node_k = node_jk - (ORDER + 1) * node_j
return node_i, node_j, node_k
from warp.fem import cache
return cache.get_func(node_ijk, self.name)
def make_node_coords_in_element(self):
LOBATTO_COORDS = self.LOBATTO_COORDS
def node_coords_in_element(
args: Grid3DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
node_i, node_j, node_k = self._node_ijk(node_index_in_elt)
return Coords(LOBATTO_COORDS[node_i], LOBATTO_COORDS[node_j], LOBATTO_COORDS[node_k])
from warp.fem import cache
return cache.get_func(node_coords_in_element, self.name)
def make_node_quadrature_weight(self):
ORDER = self.ORDER
LOBATTO_WEIGHT = self.LOBATTO_WEIGHT
def node_quadrature_weight(
args: Grid3DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
node_i, node_j, node_k = self._node_ijk(node_index_in_elt)
return LOBATTO_WEIGHT[node_i] * LOBATTO_WEIGHT[node_j] * LOBATTO_WEIGHT[node_k]
def node_quadrature_weight_linear(
args: Grid3DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return 0.125
from warp.fem import cache
if ORDER == 1:
return cache.get_func(node_quadrature_weight_linear, self.name)
return cache.get_func(node_quadrature_weight, self.name)
def make_trace_node_quadrature_weight(self):
ORDER = self.ORDER
NODES_PER_ELEMENT = self.NODES_PER_ELEMENT
LOBATTO_WEIGHT = self.LOBATTO_WEIGHT
def trace_node_quadrature_weight(
args: Grid3DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
if node_index_in_elt >= NODES_PER_ELEMENT:
node_index_in_cell = node_index_in_elt - NODES_PER_ELEMENT
else:
node_index_in_cell = node_index_in_elt
# We're either on a side interior or at a vertex
# If we find one index at extremum, pick the two other
node_i, node_j, node_k = self._node_ijk(node_index_in_cell)
if node_i == 0 or node_i == ORDER:
return LOBATTO_WEIGHT[node_j] * LOBATTO_WEIGHT[node_k]
if node_j == 0 or node_j == ORDER:
return LOBATTO_WEIGHT[node_i] * LOBATTO_WEIGHT[node_k]
return LOBATTO_WEIGHT[node_i] * LOBATTO_WEIGHT[node_j]
def trace_node_quadrature_weight_linear(
args: Grid3DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return 0.25
from warp.fem import cache
if ORDER == 1:
return cache.get_func(trace_node_quadrature_weight_linear, self.name)
return cache.get_func(trace_node_quadrature_weight, self.name)
def make_element_inner_weight(self):
ORDER = self.ORDER
NODES_PER_ELEMENT = self.NODES_PER_ELEMENT
LOBATTO_COORDS = self.LOBATTO_COORDS
LAGRANGE_SCALE = self.LAGRANGE_SCALE
def element_inner_weight(
args: Grid3DFunctionSpace.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
if node_index_in_elt < 0 or node_index_in_elt >= NODES_PER_ELEMENT:
return 0.0
node_i, node_j, node_k = self._node_ijk(node_index_in_elt)
w = float(1.0)
for k in range(ORDER + 1):
if k != node_i:
w *= coords[0] - LOBATTO_COORDS[k]
if k != node_j:
w *= coords[1] - LOBATTO_COORDS[k]
if k != node_k:
w *= coords[2] - LOBATTO_COORDS[k]
w *= LAGRANGE_SCALE[node_i] * LAGRANGE_SCALE[node_j] * LAGRANGE_SCALE[node_k]
return w
def element_inner_weight_linear(
args: Grid3DFunctionSpace.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
if node_index_in_elt < 0 or node_index_in_elt >= 8:
return 0.0
v = Grid3DFunctionSpace._vertex_coords_f(node_index_in_elt)
wx = (1.0 - coords[0]) * (1.0 - v[0]) + v[0] * coords[0]
wy = (1.0 - coords[1]) * (1.0 - v[1]) + v[1] * coords[1]
wz = (1.0 - coords[2]) * (1.0 - v[2]) + v[2] * coords[2]
return wx * wy * wz
from warp.fem import cache
if ORDER == 1:
return cache.get_func(element_inner_weight_linear, self.name)
return cache.get_func(element_inner_weight, self.name)
def make_element_inner_weight_gradient(self):
ORDER = self.ORDER
NODES_PER_ELEMENT = self.NODES_PER_ELEMENT
LOBATTO_COORDS = self.LOBATTO_COORDS
LAGRANGE_SCALE = self.LAGRANGE_SCALE
def element_inner_weight_gradient(
args: Grid3DFunctionSpace.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
if node_index_in_elt < 0 or node_index_in_elt >= NODES_PER_ELEMENT:
return wp.vec3(0.0)
node_i, node_j, node_k = self._node_ijk(node_index_in_elt)
prefix_xy = float(1.0)
prefix_yz = float(1.0)
prefix_zx = float(1.0)
for k in range(ORDER + 1):
if k != node_i:
prefix_yz *= coords[0] - LOBATTO_COORDS[k]
if k != node_j:
prefix_zx *= coords[1] - LOBATTO_COORDS[k]
if k != node_k:
prefix_xy *= coords[2] - LOBATTO_COORDS[k]
prefix_x = prefix_zx * prefix_xy
prefix_y = prefix_yz * prefix_xy
prefix_z = prefix_zx * prefix_yz
grad_x = float(0.0)
grad_y = float(0.0)
grad_z = float(0.0)
for k in range(ORDER + 1):
if k != node_i:
delta_x = coords[0] - LOBATTO_COORDS[k]
grad_x = grad_x * delta_x + prefix_x
prefix_x *= delta_x
if k != node_j:
delta_y = coords[1] - LOBATTO_COORDS[k]
grad_y = grad_y * delta_y + prefix_y
prefix_y *= delta_y
if k != node_k:
delta_z = coords[2] - LOBATTO_COORDS[k]
grad_z = grad_z * delta_z + prefix_z
prefix_z *= delta_z
grad = (
LAGRANGE_SCALE[node_i]
* LAGRANGE_SCALE[node_j]
* LAGRANGE_SCALE[node_k]
* wp.vec3(
grad_x * args.inv_cell_size[0],
grad_y * args.inv_cell_size[1],
grad_z * args.inv_cell_size[2],
)
)
return grad
def element_inner_weight_gradient_linear(
args: Grid3DFunctionSpace.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
if node_index_in_elt < 0 or node_index_in_elt >= 8:
return wp.vec3(0.0)
v = Grid3DFunctionSpace._vertex_coords_f(node_index_in_elt)
wx = (1.0 - coords[0]) * (1.0 - v[0]) + v[0] * coords[0]
wy = (1.0 - coords[1]) * (1.0 - v[1]) + v[1] * coords[1]
wz = (1.0 - coords[2]) * (1.0 - v[2]) + v[2] * coords[2]
dx = (2.0 * v[0] - 1.0) * args.inv_cell_size[0]
dy = (2.0 * v[1] - 1.0) * args.inv_cell_size[1]
dz = (2.0 * v[2] - 1.0) * args.inv_cell_size[2]
return wp.vec3(dx * wy * wz, dy * wz * wx, dz * wx * wy)
from warp.fem import cache
if ORDER == 1:
return cache.get_func(element_inner_weight_gradient_linear, self.name)
return cache.get_func(element_inner_weight_gradient, self.name)
class GridTripolynomialSpace(Grid3DFunctionSpace):
def __init__(
self,
grid: Grid3D,
degree: int,
family: int,
dtype: type = float,
dof_mapper: DofMapper = None,
):
super().__init__(grid, dtype, dof_mapper)
if family is None:
family = Polynomial.LOBATTO_GAUSS_LEGENDRE
if not is_closed(family):
raise ValueError("A closed polynomial family is required to defined a continuous funciton space")
self._shape = GridTripolynomialShapeFunctions(degree, family=family)
self.ORDER = self._shape.ORDER
self.NODES_PER_ELEMENT = self._shape.NODES_PER_ELEMENT
self.element_node_index = self._make_element_node_index()
self.node_coords_in_element = self._shape.make_node_coords_in_element()
self.node_quadrature_weight = self._shape.make_node_quadrature_weight()
self.element_inner_weight = self._shape.make_element_inner_weight()
self.element_inner_weight_gradient = self._shape.make_element_inner_weight_gradient()
self.element_outer_weight = self.element_inner_weight
self.element_outer_weight_gradient = self.element_inner_weight_gradient
def node_count(self) -> int:
return (
(self._grid.res[0] * self.ORDER + 1)
* (self._grid.res[1] * self.ORDER + 1)
* (self._grid.res[2] * self.ORDER + 1)
)
def node_positions(self):
res = self._grid.res
cell_coords = np.array(self._shape.LOBATTO_COORDS)[:-1]
grid_coords_x = np.repeat(np.arange(0, res[0], dtype=float), len(cell_coords)) + np.tile(
cell_coords, reps=res[0]
)
grid_coords_x = np.append(grid_coords_x, res[0])
X = grid_coords_x * self._grid.cell_size[0] + self._grid.origin[0]
grid_coords_y = np.repeat(np.arange(0, res[1], dtype=float), len(cell_coords)) + np.tile(
cell_coords, reps=res[1]
)
grid_coords_y = np.append(grid_coords_y, res[1])
Y = grid_coords_y * self._grid.cell_size[1] + self._grid.origin[1]
grid_coords_z = np.repeat(np.arange(0, res[2], dtype=float), len(cell_coords)) + np.tile(
cell_coords, reps=res[2]
)
grid_coords_z = np.append(grid_coords_z, res[2])
Z = grid_coords_z * self._grid.cell_size[2] + self._grid.origin[2]
return np.meshgrid(X, Y, Z, indexing="ij")
def _make_element_node_index(self):
ORDER = self.ORDER
def element_node_index(
args: Grid3DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
res = args.geo_arg.cell_arg.res
cell = Grid3D.get_cell(res, element_index)
node_i, node_j, node_k = self._shape._node_ijk(node_index_in_elt)
node_x = ORDER * cell[0] + node_i
node_y = ORDER * cell[1] + node_j
node_z = ORDER * cell[2] + node_k
node_pitch_y = (res[2] * ORDER) + 1
node_pitch_x = node_pitch_y * ((res[1] * ORDER) + 1)
node_index = node_pitch_x * node_x + node_pitch_y * node_y + node_z
return node_index
from warp.fem import cache
return cache.get_func(element_node_index, f"{self.name}_{ORDER}")
class Trace(Grid3DFunctionSpace.Trace):
def __init__(self, space: "GridTripolynomialSpace"):
super().__init__(space)
self.element_node_index = self._make_element_node_index(space)
self.node_coords_in_element = self._make_node_coords_in_element(space)
self.node_quadrature_weight = space._shape.make_trace_node_quadrature_weight()
self.element_inner_weight = self._make_element_inner_weight(space)
self.element_inner_weight_gradient = self._make_element_inner_weight_gradient(space)
self.element_outer_weight = self._make_element_outer_weight(space)
self.element_outer_weight_gradient = self._make_element_outer_weight_gradient(space)
def trace(self):
return GridTripolynomialSpace.Trace(self)
class GridDGTripolynomialSpace(Grid3DFunctionSpace):
def __init__(
self,
grid: Grid3D,
degree: int,
family: Polynomial,
dtype: type = float,
dof_mapper: DofMapper = None,
):
super().__init__(grid, dtype, dof_mapper)
if family is None:
family = Polynomial.LOBATTO_GAUSS_LEGENDRE
self._shape = GridTripolynomialShapeFunctions(degree, family=family)
self.ORDER = self._shape.ORDER
self.NODES_PER_ELEMENT = self._shape.NODES_PER_ELEMENT
self.element_node_index = self._make_element_node_index()
self.node_coords_in_element = self._shape.make_node_coords_in_element()
self.node_quadrature_weight = self._shape.make_node_quadrature_weight()
self.element_inner_weight = self._shape.make_element_inner_weight()
self.element_inner_weight_gradient = self._shape.make_element_inner_weight_gradient()
self.element_outer_weight = self.element_inner_weight
self.element_outer_weight_gradient = self.element_inner_weight_gradient
def node_count(self) -> int:
return self._grid.cell_count() * (self.ORDER + 1) ** 3
def node_positions(self):
res = self._grid.res
cell_coords = np.array(self._shape.LOBATTO_COORDS)
grid_coords_x = np.repeat(np.arange(0, res[0], dtype=float), len(cell_coords)) + np.tile(
cell_coords, reps=res[0]
)
X = grid_coords_x * self._grid.cell_size[0] + self._grid.origin[0]
grid_coords_y = np.repeat(np.arange(0, res[1], dtype=float), len(cell_coords)) + np.tile(
cell_coords, reps=res[1]
)
Y = grid_coords_y * self._grid.cell_size[1] + self._grid.origin[1]
grid_coords_z = np.repeat(np.arange(0, res[2], dtype=float), len(cell_coords)) + np.tile(
cell_coords, reps=res[2]
)
Z = grid_coords_z * self._grid.cell_size[2] + self._grid.origin[2]
return np.meshgrid(X, Y, Z, indexing="ij")
def _make_element_node_index(self):
NODES_PER_ELEMENT = self.NODES_PER_ELEMENT
def element_node_index(
args: Grid3DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return element_index * NODES_PER_ELEMENT + node_index_in_elt
from warp.fem import cache
return cache.get_func(element_node_index, f"{self.name}_{self.ORDER}")
class Trace(GridTripolynomialSpace.Trace):
def __init__(self, space: "GridDGTripolynomialSpace"):
super().__init__(space)
def trace(self):
return GridDGTripolynomialSpace.Trace(self)
| warp-main | warp/fem/space/grid_3d_function_space.py |
from typing import Any
import warp as wp
from warp.fem.types import DofIndex, ElementIndex, Coords, get_node_coord
from warp.fem.geometry import GeometryPartition
from warp.fem import utils
from .function_space import FunctionSpace
from .dof_mapper import DofMapper, IdentityMapper
from .partition import make_space_partition, SpacePartition
class NodalFunctionSpace(FunctionSpace):
"""Function space where values are collocated at nodes"""
def __init__(self, dtype: type = float, dof_mapper: DofMapper = None):
self.dof_mapper = IdentityMapper(dtype) if dof_mapper is None else dof_mapper
self.dtype = self.dof_mapper.value_dtype
self.dof_dtype = self.dof_mapper.dof_dtype
if self.dtype == wp.float32:
self.gradient_dtype = wp.vec2
elif self.dtype == wp.vec2:
self.gradient_dtype = wp.mat22
elif self.dtype == wp.vec3:
self.gradient_dtype = wp.mat33
else:
self.gradient_dtype = None
self.VALUE_DOF_COUNT = self.dof_mapper.DOF_SIZE
self.unit_dof_value = self._make_unit_dof_value(self.dof_mapper)
@property
def name(self):
return f"{self.__class__.__qualname__}_{self.ORDER}_{self.dof_mapper}".replace(".", "_")
def make_field(
self,
space_partition: SpacePartition = None,
geometry_partition: GeometryPartition = None,
) -> "wp.fem.field.NodalField":
from warp.fem.field import NodalField
if space_partition is None:
space_partition = make_space_partition(self, geometry_partition)
return NodalField(space=self, space_partition=space_partition)
@staticmethod
def _make_unit_dof_value(dof_mapper: DofMapper):
from warp.fem import cache
def unit_dof_value(args: Any, dof: DofIndex):
return dof_mapper.dof_to_value(utils.unit_element(dof_mapper.dof_dtype(0.0), get_node_coord(dof)))
return cache.get_func(unit_dof_value, str(dof_mapper))
# Interface for generating Trace space
def _inner_cell_index(args: Any, side_index: ElementIndex):
"""Given a side, returns the index of the inner cell"""
raise NotImplementedError
def _outer_cell_index(args: Any, side_index: ElementIndex):
"""Given a side, returns the index of the outer cell"""
raise NotImplementedError
def _inner_cell_coords(args: Any, side_index: ElementIndex, side_coords: Coords):
"""Given coordinates within a side, returns coordinates within the inner cell"""
raise NotImplementedError
def _outer_cell_coords(args: Any, side_index: ElementIndex, side_coords: Coords):
"""Given coordinates within a side, returns coordinates within the outer cell"""
raise NotImplementedError
def _cell_to_side_coords(
args: Any,
side_index: ElementIndex,
element_index: ElementIndex,
element_coords: Coords,
):
"""Given coordinates within a cell, returns coordinates within a side, or OUTSIDE"""
raise NotImplementedError
class NodalFunctionSpaceTrace(NodalFunctionSpace):
"""Trace of a NodalFunctionSpace"""
def __init__(self, space: NodalFunctionSpace):
self._space = space
super().__init__(space.dtype, space.dof_mapper)
self.geometry = space.geometry
self.NODES_PER_ELEMENT = wp.constant(2 * space.NODES_PER_ELEMENT)
self.DIMENSION = space.DIMENSION - 1
self.SpaceArg = space.SpaceArg
self.space_arg_value = space.space_arg_value
def node_count(self) -> int:
return self._space.node_count()
@property
def name(self):
return f"{self._space.name}_Trace"
@staticmethod
def _make_element_node_index(space: NodalFunctionSpace):
from warp.fem import cache
NODES_PER_ELEMENT = space.NODES_PER_ELEMENT
def trace_element_node_index(args: space.SpaceArg, element_index: ElementIndex, node_index_in_elt: int):
if node_index_in_elt < NODES_PER_ELEMENT:
inner_element = space._inner_cell_index(args, element_index)
return space.element_node_index(args, inner_element, node_index_in_elt)
outer_element = space._outer_cell_index(args, element_index)
return space.element_node_index(args, outer_element, node_index_in_elt - NODES_PER_ELEMENT)
return cache.get_func(trace_element_node_index, space.name)
@staticmethod
def _make_node_coords_in_element(space: NodalFunctionSpace):
from warp.fem import cache
NODES_PER_ELEMENT = space.NODES_PER_ELEMENT
def trace_node_coords_in_element(
args: space.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
if node_index_in_elt < NODES_PER_ELEMENT:
neighbour_elem = space._inner_cell_index(args, element_index)
neighbour_coords = space.node_coords_in_element(args, neighbour_elem, node_index_in_elt)
else:
neighbour_elem = space._outer_cell_index(args, element_index)
neighbour_coords = space.node_coords_in_element(
args,
neighbour_elem,
node_index_in_elt - NODES_PER_ELEMENT,
)
return space._cell_to_side_coords(args, element_index, neighbour_elem, neighbour_coords)
return cache.get_func(trace_node_coords_in_element, space.name)
@staticmethod
def _make_element_inner_weight(space: NodalFunctionSpace):
from warp.fem import cache
def trace_element_inner_weight(
args: space.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
return space.element_inner_weight(
args,
space._inner_cell_index(args, element_index),
space._inner_cell_coords(args, element_index, coords),
node_index_in_elt,
)
return cache.get_func(trace_element_inner_weight, space.name)
@staticmethod
def _make_element_outer_weight(space: NodalFunctionSpace):
from warp.fem import cache
NODES_PER_ELEMENT = space.NODES_PER_ELEMENT
def trace_element_outer_weight(
args: space.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
return space.element_outer_weight(
args,
space._outer_cell_index(args, element_index),
space._outer_cell_coords(args, element_index, coords),
node_index_in_elt - NODES_PER_ELEMENT,
)
return cache.get_func(trace_element_outer_weight, space.name)
@staticmethod
def _make_element_inner_weight_gradient(space: NodalFunctionSpace):
from warp.fem import cache
def trace_element_inner_weight_gradient(
args: space.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
return space.element_inner_weight_gradient(
args,
space._inner_cell_index(args, element_index),
space._inner_cell_coords(args, element_index, coords),
node_index_in_elt,
)
return cache.get_func(trace_element_inner_weight_gradient, space.name)
@staticmethod
def _make_element_outer_weight_gradient(space: NodalFunctionSpace):
from warp.fem import cache
NODES_PER_ELEMENT = space.NODES_PER_ELEMENT
def trace_element_outer_weight_gradient(
args: space.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
return space.element_outer_weight_gradient(
args,
space._outer_cell_index(args, element_index),
space._outer_cell_coords(args, element_index, coords),
node_index_in_elt - NODES_PER_ELEMENT,
)
return cache.get_func(trace_element_outer_weight_gradient, space.name)
def __eq__(self, other: "NodalFunctionSpaceTrace") -> bool:
return self._space == other._space
| warp-main | warp/fem/space/nodal_function_space.py |
from typing import Any, Optional
import warp as wp
from warp.fem.geometry import GeometryPartition, WholeGeometryPartition
from warp.fem.utils import compress_node_indices, _iota_kernel
from warp.fem.types import NULL_NODE_INDEX
from .function_space import FunctionSpace
wp.set_module_options({"enable_backward": False})
class SpacePartition:
class PartitionArg:
pass
def __init__(self, space: FunctionSpace, geo_partition: GeometryPartition):
self.space = space
self.geo_partition = geo_partition
def node_count(self):
"""Returns number of nodes in this partition"""
def owned_node_count(self) -> int:
"""Returns number of nodes in this partition, excluding exterior halo"""
def interior_node_count(self) -> int:
"""Returns number of interior nodes in this partition"""
def space_node_indices(self) -> wp.array:
"""Return the global function space indices for nodes in this partition"""
def partition_arg_value(self, device):
pass
def partition_node_index(args: Any, space_node_index: int):
"""Returns the index in the partition of a function space node, or -1 if it does not exist"""
def __str__(self) -> str:
return self.name
@property
def name(self) -> str:
return f"{self.__class__.__name__}"
class WholeSpacePartition(SpacePartition):
@wp.struct
class PartitionArg:
pass
def __init__(self, space: FunctionSpace):
super().__init__(space, WholeGeometryPartition(space.geometry))
self._node_indices = None
def node_count(self):
"""Returns number of nodes in this partition"""
return self.space.node_count()
def owned_node_count(self) -> int:
"""Returns number of nodes in this partition, excluding exterior halo"""
return self.space.node_count()
def interior_node_count(self) -> int:
"""Returns number of interior nodes in this partition"""
return self.space.node_count()
def space_node_indices(self):
"""Return the global function space indices for nodes in this partition"""
if self._node_indices is None:
self._node_indices = wp.empty(shape=(self.node_count(),), dtype=int)
wp.launch(kernel=_iota_kernel, dim=self._node_indices.shape, inputs=[self._node_indices, 1])
return self._node_indices
def partition_arg_value(self, device):
return WholeSpacePartition.PartitionArg()
@wp.func
def partition_node_index(args: Any, space_node_index: int):
return space_node_index
def __eq__(self, other: SpacePartition) -> bool:
return isinstance(other, SpacePartition) and self.space == other.space
class NodeCategory:
OWNED_INTERIOR = wp.constant(0)
"""Node is touched exclusively by this partition, not touched by frontier side"""
OWNED_FRONTIER = wp.constant(1)
"""Node is touched by a frontier side, but belongs to an element of this partition"""
HALO_LOCAL_SIDE = wp.constant(2)
"""Node belongs to an element of another partition, but is touched by one of our frontier side"""
HALO_OTHER_SIDE = wp.constant(3)
"""Node belongs to an element of another partition, and is not touched by one of our frontier side"""
EXTERIOR = wp.constant(4)
"""Node is never referenced by this partition"""
COUNT = 5
class NodePartition(SpacePartition):
@wp.struct
class PartitionArg:
space_to_partition: wp.array(dtype=int)
def __init__(self, space: FunctionSpace, geo_partition: GeometryPartition, with_halo: bool = True, device=None):
super().__init__(space, geo_partition=geo_partition)
self._compute_node_indices_from_sides(device, with_halo)
def node_count(self) -> int:
"""Returns number of nodes referenced by this partition, including exterior halo"""
return int(self._category_offsets[NodeCategory.HALO_OTHER_SIDE + 1])
def owned_node_count(self) -> int:
"""Returns number of nodes in this partition, excluding exterior halo"""
return int(self._category_offsets[NodeCategory.OWNED_FRONTIER + 1])
def interior_node_count(self) -> int:
"""Returns number of interior nodes in this partition"""
return int(self._category_offsets[NodeCategory.OWNED_INTERIOR + 1])
def space_node_indices(self):
"""Return the global function space indices for nodes in this partition"""
return self._node_indices
def partition_arg_value(self, device):
arg = NodePartition.PartitionArg()
arg.space_to_partition = self._space_to_partition.to(device)
return arg
@wp.func
def partition_node_index(args: PartitionArg, space_node_index: int):
return args.space_to_partition[space_node_index]
def _compute_node_indices_from_sides(self, device, with_halo: bool):
from warp.fem import cache
trace_space = self.space.trace()
NODES_PER_CELL = self.space.NODES_PER_ELEMENT
NODES_PER_SIDE = trace_space.NODES_PER_ELEMENT
def node_category_from_cells_fn(
geo_partition_arg: self.geo_partition.CellArg,
space_arg: self.space.SpaceArg,
node_mask: wp.array(dtype=int),
):
partition_cell_index = wp.tid()
cell_index = self.geo_partition.cell_index(geo_partition_arg, partition_cell_index)
for n in range(NODES_PER_CELL):
space_nidx = self.space.element_node_index(space_arg, cell_index, n)
node_mask[space_nidx] = NodeCategory.OWNED_INTERIOR
def node_category_from_owned_sides_fn(
geo_partition_arg: self.geo_partition.SideArg,
space_arg: trace_space.SpaceArg,
node_mask: wp.array(dtype=int),
):
partition_side_index = wp.tid()
side_index = self.geo_partition.side_index(geo_partition_arg, partition_side_index)
for n in range(NODES_PER_SIDE):
space_nidx = trace_space.element_node_index(space_arg, side_index, n)
if node_mask[space_nidx] == NodeCategory.EXTERIOR:
node_mask[space_nidx] = NodeCategory.HALO_LOCAL_SIDE
def node_category_from_frontier_sides_fn(
geo_partition_arg: self.geo_partition.SideArg,
space_arg: trace_space.SpaceArg,
node_mask: wp.array(dtype=int),
):
frontier_side_index = wp.tid()
side_index = self.geo_partition.frontier_side_index(geo_partition_arg, frontier_side_index)
for n in range(NODES_PER_SIDE):
space_nidx = trace_space.element_node_index(space_arg, side_index, n)
if node_mask[space_nidx] == NodeCategory.EXTERIOR:
node_mask[space_nidx] = NodeCategory.HALO_OTHER_SIDE
elif node_mask[space_nidx] == NodeCategory.OWNED_INTERIOR:
node_mask[space_nidx] = NodeCategory.OWNED_FRONTIER
node_category_from_cells_kernel = cache.get_kernel(
node_category_from_cells_fn,
suffix=f"{self.geo_partition.name}_{self.space.name}",
)
node_category_from_owned_sides_kernel = cache.get_kernel(
node_category_from_owned_sides_fn,
suffix=f"{self.geo_partition.name}_{self.space.name}",
)
node_category_from_frontier_sides_kernel = cache.get_kernel(
node_category_from_frontier_sides_fn,
suffix=f"{self.geo_partition.name}_{self.space.name}",
)
node_category = wp.empty(
shape=(self.space.node_count(),),
dtype=int,
device=device,
)
node_category.fill_(value=NodeCategory.EXTERIOR)
wp.launch(
dim=self.geo_partition.cell_count(),
kernel=node_category_from_cells_kernel,
inputs=[
self.geo_partition.cell_arg_value(device),
self.space.space_arg_value(device),
node_category,
],
device=device,
)
if with_halo:
wp.launch(
dim=self.geo_partition.side_count(),
kernel=node_category_from_owned_sides_kernel,
inputs=[
self.geo_partition.side_arg_value(device),
self.space.space_arg_value(device),
node_category,
],
device=device,
)
wp.launch(
dim=self.geo_partition.frontier_side_count(),
kernel=node_category_from_frontier_sides_kernel,
inputs=[
self.geo_partition.side_arg_value(device),
self.space.space_arg_value(device),
node_category,
],
device=device,
)
self._finalize_node_indices(node_category)
def _finalize_node_indices(self, node_category: wp.array(dtype=int)):
category_offsets, node_indices, _, __ = compress_node_indices(NodeCategory.COUNT, node_category)
self._category_offsets = category_offsets.numpy()
# Compute globla to local indices
self._space_to_partition = node_category # Reuse array storage
wp.launch(
kernel=NodePartition._scatter_partition_indices,
dim=self.space.node_count(),
device=self._space_to_partition.device,
inputs=[self.node_count(), node_indices, self._space_to_partition],
)
# Copy to shrinked-to-fit array, save on memory
self._node_indices = wp.empty(shape=(self.node_count()), dtype=int, device=node_indices.device)
wp.copy(dest=self._node_indices, src=node_indices, count=self.node_count())
@wp.kernel
def _scatter_partition_indices(
local_node_count: int,
node_indices: wp.array(dtype=int),
space_to_partition_indices: wp.array(dtype=int),
):
local_idx = wp.tid()
space_idx = node_indices[local_idx]
if local_idx < local_node_count:
space_to_partition_indices[space_idx] = local_idx
else:
space_to_partition_indices[space_idx] = NULL_NODE_INDEX
def make_space_partition(
space: FunctionSpace,
geometry_partition: Optional[GeometryPartition] = None,
with_halo: bool = True,
device=None,
) -> SpacePartition:
"""Computes the substep of nodes from a function space that touch a geometry partition
Args:
space: the function space to consider
geometry_partition: The subset of the space geometry. If not provided, use the whole geometry.
with_halo: if True, include the halo nodes (nodes from exterior frontier cells to the partition)
device: Warp device on which to perform and store computations
Returns:
the resulting space partition
"""
if geometry_partition is not None and geometry_partition.cell_count() < geometry_partition.geometry.cell_count():
return NodePartition(space, geometry_partition, with_halo=with_halo, device=device)
return WholeSpacePartition(space)
| warp-main | warp/fem/space/partition.py |
import warp as wp
import numpy as np
from warp.fem.types import ElementIndex, Coords, OUTSIDE, vec2i, vec3i
from warp.fem.geometry import Trimesh2D
from .dof_mapper import DofMapper
from .nodal_function_space import NodalFunctionSpace, NodalFunctionSpaceTrace
class Trimesh2DFunctionSpace(NodalFunctionSpace):
DIMENSION = wp.constant(2)
@wp.struct
class SpaceArg:
geo_arg: Trimesh2D.SideArg
reference_transforms: wp.array(dtype=wp.mat22f)
tri_edge_indices: wp.array2d(dtype=int)
vertex_count: int
edge_count: int
def __init__(self, mesh: Trimesh2D, dtype: type = float, dof_mapper: DofMapper = None):
super().__init__(dtype, dof_mapper)
self._mesh = mesh
self._reference_transforms: wp.array = None
self._tri_edge_indices: wp.array = None
self._compute_reference_transforms()
self._compute_tri_edge_indices()
@property
def geometry(self) -> Trimesh2D:
return self._mesh
def space_arg_value(self, device):
arg = self.SpaceArg()
arg.geo_arg = self.geometry.side_arg_value(device)
arg.reference_transforms = self._reference_transforms.to(device)
arg.tri_edge_indices = self._tri_edge_indices.to(device)
arg.vertex_count = self._mesh.vertex_count()
arg.edge_count = self._mesh.side_count()
return arg
class Trace(NodalFunctionSpaceTrace):
def __init__(self, space: NodalFunctionSpace):
super().__init__(space)
self.ORDER = space.ORDER
@wp.func
def _inner_cell_index(args: SpaceArg, side_index: ElementIndex):
return Trimesh2D.side_inner_cell_index(args.geo_arg, side_index)
@wp.func
def _outer_cell_index(args: SpaceArg, side_index: ElementIndex):
return Trimesh2D.side_outer_cell_index(args.geo_arg, side_index)
@wp.func
def _inner_cell_coords(args: SpaceArg, side_index: ElementIndex, side_coords: Coords):
tri_index = Trimesh2D.side_inner_cell_index(args.geo_arg, side_index)
return Trimesh2D.edge_to_tri_coords(args.geo_arg, side_index, tri_index, side_coords)
@wp.func
def _outer_cell_coords(args: SpaceArg, side_index: ElementIndex, side_coords: Coords):
tri_index = Trimesh2D.side_outer_cell_index(args.geo_arg, side_index)
return Trimesh2D.edge_to_tri_coords(args.geo_arg, side_index, tri_index, side_coords)
@wp.func
def _cell_to_side_coords(
args: SpaceArg,
side_index: ElementIndex,
element_index: ElementIndex,
element_coords: Coords,
):
return Trimesh2D.tri_to_edge_coords(args.geo_arg, side_index, element_index, element_coords)
def _compute_reference_transforms(self):
self._reference_transforms = wp.empty(
dtype=wp.mat22f, device=self._mesh.positions.device, shape=(self._mesh.cell_count())
)
wp.launch(
kernel=Trimesh2DFunctionSpace._compute_reference_transforms_kernel,
dim=self._reference_transforms.shape,
device=self._reference_transforms.device,
inputs=[self._mesh.tri_vertex_indices, self._mesh.positions, self._reference_transforms],
)
def _compute_tri_edge_indices(self):
self._tri_edge_indices = wp.empty(
dtype=int, device=self._mesh.tri_vertex_indices.device, shape=(self._mesh.cell_count(), 3)
)
wp.launch(
kernel=Trimesh2DFunctionSpace._compute_tri_edge_indices_kernel,
dim=self._mesh._edge_tri_indices.shape,
device=self._mesh.tri_vertex_indices.device,
inputs=[
self._mesh._edge_tri_indices,
self._mesh._edge_vertex_indices,
self._mesh.tri_vertex_indices,
self._tri_edge_indices,
],
)
@wp.kernel
def _compute_reference_transforms_kernel(
tri_vertex_indices: wp.array2d(dtype=int),
positions: wp.array(dtype=wp.vec2f),
transforms: wp.array(dtype=wp.mat22f),
):
t = wp.tid()
p0 = positions[tri_vertex_indices[t, 0]]
p1 = positions[tri_vertex_indices[t, 1]]
p2 = positions[tri_vertex_indices[t, 2]]
e1 = p1 - p0
e2 = p2 - p0
mat = wp.mat22(e1, e2)
transforms[t] = wp.transpose(wp.inverse(mat))
@wp.func
def _find_edge_index_in_tri(
edge_vtx: vec2i,
tri_vtx: vec3i,
):
for k in range(2):
if (edge_vtx[0] == tri_vtx[k] and edge_vtx[1] == tri_vtx[k + 1]) or (
edge_vtx[1] == tri_vtx[k] and edge_vtx[0] == tri_vtx[k + 1]
):
return k
return 2
@wp.kernel
def _compute_tri_edge_indices_kernel(
edge_tri_indices: wp.array(dtype=vec2i),
edge_vertex_indices: wp.array(dtype=vec2i),
tri_vertex_indices: wp.array2d(dtype=int),
tri_edge_indices: wp.array2d(dtype=int),
):
e = wp.tid()
edge_vtx = edge_vertex_indices[e]
edge_tris = edge_tri_indices[e]
t0 = edge_tris[0]
t0_vtx = vec3i(tri_vertex_indices[t0, 0], tri_vertex_indices[t0, 1], tri_vertex_indices[t0, 2])
t0_edge = Trimesh2DFunctionSpace._find_edge_index_in_tri(edge_vtx, t0_vtx)
tri_edge_indices[t0, t0_edge] = e
t1 = edge_tris[1]
if t1 != t0:
t1_vtx = vec3i(tri_vertex_indices[t1, 0], tri_vertex_indices[t1, 1], tri_vertex_indices[t1, 2])
t1_edge = Trimesh2DFunctionSpace._find_edge_index_in_tri(edge_vtx, t1_vtx)
tri_edge_indices[t1, t1_edge] = e
class Trimesh2DPiecewiseConstantSpace(Trimesh2DFunctionSpace):
ORDER = wp.constant(0)
NODES_PER_ELEMENT = wp.constant(1)
def __init__(self, grid: Trimesh2D, dtype: type = float, dof_mapper: DofMapper = None):
super().__init__(grid, dtype, dof_mapper)
self.element_outer_weight = self.element_inner_weight
self.element_outer_weight_gradient = self.element_inner_weight_gradient
def node_count(self) -> int:
return self._mesh.cell_count()
def node_positions(self):
vtx_pos = self._mesh.positions.numpy()
tri_vtx = self._mesh.tri_vertex_indices.numpy()
tri_pos = vtx_pos[tri_vtx]
centers = tri_pos.sum(axis=1) / 3.0
return centers[:,0], centers[:,1]
@wp.func
def element_node_index(
args: Trimesh2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return element_index
@wp.func
def node_coords_in_element(
args: Trimesh2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
if node_index_in_elt == 0:
return Coords(1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0)
return Coords(OUTSIDE)
@wp.func
def node_quadrature_weight(
args: Trimesh2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return 1.0
@wp.func
def element_inner_weight(
args: Trimesh2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
if node_index_in_elt == 0:
return 1.0
return 0.0
@wp.func
def element_inner_weight_gradient(
args: Trimesh2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
return wp.vec2(0.0)
class Trace(Trimesh2DFunctionSpace.Trace):
NODES_PER_ELEMENT = wp.constant(2)
ORDER = wp.constant(0)
def __init__(self, space: "Trimesh2DPiecewiseConstantSpace"):
super().__init__(space)
self.element_node_index = self._make_element_node_index(space)
self.element_inner_weight = self._make_element_inner_weight(space)
self.element_inner_weight_gradient = self._make_element_inner_weight_gradient(space)
self.element_outer_weight = self._make_element_outer_weight(space)
self.element_outer_weight_gradient = self._make_element_outer_weight_gradient(space)
@wp.func
def node_coords_in_element(
args: Trimesh2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_element: int,
):
if node_index_in_element == 0:
return Coords(0.5, 0.0, 0.0)
elif node_index_in_element == 1:
return Coords(0.5, 0.0, 0.0)
return Coords(OUTSIDE)
@wp.func
def node_quadrature_weight(
args: Trimesh2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return 1.0
def trace(self):
return Trimesh2DPiecewiseConstantSpace.Trace(self)
def _triangle_node_index(tx: int, ty: int, degree: int):
VERTEX_NODE_COUNT = 3
SIDE_INTERIOR_NODE_COUNT = degree - 1
# Index in similar order to e.g. VTK
# First vertices, then edge (counterclokwise) then interior points (recursively)
if tx == 0:
if ty == 0:
return 0
elif ty == degree:
return 2
else:
edge_index = 2
return VERTEX_NODE_COUNT + SIDE_INTERIOR_NODE_COUNT * edge_index + (SIDE_INTERIOR_NODE_COUNT - ty)
elif ty == 0:
if tx == degree:
return 1
else:
edge_index = 0
return VERTEX_NODE_COUNT + SIDE_INTERIOR_NODE_COUNT * edge_index + tx - 1
elif tx + ty == degree:
edge_index = 1
return VERTEX_NODE_COUNT + SIDE_INTERIOR_NODE_COUNT * edge_index + ty - 1
vertex_edge_node_count = 3 * degree
return vertex_edge_node_count + _triangle_node_index(tx - 1, ty - 1, degree - 2)
class Trimesh2DPolynomialShapeFunctions:
INVALID = wp.constant(-1)
VERTEX = wp.constant(0)
EDGE = wp.constant(1)
INTERIOR = wp.constant(2)
def __init__(self, degree: int):
self.ORDER = wp.constant(degree)
self.NODES_PER_ELEMENT = wp.constant((degree + 1) * (degree + 2) // 2)
self.NODES_PER_SIDE = wp.constant(degree + 1)
triangle_coords = np.empty((self.NODES_PER_ELEMENT, 2), dtype=int)
for tx in range(degree + 1):
for ty in range(degree + 1 - tx):
index = _triangle_node_index(tx, ty, degree)
triangle_coords[index] = [tx, ty]
CoordTypeVec = wp.mat(dtype=int, shape=(self.NODES_PER_ELEMENT, 2))
self.NODE_TRIANGLE_COORDS = wp.constant(CoordTypeVec(triangle_coords))
self.node_type_and_type_index = self._get_node_type_and_type_index()
self._node_triangle_coordinates = self._get_node_triangle_coordinates()
@property
def name(self) -> str:
return f"{self.ORDER}"
def _get_node_triangle_coordinates(self):
NODE_TRIANGLE_COORDS = self.NODE_TRIANGLE_COORDS
def node_triangle_coordinates(
node_index_in_elt: int,
):
return vec2i(NODE_TRIANGLE_COORDS[node_index_in_elt, 0], NODE_TRIANGLE_COORDS[node_index_in_elt, 1])
from warp.fem import cache
return cache.get_func(node_triangle_coordinates, self.name)
def _get_node_type_and_type_index(self):
ORDER = self.ORDER
NODES_PER_ELEMENT = self.NODES_PER_ELEMENT
def node_type_and_index(
node_index_in_elt: int,
):
if node_index_in_elt < 0 or node_index_in_elt >= NODES_PER_ELEMENT:
return Trimesh2DPolynomialShapeFunctions.INVALID, Trimesh2DPolynomialShapeFunctions.INVALID
if node_index_in_elt < 3:
return Trimesh2DPolynomialShapeFunctions.VERTEX, node_index_in_elt
if node_index_in_elt < 3 * ORDER:
return Trimesh2DPolynomialShapeFunctions.EDGE, (node_index_in_elt - 3)
return Trimesh2DPolynomialShapeFunctions.INTERIOR, (node_index_in_elt - 3 * ORDER)
from warp.fem import cache
return cache.get_func(node_type_and_index, self.name)
def make_node_coords_in_element(self):
ORDER = self.ORDER
def node_coords_in_element(
args: Trimesh2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
tri_coords = self._node_triangle_coordinates(node_index_in_elt)
cx = float(tri_coords[0]) / float(ORDER)
cy = float(tri_coords[1]) / float(ORDER)
return Coords(1.0 - cx - cy, cx, cy)
from warp.fem import cache
return cache.get_func(node_coords_in_element, self.name)
def make_node_quadrature_weight(self):
ORDER = self.ORDER
def node_uniform_quadrature_weight(
args: Trimesh2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
node_type, type_index = self.node_type_and_type_index(node_index_in_elt)
base_weight = 1.0 / float(3 * ORDER * ORDER)
if node_type == Trimesh2DPolynomialShapeFunctions.VERTEX:
return base_weight
if node_type == Trimesh2DPolynomialShapeFunctions.EDGE:
return 2.0 * base_weight
return 4.0 * base_weight
def node_linear_quadrature_weight(
args: Trimesh2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return 1.0 / 3.0
from warp.fem import cache
if ORDER == 1:
return cache.get_func(node_linear_quadrature_weight, self.name)
return cache.get_func(node_uniform_quadrature_weight, self.name)
def make_trace_node_quadrature_weight(self):
ORDER = self.ORDER
NODES_PER_ELEMENT = self.NODES_PER_ELEMENT
def trace_uniform_node_quadrature_weight(
args: Trimesh2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
if node_index_in_elt >= NODES_PER_ELEMENT:
node_index_in_cell = node_index_in_elt - NODES_PER_ELEMENT
else:
node_index_in_cell = node_index_in_elt
# We're either on a side interior or at a vertex
node_type, type_index = self.node_type_and_type_index(node_index_in_cell)
base_weight = 1.0 / float(ORDER)
return wp.select(node_type == Trimesh2DPolynomialShapeFunctions.VERTEX, base_weight, 0.5 * base_weight)
def trace_linear_node_quadrature_weight(
args: Trimesh2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return 0.5
from warp.fem import cache
if ORDER == 1:
return cache.get_func(trace_linear_node_quadrature_weight, self.name)
return cache.get_func(trace_uniform_node_quadrature_weight, self.name)
def make_element_inner_weight(self):
ORDER = self.ORDER
def element_inner_weight_linear(
args: Trimesh2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
if node_index_in_elt < 0 or node_index_in_elt >= 3:
return 0.0
return coords[node_index_in_elt]
def element_inner_weight_quadratic(
args: Trimesh2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
node_type, type_index = self.node_type_and_type_index(node_index_in_elt)
if node_type == Trimesh2DPolynomialShapeFunctions.VERTEX:
# Vertex
return coords[type_index] * (2.0 * coords[type_index] - 1.0)
elif node_type == Trimesh2DPolynomialShapeFunctions.EDGE:
# Edge
c1 = type_index
c2 = (type_index + 1) % 3
return 4.0 * coords[c1] * coords[c2]
return 0.0
def element_inner_weight_cubic(
args: Trimesh2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
node_type, type_index = self.node_type_and_type_index(node_index_in_elt)
if node_type == Trimesh2DPolynomialShapeFunctions.VERTEX:
# Vertex
return 0.5 * coords[type_index] * (3.0 * coords[type_index] - 1.0) * (3.0 * coords[type_index] - 2.0)
elif node_type == Trimesh2DPolynomialShapeFunctions.EDGE:
# Edge
edge = type_index // 2
k = type_index - 2 * edge
c1 = (edge + k) % 3
c2 = (edge + 1 - k) % 3
return 4.5 * coords[c1] * coords[c2] * (3.0 * coords[c1] - 1.0)
elif node_type == Trimesh2DPolynomialShapeFunctions.INTERIOR:
# Interior
return 27.0 * coords[0] * coords[1] * coords[2]
return 0.0
from warp.fem import cache
if ORDER == 1:
return cache.get_func(element_inner_weight_linear, self.name)
elif ORDER == 2:
return cache.get_func(element_inner_weight_quadratic, self.name)
elif ORDER == 3:
return cache.get_func(element_inner_weight_cubic, self.name)
return None
def make_element_inner_weight_gradient(self):
ORDER = self.ORDER
def element_inner_weight_gradient_linear(
args: Trimesh2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
if node_index_in_elt < 0 or node_index_in_elt >= 3:
return wp.vec2(0.0)
dw_dc = wp.vec3(0.0)
dw_dc[node_index_in_elt] = 1.0
dw_du = wp.vec2(dw_dc[1] - dw_dc[0], dw_dc[2] - dw_dc[0])
return args.reference_transforms[element_index] * dw_du
def element_inner_weight_gradient_quadratic(
args: Trimesh2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
node_type, type_index = self.node_type_and_type_index(node_index_in_elt)
dw_dc = wp.vec3(0.0)
if node_type == Trimesh2DPolynomialShapeFunctions.VERTEX:
# Vertex
dw_dc[type_index] = 4.0 * coords[type_index] - 1.0
elif node_type == Trimesh2DPolynomialShapeFunctions.EDGE:
# Edge
c1 = type_index
c2 = (type_index + 1) % 3
dw_dc[c1] = 4.0 * coords[c2]
dw_dc[c2] = 4.0 * coords[c1]
dw_du = wp.vec2(dw_dc[1] - dw_dc[0], dw_dc[2] - dw_dc[0])
return args.reference_transforms[element_index] * dw_du
def element_inner_weight_gradient_cubic(
args: Trimesh2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
node_type, type_index = self.node_type_and_type_index(node_index_in_elt)
dw_dc = wp.vec3(0.0)
if node_type == Trimesh2DPolynomialShapeFunctions.VERTEX:
# Vertex
dw_dc[type_index] = (
0.5 * 27.0 * coords[type_index] * coords[type_index] - 9.0 * coords[type_index] + 1.0
)
elif node_type == Trimesh2DPolynomialShapeFunctions.EDGE:
# Edge
edge = type_index // 2
k = type_index - 2 * edge
c1 = (edge + k) % 3
c2 = (edge + 1 - k) % 3
dw_dc[c1] = 4.5 * coords[c2] * (6.0 * coords[c1] - 1.0)
dw_dc[c2] = 4.5 * coords[c1] * (3.0 * coords[c1] - 1.0)
elif node_type == Trimesh2DPolynomialShapeFunctions.INTERIOR:
# Interior
dw_dc = wp.vec3(
27.0 * coords[1] * coords[2], 27.0 * coords[2] * coords[0], 27.0 * coords[0] * coords[1]
)
dw_du = wp.vec2(dw_dc[1] - dw_dc[0], dw_dc[2] - dw_dc[0])
return args.reference_transforms[element_index] * dw_du
from warp.fem import cache
if ORDER == 1:
return cache.get_func(element_inner_weight_gradient_linear, self.name)
elif ORDER == 2:
return cache.get_func(element_inner_weight_gradient_quadratic, self.name)
elif ORDER == 3:
return cache.get_func(element_inner_weight_gradient_cubic, self.name)
return None
@staticmethod
def node_positions(space):
if space.ORDER == 1:
return np.transpose(space._mesh.positions.numpy())
NODES_PER_ELEMENT = space.NODES_PER_ELEMENT
def fill_node_positions_fn(
space_arg: space.SpaceArg,
node_positions: wp.array(dtype=wp.vec2),
):
element_index = wp.tid()
tri_idx = space_arg.geo_arg.tri_vertex_indices[element_index]
p0 = space_arg.geo_arg.positions[tri_idx[0]]
p1 = space_arg.geo_arg.positions[tri_idx[1]]
p2 = space_arg.geo_arg.positions[tri_idx[2]]
for n in range(NODES_PER_ELEMENT):
node_index = space.element_node_index(space_arg, element_index, n)
coords = space.node_coords_in_element(space_arg, element_index, n)
pos = coords[0] * p0 + coords[1] * p1 + coords[2] * p2
node_positions[node_index] = pos
from warp.fem import cache
fill_node_positions = cache.get_kernel(
fill_node_positions_fn,
suffix=space.name,
)
device = space._mesh.tri_vertex_indices.device
node_positions = wp.empty(
shape=space.node_count(),
dtype=wp.vec2,
device=device,
)
wp.launch(
dim=space._mesh.cell_count(),
kernel=fill_node_positions,
inputs=[
space.space_arg_value(device),
node_positions,
],
device=device,
)
return np.transpose(node_positions.numpy())
@staticmethod
def node_triangulation(space):
if space.ORDER == 1:
return space._mesh.tri_vertex_indices.numpy()
NODES_PER_ELEMENT = space.NODES_PER_ELEMENT
def fill_element_node_indices_fn(
space_arg: space.SpaceArg,
element_node_indices: wp.array2d(dtype=int),
):
element_index = wp.tid()
for n in range(NODES_PER_ELEMENT):
element_node_indices[element_index, n] = space.element_node_index(space_arg, element_index, n)
from warp.fem import cache
fill_element_node_indices = cache.get_kernel(
fill_element_node_indices_fn,
suffix=space.name,
)
device = space._mesh.tri_vertex_indices.device
element_node_indices = wp.empty(
shape=(space._mesh.cell_count(), NODES_PER_ELEMENT),
dtype=int,
device=device,
)
wp.launch(
dim=element_node_indices.shape[0],
kernel=fill_element_node_indices,
inputs=[
space.space_arg_value(device),
element_node_indices,
],
device=device,
)
element_node_indices = element_node_indices.numpy()
if space.ORDER == 2:
element_triangles = [[0, 3, 5], [3, 1, 4], [2, 5, 4], [3, 4, 5]]
elif space.ORDER == 3:
element_triangles = [
[0, 3, 8],
[3, 4, 9],
[4, 1, 5],
[8, 3, 9],
[4, 5, 9],
[8, 9, 7],
[9, 5, 6],
[6, 7, 9],
[7, 6, 2],
]
tri_indices = element_node_indices[:, element_triangles].reshape(-1, 3)
return tri_indices
class Trimesh2DPolynomialSpace(Trimesh2DFunctionSpace):
def __init__(self, grid: Trimesh2D, degree: int, dtype: type = float, dof_mapper: DofMapper = None):
super().__init__(grid, dtype, dof_mapper)
self._shape = Trimesh2DPolynomialShapeFunctions(degree)
self.ORDER = self._shape.ORDER
self.NODES_PER_ELEMENT = self._shape.NODES_PER_ELEMENT
self.element_node_index = self._make_element_node_index()
self.node_coords_in_element = self._shape.make_node_coords_in_element()
self.node_quadrature_weight = self._shape.make_node_quadrature_weight()
self.element_inner_weight = self._shape.make_element_inner_weight()
self.element_inner_weight_gradient = self._shape.make_element_inner_weight_gradient()
self.element_outer_weight = self.element_inner_weight
self.element_outer_weight_gradient = self.element_inner_weight_gradient
def _make_element_node_index(self):
INTERIOR_NODES_PER_SIDE = wp.constant(max(0, self.ORDER - 1))
INTERIOR_NODES_PER_CELL = wp.constant(max(0, self.ORDER - 2) * max(0, self.ORDER - 1) // 2)
def element_node_index(
args: Trimesh2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
node_type, type_index = self._shape.node_type_and_type_index(node_index_in_elt)
if node_type == Trimesh2DPolynomialShapeFunctions.VERTEX:
return args.geo_arg.tri_vertex_indices[element_index][type_index]
global_offset = args.vertex_count
if node_type == Trimesh2DPolynomialShapeFunctions.EDGE:
edge = type_index // INTERIOR_NODES_PER_SIDE
edge_node = type_index - INTERIOR_NODES_PER_SIDE * edge
global_edge_index = args.tri_edge_indices[element_index][edge]
if (
args.geo_arg.edge_vertex_indices[global_edge_index][0]
!= args.geo_arg.tri_vertex_indices[element_index][edge]
):
edge_node = INTERIOR_NODES_PER_SIDE - 1 - edge_node
return global_offset + INTERIOR_NODES_PER_SIDE * global_edge_index + edge_node
global_offset += INTERIOR_NODES_PER_SIDE * args.edge_count
return global_offset + INTERIOR_NODES_PER_CELL * element_index + type_index
from warp.fem import cache
return cache.get_func(element_node_index, self.name)
def node_count(self) -> int:
INTERIOR_NODES_PER_SIDE = wp.constant(max(0, self.ORDER - 1))
INTERIOR_NODES_PER_CELL = wp.constant(max(0, self.ORDER - 2) * max(0, self.ORDER - 1) // 2)
return (
self._mesh.vertex_count()
+ self._mesh.side_count() * INTERIOR_NODES_PER_SIDE
+ self._mesh.cell_count() * INTERIOR_NODES_PER_CELL
)
def node_positions(self):
return Trimesh2DPolynomialShapeFunctions.node_positions(self)
def node_triangulation(self):
return Trimesh2DPolynomialShapeFunctions.node_triangulation(self)
class Trace(Trimesh2DFunctionSpace.Trace):
NODES_PER_ELEMENT = wp.constant(2)
ORDER = wp.constant(0)
def __init__(self, space: "Trimesh2DPolynomialSpace"):
super().__init__(space)
self.element_node_index = self._make_element_node_index(space)
self.node_coords_in_element = self._make_node_coords_in_element(space)
self.node_quadrature_weight = space._shape.make_trace_node_quadrature_weight()
self.element_inner_weight = self._make_element_inner_weight(space)
self.element_inner_weight_gradient = self._make_element_inner_weight_gradient(space)
self.element_outer_weight = self._make_element_outer_weight(space)
self.element_outer_weight_gradient = self._make_element_outer_weight_gradient(space)
def trace(self):
return Trimesh2DPolynomialSpace.Trace(self)
class Trimesh2DDGPolynomialSpace(Trimesh2DFunctionSpace):
def __init__(
self,
mesh: Trimesh2D,
degree: int,
dtype: type = float,
dof_mapper: DofMapper = None,
):
super().__init__(mesh, dtype, dof_mapper)
self._shape = Trimesh2DPolynomialShapeFunctions(degree)
self.ORDER = self._shape.ORDER
self.NODES_PER_ELEMENT = self._shape.NODES_PER_ELEMENT
self.element_node_index = self._make_element_node_index()
self.node_coords_in_element = self._shape.make_node_coords_in_element()
self.node_quadrature_weight = self._shape.make_node_quadrature_weight()
self.element_inner_weight = self._shape.make_element_inner_weight()
self.element_inner_weight_gradient = self._shape.make_element_inner_weight_gradient()
self.element_outer_weight = self.element_inner_weight
self.element_outer_weight_gradient = self.element_inner_weight_gradient
def node_count(self) -> int:
return self._mesh.cell_count() * self.NODES_PER_ELEMENT
def node_positions(self):
return Trimesh2DPolynomialShapeFunctions.node_positions(self)
def node_triangulation(self):
return Trimesh2DPolynomialShapeFunctions.node_triangulation(self)
def _make_element_node_index(self):
NODES_PER_ELEMENT = self.NODES_PER_ELEMENT
def element_node_index(
args: Trimesh2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return element_index * NODES_PER_ELEMENT + node_index_in_elt
from warp.fem import cache
return cache.get_func(element_node_index, f"{self.name}_{self.ORDER}")
class Trace(Trimesh2DPolynomialSpace.Trace):
def __init__(self, space: "Trimesh2DDGPolynomialSpace"):
super().__init__(space)
def trace(self):
return Trimesh2DDGPolynomialSpace.Trace(self)
| warp-main | warp/fem/space/trimesh_2d_function_space.py |
from typing import Optional
import warp.fem.domain
import warp.fem.geometry
import warp.fem.polynomial
from .function_space import FunctionSpace
from .nodal_function_space import NodalFunctionSpace
from .grid_2d_function_space import (
GridPiecewiseConstantSpace,
GridBipolynomialSpace,
GridDGBipolynomialSpace,
)
from .grid_3d_function_space import (
GridTripolynomialSpace,
GridDGTripolynomialSpace,
Grid3DPiecewiseConstantSpace,
)
from .trimesh_2d_function_space import (
Trimesh2DPiecewiseConstantSpace,
Trimesh2DPolynomialSpace,
Trimesh2DDGPolynomialSpace,
)
from .tetmesh_function_space import TetmeshPiecewiseConstantSpace, TetmeshPolynomialSpace, TetmeshDGPolynomialSpace
from .partition import SpacePartition, make_space_partition
from .restriction import SpaceRestriction
from .dof_mapper import DofMapper, IdentityMapper, SymmetricTensorMapper
def make_space_restriction(
space: FunctionSpace,
space_partition: Optional[SpacePartition] = None,
domain: Optional[warp.fem.domain.GeometryDomain] = None,
device=None,
) -> SpaceRestriction:
"""
Restricts a function space to a Domain, i.e. a subset of its elements.
Args:
space: the space to be restricted
space_partition: if provided, the subset of nodes from ``space`` to consider
domain: the domain to restrict the space to, defaults to all cells of the space geometry or partition.
"""
if domain is None:
if space_partition is None:
domain = warp.fem.domain.Cells(geometry=space.geometry)
else:
domain = warp.fem.domain.Cells(geometry=space_partition.geo_partition)
return SpaceRestriction(space=space, space_partition=space_partition, domain=domain, device=device)
def make_polynomial_space(
geo: warp.fem.geometry.Geometry,
dtype: type = float,
dof_mapper: Optional[DofMapper] = None,
degree: int = 1,
discontinuous: bool = False,
family: Optional[warp.fem.polynomial.Polynomial] = None,
) -> FunctionSpace:
"""
Equip elements of a geometry with a Lagrange polynomial function space
Args:
geo: the Geometry on which to build the space
dtype: value type the function space. If ``dof_mapper`` is provided, the value type from the DofMapper will be used instead.
dof_mapper: mapping from node degrees of freedom to function values, defaults to Identity. Useful for reduced coordinates, e.g. :py:class:`SymmetricTensorMapper` maps 2x2 (resp 3x3) symmetric tensors to 3 (resp 6) degrees of freedom.
degree: polynomial degree of the per-element shape functions
discontinuous: if True, use Discontinuous Galerkin shape functions. Discontinuous is implied if degree is 0, i.e, piecewise-constant shape functions.
family: Polynomial family used to generate the shape function basis. If not provided, a reasonable basis is chosen.
Returns:
the constructed function space
"""
if isinstance(geo, warp.fem.geometry.Grid2D):
if degree == 0:
return GridPiecewiseConstantSpace(geo, dtype=dtype, dof_mapper=dof_mapper)
if discontinuous:
return GridDGBipolynomialSpace(geo, dtype=dtype, dof_mapper=dof_mapper, degree=degree, family=family)
else:
return GridBipolynomialSpace(geo, dtype=dtype, dof_mapper=dof_mapper, degree=degree, family=family)
if isinstance(geo, warp.fem.geometry.Grid3D):
if degree == 0:
return Grid3DPiecewiseConstantSpace(geo, dtype=dtype, dof_mapper=dof_mapper)
if discontinuous:
return GridDGTripolynomialSpace(geo, dtype=dtype, dof_mapper=dof_mapper, degree=degree, family=family)
else:
return GridTripolynomialSpace(geo, dtype=dtype, dof_mapper=dof_mapper, degree=degree, family=family)
if isinstance(geo, warp.fem.geometry.Trimesh2D):
if degree == 0:
return Trimesh2DPiecewiseConstantSpace(geo, dtype=dtype, dof_mapper=dof_mapper)
if discontinuous:
return Trimesh2DDGPolynomialSpace(geo, dtype=dtype, dof_mapper=dof_mapper, degree=degree)
else:
return Trimesh2DPolynomialSpace(geo, dtype=dtype, dof_mapper=dof_mapper, degree=degree)
if isinstance(geo, warp.fem.geometry.Tetmesh):
if degree == 0:
return TetmeshPiecewiseConstantSpace(geo, dtype=dtype, dof_mapper=dof_mapper)
if discontinuous:
return TetmeshDGPolynomialSpace(geo, dtype=dtype, dof_mapper=dof_mapper, degree=degree)
else:
return TetmeshPolynomialSpace(geo, dtype=dtype, dof_mapper=dof_mapper, degree=degree)
raise NotImplementedError
| warp-main | warp/fem/space/__init__.py |
from typing import Any
from enum import Enum
import math
import warp as wp
import warp.types
from warp.fem.types import vec6
_SQRT_2 = wp.constant(math.sqrt(2.0))
_SQRT_3 = wp.constant(math.sqrt(3.0))
_SQRT_1_2 = wp.constant(math.sqrt(1.0 / 2.0))
_SQRT_1_3 = wp.constant(math.sqrt(1.0 / 3.0))
class DofMapper:
"""Base class from mapping node degrees of freedom to function values"""
value_dtype: type
dof_dtype: type
DOF_SIZE: int
@wp.func
def dof_to_value(dof: Any):
raise NotImplementedError
@wp.func
def value_to_dof(val: Any):
raise NotImplementedError
def __str__(self):
return f"{self.value_dtype.__name__}_{self.DOF_SIZE}"
class IdentityMapper(DofMapper):
"""Identity mapper"""
def __init__(self, dtype: type):
if dtype == float:
dtype = wp.float32
self.value_dtype = dtype
self.dof_dtype = dtype
size = warp.types.type_length(dtype)
self.DOF_SIZE = wp.constant(size)
@wp.func
def dof_to_value(dof: Any):
return dof
@wp.func
def value_to_dof(val: Any):
return val
class SymmetricTensorMapper(DofMapper):
"""Orthonormal isomorphism from R^{n (n+1)} to nxn symmetric tensors,
using usual L2 norm for vectors and half Frobenius norm, (tau : tau)/2 for tensors.
"""
class Mapping(Enum):
VOIGT = 0
"""Voigt ordering of vector coefficients:
first the three diagonal terms, then off-diagonal coefficients"""
DB16 = 1
"""Ordering that also separates normal from tangential coefficients:
first trace, then other diagonal terms, then off-diagonal coefficients.
See [Daviet and Bertails-Descoubes 2016]"""
def __init__(self, dtype: type, mapping: Mapping = Mapping.VOIGT):
self.value_dtype = dtype
self.mapping = mapping
if dtype == wp.mat22:
self.dof_dtype = wp.vec3
self.DOF_SIZE = wp.constant(3)
if mapping == SymmetricTensorMapper.Mapping.VOIGT:
self.dof_to_value = SymmetricTensorMapper.dof_to_value_2d_voigt
self.value_to_dof = SymmetricTensorMapper.value_to_dof_2d_voigt
else:
self.dof_to_value = SymmetricTensorMapper.dof_to_value_2d
self.value_to_dof = SymmetricTensorMapper.value_to_dof_2d
elif dtype == wp.mat33:
self.dof_dtype = vec6
self.DOF_SIZE = wp.constant(6)
if mapping == SymmetricTensorMapper.Mapping.VOIGT:
self.dof_to_value = SymmetricTensorMapper.dof_to_value_3d_voigt
self.value_to_dof = SymmetricTensorMapper.value_to_dof_3d_voigt
else:
self.dof_to_value = SymmetricTensorMapper.dof_to_value_3d
self.value_to_dof = SymmetricTensorMapper.value_to_dof_3d
else:
raise ValueError("Unsupported value dtype: ", dtype)
def __str__(self):
return f"{self.mapping}_{self.DOF_SIZE}"
@wp.func
def dof_to_value_2d(dof: wp.vec3):
a = dof[0]
b = dof[1]
c = dof[2]
return wp.mat22(a + b, c, c, a - b)
@wp.func
def value_to_dof_2d(val: wp.mat22):
a = 0.5 * (val[0, 0] + val[1, 1])
b = 0.5 * (val[0, 0] - val[1, 1])
c = 0.5 * (val[0, 1] + val[1, 0])
return wp.vec3(a, b, c)
@wp.func
def dof_to_value_2d_voigt(dof: wp.vec3):
a = _SQRT_2 * dof[0]
b = _SQRT_2 * dof[1]
c = dof[2]
return wp.mat22(a, c, c, b)
@wp.func
def value_to_dof_2d_voigt(val: wp.mat22):
a = _SQRT_1_2 * val[0, 0]
b = _SQRT_1_2 * val[1, 1]
c = 0.5 * (val[0, 1] + val[1, 0])
return wp.vec3(a, b, c)
@wp.func
def dof_to_value_3d(dof: vec6):
a = dof[0] * _SQRT_2 * _SQRT_1_3
b = dof[1]
c = dof[2] * _SQRT_1_3
d = dof[3]
e = dof[4]
f = dof[5]
return wp.mat33(
a + b - c,
f,
e,
f,
a - b - c,
d,
e,
d,
a + 2.0 * c,
)
@wp.func
def value_to_dof_3d(val: wp.mat33):
a = (val[0, 0] + val[1, 1] + val[2, 2]) * _SQRT_1_3 * _SQRT_1_2
b = 0.5 * (val[0, 0] - val[1, 1])
c = 0.5 * (val[2, 2] - (val[0, 0] + val[1, 1] + val[2, 2]) / 3.0) * _SQRT_3
d = 0.5 * (val[2, 1] + val[1, 2])
e = 0.5 * (val[0, 2] + val[2, 0])
f = 0.5 * (val[1, 0] + val[0, 1])
return vec6(a, b, c, d, e, f)
@wp.func
def dof_to_value_3d_voigt(dof: vec6):
a = _SQRT_2 * dof[0]
b = _SQRT_2 * dof[1]
c = _SQRT_2 * dof[2]
d = dof[3]
e = dof[4]
f = dof[5]
return wp.mat33(
a,
f,
e,
f,
b,
d,
e,
d,
c,
)
@wp.func
def value_to_dof_3d_voigt(val: wp.mat33):
a = _SQRT_1_2 * val[0, 0]
b = _SQRT_1_2 * val[1, 1]
c = _SQRT_1_2 * val[2, 2]
d = 0.5 * (val[2, 1] + val[1, 2])
e = 0.5 * (val[0, 2] + val[2, 0])
f = 0.5 * (val[1, 0] + val[0, 1])
return vec6(a, b, c, d, e, f)
| warp-main | warp/fem/space/dof_mapper.py |
import warp as wp
from warp.fem.domain import GeometryDomain
from warp.fem.types import NodeElementIndex
from warp.fem.utils import compress_node_indices
from .function_space import FunctionSpace
from .partition import SpacePartition
wp.set_module_options({"enable_backward": False})
class SpaceRestriction:
"""Restriction of a space to a given GeometryDomain"""
def __init__(
self,
space: FunctionSpace,
domain: GeometryDomain,
space_partition: SpacePartition,
device=None,
):
if domain.dimension() == space.DIMENSION - 1:
space = space.trace()
if domain.dimension() != space.DIMENSION:
raise ValueError("Incompatible space and domain dimensions")
self.space = space
self.space_partition = space_partition
self.domain = domain
self._compute_node_element_indices(device=device)
def _compute_node_element_indices(self, device):
from warp.fem import cache
NODES_PER_ELEMENT = self.space.NODES_PER_ELEMENT
def fill_element_node_indices_fn(
domain_index_arg: self.domain.ElementIndexArg,
space_arg: self.space.SpaceArg,
partition_arg: self.space_partition.PartitionArg,
element_node_indices: wp.array2d(dtype=int),
):
domain_element_index = wp.tid()
element_index = self.domain.element_index(domain_index_arg, domain_element_index)
for n in range(NODES_PER_ELEMENT):
space_nidx = self.space.element_node_index(space_arg, element_index, n)
partition_nidx = self.space_partition.partition_node_index(partition_arg, space_nidx)
element_node_indices[domain_element_index, n] = partition_nidx
fill_element_node_indices = cache.get_kernel(
fill_element_node_indices_fn,
suffix=f"{self.domain.name}_{self.space.name}_{self.space_partition.name}",
)
element_node_indices = wp.empty(
shape=(self.domain.element_count(), NODES_PER_ELEMENT),
dtype=int,
device=device,
)
wp.launch(
dim=element_node_indices.shape[0],
kernel=fill_element_node_indices,
inputs=[
self.domain.element_index_arg_value(device),
self.space.space_arg_value(device),
self.space_partition.partition_arg_value(device),
element_node_indices,
],
device=device,
)
# Build compressed map from node to element indices
flattened_node_indices = element_node_indices.reshape(element_node_indices.size)
(
self._dof_partition_element_offsets,
node_array_indices,
self._node_count,
self._dof_partition_indices,
) = compress_node_indices(self.space_partition.node_count(), flattened_node_indices)
# Extract element index and index in element
self._dof_element_indices = wp.empty_like(flattened_node_indices)
self._dof_indices_in_element = wp.empty_like(flattened_node_indices)
wp.launch(
kernel=SpaceRestriction._split_vertex_element_index,
dim=flattened_node_indices.shape,
inputs=[NODES_PER_ELEMENT, node_array_indices, self._dof_element_indices, self._dof_indices_in_element],
device=flattened_node_indices.device,
)
def node_count(self):
return self._node_count
def partition_element_offsets(self):
return self._dof_partition_element_offsets
def node_partition_indices(self):
return self._dof_partition_indices
def total_node_element_count(self):
return self._dof_element_indices.size
@wp.struct
class NodeArg:
dof_element_offsets: wp.array(dtype=int)
dof_element_indices: wp.array(dtype=int)
dof_partition_indices: wp.array(dtype=int)
dof_indices_in_element: wp.array(dtype=int)
def node_arg(self, device):
arg = SpaceRestriction.NodeArg()
arg.dof_element_offsets = self._dof_partition_element_offsets.to(device)
arg.dof_element_indices = self._dof_element_indices.to(device)
arg.dof_partition_indices = self._dof_partition_indices.to(device)
arg.dof_indices_in_element = self._dof_indices_in_element.to(device)
return arg
@wp.func
def node_partition_index(args: NodeArg, node_index: int):
return args.dof_partition_indices[node_index]
@wp.func
def node_element_count(args: NodeArg, node_index: int):
partition_node_index = SpaceRestriction.node_partition_index(args, node_index)
return args.dof_element_offsets[partition_node_index + 1] - args.dof_element_offsets[partition_node_index]
@wp.func
def node_element_index(args: NodeArg, node_index: int, element_index: int):
partition_node_index = SpaceRestriction.node_partition_index(args, node_index)
offset = args.dof_element_offsets[partition_node_index] + element_index
domain_element_index = args.dof_element_indices[offset]
index_in_element = args.dof_indices_in_element[offset]
return NodeElementIndex(domain_element_index, index_in_element)
@wp.kernel
def _split_vertex_element_index(
vertex_per_element: int,
sorted_indices: wp.array(dtype=int),
vertex_element_index: wp.array(dtype=int),
vertex_index_in_element: wp.array(dtype=int),
):
idx = sorted_indices[wp.tid()]
element_index = idx // vertex_per_element
vertex_element_index[wp.tid()] = element_index
vertex_index_in_element[wp.tid()] = idx - vertex_per_element * element_index
| warp-main | warp/fem/space/restriction.py |
import warp as wp
import numpy as np
from warp.fem.types import ElementIndex, Coords, OUTSIDE, vec2i, vec3i, vec4i
from warp.fem.geometry import Tetmesh
from .dof_mapper import DofMapper
from .nodal_function_space import NodalFunctionSpace, NodalFunctionSpaceTrace
class TetmeshFunctionSpace(NodalFunctionSpace):
DIMENSION = wp.constant(3)
@wp.struct
class SpaceArg:
geo_arg: Tetmesh.SideArg
reference_transforms: wp.array(dtype=wp.mat33f)
tet_edge_indices: wp.array2d(dtype=int)
tet_face_indices: wp.array2d(dtype=int)
vertex_count: int
edge_count: int
face_count: int
def __init__(self, mesh: Tetmesh, dtype: type = float, dof_mapper: DofMapper = None):
super().__init__(dtype, dof_mapper)
self._mesh = mesh
self._reference_transforms: wp.array = None
self._tet_face_indices: wp.array = None
self._compute_reference_transforms()
self._compute_tet_face_indices()
self._compute_tet_edge_indices()
@property
def geometry(self) -> Tetmesh:
return self._mesh
def edge_count(self):
return self._edge_vertex_indices.shape[0]
def space_arg_value(self, device):
arg = self.SpaceArg()
arg.geo_arg = self.geometry.side_arg_value(device)
arg.reference_transforms = self._reference_transforms.to(device)
arg.tet_face_indices = self._tet_face_indices.to(device)
arg.tet_edge_indices = self._tet_edge_indices.to(device)
arg.vertex_count = self._mesh.vertex_count()
arg.face_count = self._mesh.side_count()
arg.edge_count = self.edge_count()
return arg
class Trace(NodalFunctionSpaceTrace):
def __init__(self, space: NodalFunctionSpace):
super().__init__(space)
self.ORDER = space.ORDER
@wp.func
def _inner_cell_index(args: SpaceArg, side_index: ElementIndex):
return Tetmesh.side_inner_cell_index(args.geo_arg, side_index)
@wp.func
def _outer_cell_index(args: SpaceArg, side_index: ElementIndex):
return Tetmesh.side_outer_cell_index(args.geo_arg, side_index)
@wp.func
def _inner_cell_coords(args: SpaceArg, side_index: ElementIndex, side_coords: Coords):
tet_index = Tetmesh.side_inner_cell_index(args.geo_arg, side_index)
return Tetmesh.face_to_tet_coords(args.geo_arg, side_index, tet_index, side_coords)
@wp.func
def _outer_cell_coords(args: SpaceArg, side_index: ElementIndex, side_coords: Coords):
tet_index = Tetmesh.side_outer_cell_index(args.geo_arg, side_index)
return Tetmesh.face_to_tet_coords(args.geo_arg, side_index, tet_index, side_coords)
@wp.func
def _cell_to_side_coords(
args: SpaceArg,
side_index: ElementIndex,
element_index: ElementIndex,
element_coords: Coords,
):
return Tetmesh.tet_to_face_coords(args.geo_arg, side_index, element_index, element_coords)
def _compute_reference_transforms(self):
self._reference_transforms = wp.empty(
dtype=wp.mat33f, device=self._mesh.positions.device, shape=(self._mesh.cell_count())
)
wp.launch(
kernel=TetmeshFunctionSpace._compute_reference_transforms_kernel,
dim=self._reference_transforms.shape,
device=self._reference_transforms.device,
inputs=[self._mesh.tet_vertex_indices, self._mesh.positions, self._reference_transforms],
)
def _compute_tet_face_indices(self):
self._tet_face_indices = wp.empty(
dtype=int, device=self._mesh.tet_vertex_indices.device, shape=(self._mesh.cell_count(), 4)
)
wp.launch(
kernel=TetmeshFunctionSpace._compute_tet_face_indices_kernel,
dim=self._mesh._face_tet_indices.shape,
device=self._mesh.tet_vertex_indices.device,
inputs=[
self._mesh._face_tet_indices,
self._mesh._face_vertex_indices,
self._mesh.tet_vertex_indices,
self._tet_face_indices,
],
)
def _compute_tet_edge_indices(self):
from warp.fem.utils import _get_pinned_temp_count_buffer
from warp.utils import array_scan
device = self._mesh.tet_vertex_indices.device
vertex_start_edge_count = wp.zeros(dtype=int, device=device, shape=self._mesh.vertex_count())
vertex_start_edge_offsets = wp.empty_like(vertex_start_edge_count)
vertex_edge_ends = wp.empty(dtype=int, device=device, shape=(6 * self._mesh.cell_count()))
# Count face edges starting at each vertex
wp.launch(
kernel=TetmeshFunctionSpace._count_starting_edges_kernel,
device=device,
dim=self._mesh.cell_count(),
inputs=[self._mesh.tet_vertex_indices, vertex_start_edge_count],
)
array_scan(in_array=vertex_start_edge_count, out_array=vertex_start_edge_offsets, inclusive=False)
# Count number of unique edges (deduplicate across faces)
vertex_unique_edge_count = vertex_start_edge_count
wp.launch(
kernel=TetmeshFunctionSpace._count_unique_starting_edges_kernel,
device=device,
dim=self._mesh.vertex_count(),
inputs=[
self._mesh._vertex_tet_offsets,
self._mesh._vertex_tet_indices,
self._mesh.tet_vertex_indices,
vertex_start_edge_offsets,
vertex_unique_edge_count,
vertex_edge_ends,
],
)
vertex_unique_edge_offsets = wp.empty_like(vertex_start_edge_offsets)
array_scan(in_array=vertex_start_edge_count, out_array=vertex_unique_edge_offsets, inclusive=False)
# Get back edge count to host
if device.is_cuda:
edge_count = _get_pinned_temp_count_buffer(device)
# Last vertex will not own any edge, so its count will be zero; just fetching last prefix count is ok
wp.copy(dest=edge_count, src=vertex_unique_edge_offsets, src_offset=self._mesh.vertex_count() - 1, count=1)
wp.synchronize_stream(wp.get_stream())
edge_count = int(edge_count.numpy()[0])
else:
edge_count = int(vertex_unique_edge_offsets.numpy()[self._mesh.vertex_count() - 1])
self._edge_vertex_indices = wp.empty(shape=(edge_count,), dtype=vec2i, device=device)
self._tet_edge_indices = wp.empty(
dtype=int, device=self._mesh.tet_vertex_indices.device, shape=(self._mesh.cell_count(), 6)
)
# Compress edge data
wp.launch(
kernel=TetmeshFunctionSpace._compress_edges_kernel,
device=device,
dim=self._mesh.vertex_count(),
inputs=[
self._mesh._vertex_tet_offsets,
self._mesh._vertex_tet_indices,
self._mesh.tet_vertex_indices,
vertex_start_edge_offsets,
vertex_unique_edge_offsets,
vertex_unique_edge_count,
vertex_edge_ends,
self._edge_vertex_indices,
self._tet_edge_indices,
],
)
@wp.kernel
def _compute_reference_transforms_kernel(
tet_vertex_indices: wp.array2d(dtype=int),
positions: wp.array(dtype=wp.vec3f),
transforms: wp.array(dtype=wp.mat33f),
):
t = wp.tid()
p0 = positions[tet_vertex_indices[t, 0]]
p1 = positions[tet_vertex_indices[t, 1]]
p2 = positions[tet_vertex_indices[t, 2]]
p3 = positions[tet_vertex_indices[t, 3]]
e1 = p1 - p0
e2 = p2 - p0
e3 = p3 - p0
mat = wp.mat33(e1, e2, e3)
transforms[t] = wp.transpose(wp.inverse(mat))
@wp.func
def _find_face_index_in_tet(
face_vtx: vec3i,
tet_vtx: vec4i,
):
for k in range(3):
tvk = vec3i(tet_vtx[k], tet_vtx[(k + 1) % 4], tet_vtx[(k + 2) % 4])
# Use fact that face always start with min vertex
min_t = wp.min(tvk)
max_t = wp.max(tvk)
mid_t = tvk[0] + tvk[1] + tvk[2] - min_t - max_t
if min_t == face_vtx[0] and (
(face_vtx[2] == max_t and face_vtx[1] == mid_t) or (face_vtx[1] == max_t and face_vtx[2] == mid_t)
):
return k
return 3
@wp.kernel
def _compute_tet_face_indices_kernel(
face_tet_indices: wp.array(dtype=vec2i),
face_vertex_indices: wp.array(dtype=vec3i),
tet_vertex_indices: wp.array2d(dtype=int),
tet_face_indices: wp.array2d(dtype=int),
):
e = wp.tid()
face_vtx = face_vertex_indices[e]
face_tets = face_tet_indices[e]
t0 = face_tets[0]
t0_vtx = vec4i(
tet_vertex_indices[t0, 0], tet_vertex_indices[t0, 1], tet_vertex_indices[t0, 2], tet_vertex_indices[t0, 3]
)
t0_face = TetmeshFunctionSpace._find_face_index_in_tet(face_vtx, t0_vtx)
tet_face_indices[t0, t0_face] = e
t1 = face_tets[1]
if t1 != t0:
t1_vtx = vec4i(
tet_vertex_indices[t1, 0],
tet_vertex_indices[t1, 1],
tet_vertex_indices[t1, 2],
tet_vertex_indices[t1, 3],
)
t1_face = TetmeshFunctionSpace._find_face_index_in_tet(face_vtx, t1_vtx)
tet_face_indices[t1, t1_face] = e
@wp.kernel
def _count_starting_edges_kernel(
tri_vertex_indices: wp.array2d(dtype=int), vertex_start_edge_count: wp.array(dtype=int)
):
t = wp.tid()
for k in range(3):
v0 = tri_vertex_indices[t, k]
v1 = tri_vertex_indices[t, (k + 1) % 3]
if v0 < v1:
wp.atomic_add(vertex_start_edge_count, v0, 1)
else:
wp.atomic_add(vertex_start_edge_count, v1, 1)
for k in range(3):
v0 = tri_vertex_indices[t, k]
v1 = tri_vertex_indices[t, 3]
if v0 < v1:
wp.atomic_add(vertex_start_edge_count, v0, 1)
else:
wp.atomic_add(vertex_start_edge_count, v1, 1)
@wp.func
def _find(
needle: int,
values: wp.array(dtype=int),
beg: int,
end: int,
):
for i in range(beg, end):
if values[i] == needle:
return i
return -1
@wp.kernel
def _count_unique_starting_edges_kernel(
vertex_tet_offsets: wp.array(dtype=int),
vertex_tet_indices: wp.array(dtype=int),
tet_vertex_indices: wp.array2d(dtype=int),
vertex_start_edge_offsets: wp.array(dtype=int),
vertex_start_edge_count: wp.array(dtype=int),
edge_ends: wp.array(dtype=int),
):
v = wp.tid()
edge_beg = vertex_start_edge_offsets[v]
tet_beg = vertex_tet_offsets[v]
tet_end = vertex_tet_offsets[v + 1]
edge_cur = edge_beg
for tet in range(tet_beg, tet_end):
t = vertex_tet_indices[tet]
for k in range(3):
v0 = tet_vertex_indices[t, k]
v1 = tet_vertex_indices[t, (k + 1) % 3]
if v == wp.min(v0, v1):
other_v = wp.max(v0, v1)
if TetmeshFunctionSpace._find(other_v, edge_ends, edge_beg, edge_cur) == -1:
edge_ends[edge_cur] = other_v
edge_cur += 1
for k in range(3):
v0 = tet_vertex_indices[t, k]
v1 = tet_vertex_indices[t, 3]
if v == wp.min(v0, v1):
other_v = wp.max(v0, v1)
if TetmeshFunctionSpace._find(other_v, edge_ends, edge_beg, edge_cur) == -1:
edge_ends[edge_cur] = other_v
edge_cur += 1
vertex_start_edge_count[v] = edge_cur - edge_beg
@wp.kernel
def _compress_edges_kernel(
vertex_tet_offsets: wp.array(dtype=int),
vertex_tet_indices: wp.array(dtype=int),
tet_vertex_indices: wp.array2d(dtype=int),
vertex_start_edge_offsets: wp.array(dtype=int),
vertex_unique_edge_offsets: wp.array(dtype=int),
vertex_unique_edge_count: wp.array(dtype=int),
uncompressed_edge_ends: wp.array(dtype=int),
edge_vertex_indices: wp.array(dtype=vec2i),
tet_edge_indices: wp.array2d(dtype=int),
):
v = wp.tid()
uncompressed_beg = vertex_start_edge_offsets[v]
unique_beg = vertex_unique_edge_offsets[v]
unique_count = vertex_unique_edge_count[v]
for e in range(unique_count):
src_index = uncompressed_beg + e
edge_index = unique_beg + e
edge_vertex_indices[edge_index] = vec2i(v, uncompressed_edge_ends[src_index])
tet_beg = vertex_tet_offsets[v]
tet_end = vertex_tet_offsets[v + 1]
for tet in range(tet_beg, tet_end):
t = vertex_tet_indices[tet]
for k in range(3):
v0 = tet_vertex_indices[t, k]
v1 = tet_vertex_indices[t, (k + 1) % 3]
if v == wp.min(v0, v1):
other_v = wp.max(v0, v1)
edge_id = (
TetmeshFunctionSpace._find(
other_v, uncompressed_edge_ends, uncompressed_beg, uncompressed_beg + unique_count
)
- uncompressed_beg
+ unique_beg
)
tet_edge_indices[t][k] = edge_id
for k in range(3):
v0 = tet_vertex_indices[t, k]
v1 = tet_vertex_indices[t, 3]
if v == wp.min(v0, v1):
other_v = wp.max(v0, v1)
edge_id = (
TetmeshFunctionSpace._find(
other_v, uncompressed_edge_ends, uncompressed_beg, uncompressed_beg + unique_count
)
- uncompressed_beg
+ unique_beg
)
tet_edge_indices[t][k + 3] = edge_id
class TetmeshPiecewiseConstantSpace(TetmeshFunctionSpace):
ORDER = wp.constant(0)
NODES_PER_ELEMENT = wp.constant(1)
def __init__(self, grid: Tetmesh, dtype: type = float, dof_mapper: DofMapper = None):
super().__init__(grid, dtype, dof_mapper)
self.element_outer_weight = self.element_inner_weight
self.element_outer_weight_gradient = self.element_inner_weight_gradient
def node_count(self) -> int:
return self._mesh.cell_count()
def node_positions(self):
vtx_pos = self._mesh.positions.numpy()
tet_vtx = self._mesh.tet_vertex_indices.numpy()
tet_pos = vtx_pos[tet_vtx]
centers = tet_pos.sum(axis=1) / 4.0
return centers[:, 0], centers[:, 1], centers[:, 2]
@wp.func
def element_node_index(
args: TetmeshFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return element_index
@wp.func
def node_coords_in_element(
args: TetmeshFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
if node_index_in_elt == 0:
return Coords(1.0 / 4.0, 1.0 / 4.0, 1.0 / 4.0)
return Coords(OUTSIDE)
@wp.func
def node_quadrature_weight(
args: TetmeshFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return 1.0
@wp.func
def element_inner_weight(
args: TetmeshFunctionSpace.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
if node_index_in_elt == 0:
return 1.0
return 0.0
@wp.func
def element_inner_weight_gradient(
args: TetmeshFunctionSpace.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
return wp.vec3(0.0)
class Trace(TetmeshFunctionSpace.Trace):
NODES_PER_ELEMENT = wp.constant(2)
ORDER = wp.constant(0)
def __init__(self, space: "TetmeshPiecewiseConstantSpace"):
super().__init__(space)
self.element_node_index = self._make_element_node_index(space)
self.element_inner_weight = self._make_element_inner_weight(space)
self.element_inner_weight_gradient = self._make_element_inner_weight_gradient(space)
self.element_outer_weight = self._make_element_outer_weight(space)
self.element_outer_weight_gradient = self._make_element_outer_weight_gradient(space)
@wp.func
def node_coords_in_element(
args: TetmeshFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_element: int,
):
if node_index_in_element == 0:
return Coords(1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0)
elif node_index_in_element == 1:
return Coords(1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0)
return Coords(OUTSIDE)
@wp.func
def node_quadrature_weight(
args: TetmeshFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return 1.0
def trace(self):
return TetmeshPiecewiseConstantSpace.Trace(self)
def _tet_node_index(tx: int, ty: int, tz: int, degree: int):
from .trimesh_2d_function_space import _triangle_node_index
VERTEX_NODE_COUNT = 4
EDGE_INTERIOR_NODE_COUNT = degree - 1
VERTEX_EDGE_NODE_COUNT = VERTEX_NODE_COUNT + 6 * EDGE_INTERIOR_NODE_COUNT
FACE_INTERIOR_NODE_COUNT = (degree - 1) * (degree - 2) // 2
VERTEX_EDGE_FACE_NODE_COUNT = VERTEX_EDGE_NODE_COUNT + 4 * FACE_INTERIOR_NODE_COUNT
# Index in similar order to e.g. VTK
# First vertices, then edges (counterclokwise), then faces, then interior points (recursively)
if tx == 0:
if ty == 0:
if tz == 0:
return 0
elif tz == degree:
return 3
else:
# 0-3 edge
edge_index = 3
return VERTEX_NODE_COUNT + EDGE_INTERIOR_NODE_COUNT * edge_index + (tz - 1)
elif tz == 0:
if ty == degree:
return 2
else:
# 2-0 edge
edge_index = 2
return VERTEX_NODE_COUNT + EDGE_INTERIOR_NODE_COUNT * edge_index + (EDGE_INTERIOR_NODE_COUNT - ty)
elif tz + ty == degree:
# 2-3 edge
edge_index = 5
return VERTEX_NODE_COUNT + EDGE_INTERIOR_NODE_COUNT * edge_index + (tz - 1)
else:
# 2-3-0 face
face_index = 2
return (
VERTEX_EDGE_NODE_COUNT
+ FACE_INTERIOR_NODE_COUNT * face_index
+ _triangle_node_index(degree - 2 - ty, tz - 1, degree - 2)
)
elif ty == 0:
if tz == 0:
if tx == degree:
return 1
else:
# 0-1 edge
edge_index = 0
return VERTEX_NODE_COUNT + EDGE_INTERIOR_NODE_COUNT * edge_index + (tx - 1)
elif tz + tx == degree:
# 1-3 edge
edge_index = 4
return VERTEX_NODE_COUNT + EDGE_INTERIOR_NODE_COUNT * edge_index + (tz - 1)
else:
# 3-0-1 face
face_index = 3
return (
VERTEX_EDGE_NODE_COUNT
+ FACE_INTERIOR_NODE_COUNT * face_index
+ _triangle_node_index(tx - 1, tz - 1, degree - 2)
)
elif tz == 0:
if tx + ty == degree:
# 1-2 edge
edge_index = 1
return VERTEX_NODE_COUNT + EDGE_INTERIOR_NODE_COUNT * edge_index + (ty - 1)
else:
# 0-1-2 face
face_index = 0
return (
VERTEX_EDGE_NODE_COUNT
+ FACE_INTERIOR_NODE_COUNT * face_index
+ _triangle_node_index(tx - 1, ty - 1, degree - 2)
)
elif tx + ty + tz == degree:
# 1-2-3 face
face_index = 1
return (
VERTEX_EDGE_NODE_COUNT
+ FACE_INTERIOR_NODE_COUNT * face_index
+ _triangle_node_index(tx - 1, tz - 1, degree - 2)
)
return VERTEX_EDGE_FACE_NODE_COUNT + _tet_node_index(tx - 1, ty - 1, tz - 1, degree - 3)
class TetmeshPolynomialShapeFunctions:
INVALID = wp.constant(-1)
VERTEX = wp.constant(0)
EDGE = wp.constant(1)
FACE = wp.constant(2)
INTERIOR = wp.constant(3)
def __init__(self, degree: int):
self.ORDER = wp.constant(degree)
self.NODES_PER_ELEMENT = wp.constant((degree + 1) * (degree + 2) * (degree + 3) // 6)
self.NODES_PER_SIDE = wp.constant((degree + 1) * (degree + 2) // 2)
tet_coords = np.empty((self.NODES_PER_ELEMENT, 3), dtype=int)
for tx in range(degree + 1):
for ty in range(degree + 1 - tx):
for tz in range(degree + 1 - tx - ty):
index = _tet_node_index(tx, ty, tz, degree)
tet_coords[index] = [tx, ty, tz]
CoordTypeVec = wp.mat(dtype=int, shape=(self.NODES_PER_ELEMENT, 3))
self.NODE_TET_COORDS = wp.constant(CoordTypeVec(tet_coords))
self.node_type_and_type_index = self._get_node_type_and_type_index()
self._node_tet_coordinates = self._get_node_tet_coordinates()
@property
def name(self) -> str:
return f"{self.ORDER}"
def _get_node_tet_coordinates(self):
NODE_TET_COORDS = self.NODE_TET_COORDS
def node_tet_coordinates(
node_index_in_elt: int,
):
return vec3i(
NODE_TET_COORDS[node_index_in_elt, 0],
NODE_TET_COORDS[node_index_in_elt, 1],
NODE_TET_COORDS[node_index_in_elt, 2],
)
from warp.fem import cache
return cache.get_func(node_tet_coordinates, self.name)
def _get_node_type_and_type_index(self):
ORDER = self.ORDER
NODES_PER_ELEMENT = self.NODES_PER_ELEMENT
def node_type_and_index(
node_index_in_elt: int,
):
if node_index_in_elt < 0 or node_index_in_elt >= NODES_PER_ELEMENT:
return TetmeshPolynomialShapeFunctions.INVALID, TetmeshPolynomialShapeFunctions.INVALID
if node_index_in_elt < 4:
return TetmeshPolynomialShapeFunctions.VERTEX, node_index_in_elt
if node_index_in_elt < (6 * ORDER - 2):
return TetmeshPolynomialShapeFunctions.EDGE, (node_index_in_elt - 4)
if node_index_in_elt < (2 * ORDER * ORDER + 2):
return TetmeshPolynomialShapeFunctions.FACE, (node_index_in_elt - (6 * ORDER - 2))
return TetmeshPolynomialShapeFunctions.INTERIOR, (node_index_in_elt - (2 * ORDER * ORDER + 2))
from warp.fem import cache
return cache.get_func(node_type_and_index, self.name)
def make_node_coords_in_element(self):
ORDER = self.ORDER
def node_coords_in_element(
args: TetmeshFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
tet_coords = self._node_tet_coordinates(node_index_in_elt)
cx = float(tet_coords[0]) / float(ORDER)
cy = float(tet_coords[1]) / float(ORDER)
cz = float(tet_coords[2]) / float(ORDER)
return Coords(cx, cy, cz)
from warp.fem import cache
return cache.get_func(node_coords_in_element, self.name)
def make_node_quadrature_weight(self):
ORDER = self.ORDER
def node_uniform_quadrature_weight(
args: TetmeshFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
node_type, type_index = self.node_type_and_type_index(node_index_in_elt)
base_weight = 1.0 / float(4 * ORDER * ORDER * ORDER)
if node_type == TetmeshPolynomialShapeFunctions.VERTEX:
return base_weight
if node_type == TetmeshPolynomialShapeFunctions.EDGE:
return 2.0 * base_weight
if node_type == TetmeshPolynomialShapeFunctions.FACE:
return 4.0 * base_weight
return 8.0 * base_weight
def node_linear_quadrature_weight(
args: TetmeshFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return 1.0 / 4.0
from warp.fem import cache
if ORDER == 1:
return cache.get_func(node_linear_quadrature_weight, self.name)
return cache.get_func(node_uniform_quadrature_weight, self.name)
def make_trace_node_quadrature_weight(self):
ORDER = self.ORDER
NODES_PER_ELEMENT = self.NODES_PER_ELEMENT
def trace_uniform_node_quadrature_weight(
args: TetmeshFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
if node_index_in_elt >= NODES_PER_ELEMENT:
node_index_in_cell = node_index_in_elt - NODES_PER_ELEMENT
else:
node_index_in_cell = node_index_in_elt
# We're either on a side interior or at a vertex
node_type, type_index = self.node_type_and_type_index(node_index_in_cell)
base_weight = 1.0 / float(3 * ORDER * ORDER)
if node_type == TetmeshPolynomialShapeFunctions.VERTEX:
return base_weight
if node_type == TetmeshPolynomialShapeFunctions.EDGE:
return 2.0 * base_weight
return 4.0 * base_weight
def trace_linear_node_quadrature_weight(
args: TetmeshFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return 1.0 / 3.0
from warp.fem import cache
if ORDER == 1:
return cache.get_func(trace_linear_node_quadrature_weight, self.name)
return cache.get_func(trace_uniform_node_quadrature_weight, self.name)
def make_element_inner_weight(self):
ORDER = self.ORDER
def element_inner_weight_linear(
args: TetmeshFunctionSpace.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
if node_index_in_elt < 0 or node_index_in_elt >= 4:
return 0.0
tet_coords = wp.vec4(1.0 - coords[0] - coords[1] - coords[2], coords[0], coords[1], coords[2])
return tet_coords[node_index_in_elt]
def element_inner_weight_quadratic(
args: TetmeshFunctionSpace.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
node_type, type_index = self.node_type_and_type_index(node_index_in_elt)
tet_coords = wp.vec4(1.0 - coords[0] - coords[1] - coords[2], coords[0], coords[1], coords[2])
if node_type == TetmeshPolynomialShapeFunctions.VERTEX:
# Vertex
return tet_coords[type_index] * (2.0 * tet_coords[type_index] - 1.0)
elif node_type == TetmeshPolynomialShapeFunctions.EDGE:
# Edge
if type_index < 3:
c1 = type_index
c2 = (type_index + 1) % 3
else:
c1 = type_index - 3
c2 = 3
return 4.0 * tet_coords[c1] * tet_coords[c2]
return 0.0
def element_inner_weight_cubic(
args: TetmeshFunctionSpace.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
node_type, type_index = self.node_type_and_type_index(node_index_in_elt)
tet_coords = wp.vec4(1.0 - coords[0] - coords[1] - coords[2], coords[0], coords[1], coords[2])
if node_type == TetmeshPolynomialShapeFunctions.VERTEX:
# Vertex
return (
0.5
* tet_coords[type_index]
* (3.0 * tet_coords[type_index] - 1.0)
* (3.0 * tet_coords[type_index] - 2.0)
)
elif node_type == TetmeshPolynomialShapeFunctions.EDGE:
# Edge
edge = type_index // 2
edge_node = type_index - 2 * edge
if edge < 3:
c1 = (edge + edge_node) % 3
c2 = (edge + 1 - edge_node) % 3
elif edge_node == 0:
c1 = edge - 3
c2 = 3
else:
c1 = 3
c2 = edge - 3
return 4.5 * tet_coords[c1] * tet_coords[c2] * (3.0 * tet_coords[c1] - 1.0)
elif node_type == TetmeshPolynomialShapeFunctions.FACE:
# Interior
c1 = type_index
c2 = (c1 + 1) % 4
c3 = (c1 + 2) % 4
return 27.0 * tet_coords[c1] * tet_coords[c2] * tet_coords[c3]
return 0.0
from warp.fem import cache
if ORDER == 1:
return cache.get_func(element_inner_weight_linear, self.name)
elif ORDER == 2:
return cache.get_func(element_inner_weight_quadratic, self.name)
elif ORDER == 3:
return cache.get_func(element_inner_weight_cubic, self.name)
return None
def make_element_inner_weight_gradient(self):
ORDER = self.ORDER
def element_inner_weight_gradient_linear(
args: TetmeshFunctionSpace.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
if node_index_in_elt < 0 or node_index_in_elt >= 4:
return wp.vec3(0.0)
dw_dc = wp.vec4(0.0)
dw_dc[node_index_in_elt] = 1.0
dw_du = wp.vec3(dw_dc[1] - dw_dc[0], dw_dc[2] - dw_dc[0], dw_dc[3] - dw_dc[0])
return args.reference_transforms[element_index] * dw_du
def element_inner_weight_gradient_quadratic(
args: TetmeshFunctionSpace.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
node_type, type_index = self.node_type_and_type_index(node_index_in_elt)
tet_coords = wp.vec4(1.0 - coords[0] - coords[1] - coords[2], coords[0], coords[1], coords[2])
dw_dc = wp.vec4(0.0)
if node_type == TetmeshPolynomialShapeFunctions.VERTEX:
# Vertex
dw_dc[type_index] = 4.0 * tet_coords[type_index] - 1.0
elif node_type == TetmeshPolynomialShapeFunctions.EDGE:
# Edge
if type_index < 3:
c1 = type_index
c2 = (type_index + 1) % 3
else:
c1 = type_index - 3
c2 = 3
dw_dc[c1] = 4.0 * tet_coords[c2]
dw_dc[c2] = 4.0 * tet_coords[c1]
dw_du = wp.vec3(dw_dc[1] - dw_dc[0], dw_dc[2] - dw_dc[0], dw_dc[3] - dw_dc[0])
return args.reference_transforms[element_index] * dw_du
def element_inner_weight_gradient_cubic(
args: TetmeshFunctionSpace.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
node_type, type_index = self.node_type_and_type_index(node_index_in_elt)
tet_coords = wp.vec4(1.0 - coords[0] - coords[1] - coords[2], coords[0], coords[1], coords[2])
dw_dc = wp.vec4(0.0)
if node_type == TetmeshPolynomialShapeFunctions.VERTEX:
# Vertex
dw_dc[type_index] = (
0.5 * 27.0 * tet_coords[type_index] * tet_coords[type_index] - 9.0 * tet_coords[type_index] + 1.0
)
elif node_type == TetmeshPolynomialShapeFunctions.EDGE:
# Edge
edge = type_index // 2
edge_node = type_index - 2 * edge
if edge < 3:
c1 = (edge + edge_node) % 3
c2 = (edge + 1 - edge_node) % 3
elif edge_node == 0:
c1 = edge - 3
c2 = 3
else:
c1 = 3
c2 = edge - 3
dw_dc[c1] = 4.5 * tet_coords[c2] * (6.0 * tet_coords[c1] - 1.0)
dw_dc[c2] = 4.5 * tet_coords[c1] * (3.0 * tet_coords[c1] - 1.0)
elif node_type == TetmeshPolynomialShapeFunctions.FACE:
# Interior
c1 = type_index
c2 = (c1 + 1) % 4
c3 = (c1 + 2) % 4
dw_dc[c1] = 27.0 * tet_coords[c2] * tet_coords[c3]
dw_dc[c2] = 27.0 * tet_coords[c3] * tet_coords[c1]
dw_dc[c3] = 27.0 * tet_coords[c1] * tet_coords[c2]
dw_du = wp.vec3(dw_dc[1] - dw_dc[0], dw_dc[2] - dw_dc[0], dw_dc[3] - dw_dc[0])
return args.reference_transforms[element_index] * dw_du
from warp.fem import cache
if ORDER == 1:
return cache.get_func(element_inner_weight_gradient_linear, self.name)
elif ORDER == 2:
return cache.get_func(element_inner_weight_gradient_quadratic, self.name)
elif ORDER == 3:
return cache.get_func(element_inner_weight_gradient_cubic, self.name)
return None
@staticmethod
def node_positions(space):
if space.ORDER == 1:
node_positions = space._mesh.positions.numpy()
return node_positions[:, 0], node_positions[:, 1], node_positions[:, 2]
NODES_PER_ELEMENT = space.NODES_PER_ELEMENT
def fill_node_positions_fn(
space_arg: space.SpaceArg,
node_positions: wp.array(dtype=wp.vec3),
):
element_index = wp.tid()
tet_idx = space_arg.geo_arg.tet_vertex_indices[element_index]
p0 = space_arg.geo_arg.positions[tet_idx[0]]
p1 = space_arg.geo_arg.positions[tet_idx[1]]
p2 = space_arg.geo_arg.positions[tet_idx[2]]
p3 = space_arg.geo_arg.positions[tet_idx[3]]
for n in range(NODES_PER_ELEMENT):
node_index = space.element_node_index(space_arg, element_index, n)
coords = space.node_coords_in_element(space_arg, element_index, n)
pos = p0 + coords[0] * (p1 - p0) + coords[1] * (p2 - p0) + coords[2] * (p3 - p0)
node_positions[node_index] = pos
from warp.fem import cache
fill_node_positions = cache.get_kernel(
fill_node_positions_fn,
suffix=space.name,
)
device = space._mesh.tet_vertex_indices.device
node_positions = wp.empty(
shape=space.node_count(),
dtype=wp.vec3,
device=device,
)
wp.launch(
dim=space._mesh.cell_count(),
kernel=fill_node_positions,
inputs=[
space.space_arg_value(device),
node_positions,
],
device=device,
)
node_positions = node_positions.numpy()
return node_positions[:, 0], node_positions[:, 1], node_positions[:, 2]
class TetmeshPolynomialSpace(TetmeshFunctionSpace):
def __init__(self, grid: Tetmesh, degree: int, dtype: type = float, dof_mapper: DofMapper = None):
super().__init__(grid, dtype, dof_mapper)
self._shape = TetmeshPolynomialShapeFunctions(degree)
self.ORDER = self._shape.ORDER
self.NODES_PER_ELEMENT = self._shape.NODES_PER_ELEMENT
self.element_node_index = self._make_element_node_index()
self.node_coords_in_element = self._shape.make_node_coords_in_element()
self.node_quadrature_weight = self._shape.make_node_quadrature_weight()
self.element_inner_weight = self._shape.make_element_inner_weight()
self.element_inner_weight_gradient = self._shape.make_element_inner_weight_gradient()
self.element_outer_weight = self.element_inner_weight
self.element_outer_weight_gradient = self.element_inner_weight_gradient
def _make_element_node_index(self):
INTERIOR_NODES_PER_EDGE = wp.constant(max(0, self.ORDER - 1))
INTERIOR_NODES_PER_FACE = wp.constant(max(0, self.ORDER - 2) * max(0, self.ORDER - 1) // 2)
INTERIOR_NODES_PER_CELL = wp.constant(
max(0, self.ORDER - 3) * max(0, self.ORDER - 2) * max(0, self.ORDER - 1) // 6
)
def element_node_index(
args: TetmeshFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
node_type, type_index = self._shape.node_type_and_type_index(node_index_in_elt)
if node_type == TetmeshPolynomialShapeFunctions.VERTEX:
return args.geo_arg.tet_vertex_indices[element_index][type_index]
global_offset = args.vertex_count
if node_type == TetmeshPolynomialShapeFunctions.EDGE:
edge = type_index // INTERIOR_NODES_PER_EDGE
edge_node = type_index - INTERIOR_NODES_PER_EDGE * edge
global_edge_index = args.tet_edge_indices[element_index][edge]
# Test if we need to swap edge direction
if INTERIOR_NODES_PER_EDGE > 1:
if edge < 3:
c1 = edge
c2 = (edge + 1) % 3
else:
c1 = edge - 3
c2 = 3
if (
args.geo_arg.tet_vertex_indices[element_index][c1]
> args.geo_arg.tet_vertex_indices[element_index][c2]
):
edge_node = INTERIOR_NODES_PER_EDGE - 1 - edge_node
return global_offset + INTERIOR_NODES_PER_EDGE * global_edge_index + edge_node
global_offset += INTERIOR_NODES_PER_EDGE * args.edge_count
if node_type == TetmeshPolynomialShapeFunctions.FACE:
face = type_index // INTERIOR_NODES_PER_FACE
face_node = type_index - INTERIOR_NODES_PER_FACE * face
global_face_index = args.tet_face_indices[element_index][face]
if INTERIOR_NODES_PER_FACE == 3:
# Hard code for P4 case, 3 nodes per face
# Higher orders would require rotating triangle coordinates, this is not supported yet
vidx = args.geo_arg.tet_vertex_indices[element_index][(face + face_node) % 4]
fvi = args.geo_arg.face_vertex_indices[global_face_index]
if vidx == fvi[0]:
face_node = 0
elif vidx == fvi[1]:
face_node = 1
else:
face_node = 2
return global_offset + INTERIOR_NODES_PER_FACE * global_face_index + face_node
global_offset += INTERIOR_NODES_PER_FACE * args.face_count
return global_offset + INTERIOR_NODES_PER_CELL * element_index + type_index
from warp.fem import cache
return cache.get_func(element_node_index, self.name)
def node_count(self) -> int:
INTERIOR_NODES_PER_EDGE = wp.constant(max(0, self.ORDER - 1))
INTERIOR_NODES_PER_FACE = wp.constant(max(0, self.ORDER - 2) * max(0, self.ORDER - 1) // 2)
INTERIOR_NODES_PER_CELL = wp.constant(
max(0, self.ORDER - 3) * max(0, self.ORDER - 2) * max(0, self.ORDER - 1) // 6
)
return (
self._mesh.vertex_count()
+ self.edge_count() * INTERIOR_NODES_PER_EDGE
+ self._mesh.side_count() * INTERIOR_NODES_PER_FACE
+ self._mesh.cell_count() * INTERIOR_NODES_PER_CELL
)
def node_positions(self):
return TetmeshPolynomialShapeFunctions.node_positions(self)
class Trace(TetmeshFunctionSpace.Trace):
NODES_PER_ELEMENT = wp.constant(2)
ORDER = wp.constant(0)
def __init__(self, space: "TetmeshPolynomialSpace"):
super().__init__(space)
self.element_node_index = self._make_element_node_index(space)
self.node_coords_in_element = self._make_node_coords_in_element(space)
self.node_quadrature_weight = space._shape.make_trace_node_quadrature_weight()
self.element_inner_weight = self._make_element_inner_weight(space)
self.element_inner_weight_gradient = self._make_element_inner_weight_gradient(space)
self.element_outer_weight = self._make_element_outer_weight(space)
self.element_outer_weight_gradient = self._make_element_outer_weight_gradient(space)
def trace(self):
return TetmeshPolynomialSpace.Trace(self)
class TetmeshDGPolynomialSpace(TetmeshFunctionSpace):
def __init__(
self,
mesh: Tetmesh,
degree: int,
dtype: type = float,
dof_mapper: DofMapper = None,
):
super().__init__(mesh, dtype, dof_mapper)
self._shape = TetmeshPolynomialShapeFunctions(degree)
self.ORDER = self._shape.ORDER
self.NODES_PER_ELEMENT = self._shape.NODES_PER_ELEMENT
self.element_node_index = self._make_element_node_index()
self.node_coords_in_element = self._shape.make_node_coords_in_element()
self.node_quadrature_weight = self._shape.make_node_quadrature_weight()
self.element_inner_weight = self._shape.make_element_inner_weight()
self.element_inner_weight_gradient = self._shape.make_element_inner_weight_gradient()
self.element_outer_weight = self.element_inner_weight
self.element_outer_weight_gradient = self.element_inner_weight_gradient
def node_count(self) -> int:
return self._mesh.cell_count() * self.NODES_PER_ELEMENT
def node_positions(self):
return TetmeshPolynomialShapeFunctions.node_positions(self)
def node_triangulation(self):
return TetmeshPolynomialShapeFunctions.node_triangulation(self)
def _make_element_node_index(self):
NODES_PER_ELEMENT = self.NODES_PER_ELEMENT
def element_node_index(
args: TetmeshFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return element_index * NODES_PER_ELEMENT + node_index_in_elt
from warp.fem import cache
return cache.get_func(element_node_index, f"{self.name}_{self.ORDER}")
class Trace(TetmeshPolynomialSpace.Trace):
def __init__(self, space: "TetmeshDGPolynomialSpace"):
super().__init__(space)
def trace(self):
return TetmeshDGPolynomialSpace.Trace(self)
| warp-main | warp/fem/space/tetmesh_function_space.py |
import warp as wp
import numpy as np
from warp.fem.types import ElementIndex, Coords, OUTSIDE
from warp.fem.types import vec2i
from warp.fem.polynomial import Polynomial, lagrange_scales, quadrature_1d, is_closed
from warp.fem.geometry import Grid2D
from .dof_mapper import DofMapper
from .nodal_function_space import NodalFunctionSpace, NodalFunctionSpaceTrace
class Grid2DFunctionSpace(NodalFunctionSpace):
DIMENSION = wp.constant(2)
@wp.struct
class SpaceArg:
geo_arg: Grid2D.SideArg
inv_cell_size: wp.vec2
def __init__(self, grid: Grid2D, dtype: type = float, dof_mapper: DofMapper = None):
super().__init__(dtype, dof_mapper)
self._grid = grid
@property
def geometry(self) -> Grid2D:
return self._grid
def space_arg_value(self, device):
arg = self.SpaceArg()
arg.geo_arg = self.geometry.side_arg_value(device)
arg.inv_cell_size = wp.vec2(
1.0 / self.geometry.cell_size[0],
1.0 / self.geometry.cell_size[1],
)
return arg
class Trace(NodalFunctionSpaceTrace):
def __init__(self, space: NodalFunctionSpace):
super().__init__(space)
self.ORDER = space.ORDER
@wp.func
def _inner_cell_index(args: SpaceArg, side_index: ElementIndex):
return Grid2D.side_inner_cell_index(args.geo_arg, side_index)
@wp.func
def _outer_cell_index(args: SpaceArg, side_index: ElementIndex):
return Grid2D.side_outer_cell_index(args.geo_arg, side_index)
@wp.func
def _inner_cell_coords(args: SpaceArg, side_index: ElementIndex, side_coords: Coords):
side = Grid2D.get_side(args.geo_arg, side_index)
if side.origin[0] == 0:
inner_alt = 0.0
else:
inner_alt = 1.0
coords = Grid2D._rotate(side.axis, wp.vec2(inner_alt, side_coords[0]))
return Coords(coords[0], coords[1], 0.0)
@wp.func
def _outer_cell_coords(args: SpaceArg, side_index: ElementIndex, side_coords: Coords):
side = Grid2D.get_side(args.geo_arg, side_index)
alt_axis = Grid2D.ROTATION[side.axis, 0]
if side.origin[0] == args.geo_arg.cell_arg.res[alt_axis]:
outer_alt = 1.0
else:
outer_alt = 0.0
coords = Grid2D._rotate(side.axis, wp.vec2(outer_alt, side_coords[0]))
return Coords(coords[0], coords[1], 0.0)
@wp.func
def _cell_to_side_coords(
args: SpaceArg,
side_index: ElementIndex,
element_index: ElementIndex,
element_coords: Coords,
):
side = Grid2D.get_side(args.geo_arg, side_index)
cell = Grid2D.get_cell(args.geo_arg.cell_arg.res, element_index)
if float(side.origin[0] - cell[side.axis]) == element_coords[side.axis]:
long_axis = Grid2D.ROTATION[side.axis, 1]
return Coords(element_coords[long_axis], 0.0, 0.0)
return Coords(OUTSIDE)
@wp.func
def _vertex_coords(vidx_in_cell: int):
x = vidx_in_cell // 2
y = vidx_in_cell - 2 * x
return vec2i(x, y)
@wp.func
def _vertex_coords_f(vidx_in_cell: int):
x = vidx_in_cell // 2
y = vidx_in_cell - 2 * x
return wp.vec2(float(x), float(y))
@wp.func
def _vertex_index(args: SpaceArg, cell_index: ElementIndex, vidx_in_cell: int):
res = args.geo_arg.cell_arg.res
x_stride = res[1] + 1
corner = Grid2D.get_cell(res, cell_index) + Grid2DFunctionSpace._vertex_coords(vidx_in_cell)
return Grid2D._from_2d_index(x_stride, corner)
class GridPiecewiseConstantSpace(Grid2DFunctionSpace):
ORDER = wp.constant(0)
NODES_PER_ELEMENT = wp.constant(1)
def __init__(self, grid: Grid2D, dtype: type = float, dof_mapper: DofMapper = None):
super().__init__(grid, dtype, dof_mapper)
self.element_outer_weight = self.element_inner_weight
self.element_outer_weight_gradient = self.element_inner_weight_gradient
def node_count(self) -> int:
return self._grid.cell_count()
def node_positions(self):
res = self._grid.res
X = (np.arange(0, res[0], dtype=float) + 0.5) * self._grid.cell_size[0] + self._grid.origin[0]
Y = (np.arange(0, res[1], dtype=float) + 0.5) * self._grid.cell_size[1] + self._grid.origin[1]
return np.meshgrid(X, Y, indexing="ij")
@wp.func
def element_node_index(
args: Grid2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return element_index
@wp.func
def node_coords_in_element(
args: Grid2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
if node_index_in_elt == 0:
return Coords(0.5, 0.5, 0.0)
return Coords(OUTSIDE)
@wp.func
def node_quadrature_weight(
args: Grid2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return 1.0
@wp.func
def element_inner_weight(
args: Grid2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
if node_index_in_elt == 0:
return 1.0
return 0.0
@wp.func
def element_inner_weight_gradient(
args: Grid2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
return wp.vec2(0.0)
class Trace(Grid2DFunctionSpace.Trace):
NODES_PER_ELEMENT = wp.constant(2)
ORDER = wp.constant(0)
def __init__(self, space: "GridPiecewiseConstantSpace"):
super().__init__(space)
self.element_node_index = self._make_element_node_index(space)
self.element_inner_weight = self._make_element_inner_weight(space)
self.element_inner_weight_gradient = self._make_element_inner_weight_gradient(space)
self.element_outer_weight = self._make_element_outer_weight(space)
self.element_outer_weight_gradient = self._make_element_outer_weight_gradient(space)
@wp.func
def node_coords_in_element(
args: Grid2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_element: int,
):
if node_index_in_element == 0:
return Coords(0.5, 0.0, 0.0)
elif node_index_in_element == 1:
return Coords(0.5, 0.0, 0.0)
return Coords(OUTSIDE)
@wp.func
def node_quadrature_weight(
args: Grid2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return 1.0
def trace(self):
return GridPiecewiseConstantSpace.Trace(self)
class GridBipolynomialShapeFunctions:
def __init__(self, degree: int, family: Polynomial):
self.family = family
self.ORDER = wp.constant(degree)
self.NODES_PER_ELEMENT = wp.constant((degree + 1) * (degree + 1))
self.NODES_PER_SIDE = wp.constant(degree + 1)
lobatto_coords, lobatto_weight = quadrature_1d(point_count=degree + 1, family=family)
lagrange_scale = lagrange_scales(lobatto_coords)
NodeVec = wp.types.vector(length=degree + 1, dtype=wp.float32)
self.LOBATTO_COORDS = wp.constant(NodeVec(lobatto_coords))
self.LOBATTO_WEIGHT = wp.constant(NodeVec(lobatto_weight))
self.LAGRANGE_SCALE = wp.constant(NodeVec(lagrange_scale))
@property
def name(self) -> str:
return f"{self.family}_{self.ORDER}"
def make_node_coords_in_element(self):
ORDER = self.ORDER
LOBATTO_COORDS = self.LOBATTO_COORDS
def node_coords_in_element(
args: Grid2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
node_i = node_index_in_elt // (ORDER + 1)
node_j = node_index_in_elt - (ORDER + 1) * node_i
return Coords(LOBATTO_COORDS[node_i], LOBATTO_COORDS[node_j], 0.0)
from warp.fem import cache
return cache.get_func(node_coords_in_element, self.name)
def make_node_quadrature_weight(self):
ORDER = self.ORDER
LOBATTO_WEIGHT = self.LOBATTO_WEIGHT
def node_quadrature_weight(
args: Grid2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
node_i = node_index_in_elt // (ORDER + 1)
node_j = node_index_in_elt - (ORDER + 1) * node_i
return LOBATTO_WEIGHT[node_i] * LOBATTO_WEIGHT[node_j]
def node_quadrature_weight_linear(
args: Grid2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return 0.25
from warp.fem import cache
if ORDER == 1:
return cache.get_func(node_quadrature_weight_linear, self.name)
return cache.get_func(node_quadrature_weight, self.name)
def make_trace_node_quadrature_weight(self):
ORDER = self.ORDER
NODES_PER_ELEMENT = self.NODES_PER_ELEMENT
LOBATTO_WEIGHT = self.LOBATTO_WEIGHT
def trace_node_quadrature_weight(
args: Grid2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
if node_index_in_elt >= NODES_PER_ELEMENT:
node_index_in_cell = node_index_in_elt - NODES_PER_ELEMENT
else:
node_index_in_cell = node_index_in_elt
# We're either on a side interior or at a vertex
# I.e., either both indices are at extrema, or only one is
# Pick the interior one if possible, if both are at extrema pick any one
node_i = node_index_in_cell // (ORDER + 1)
if node_i > 0 and node_i < ORDER:
return LOBATTO_WEIGHT[node_i]
node_j = node_index_in_cell - (ORDER + 1) * node_i
return LOBATTO_WEIGHT[node_j]
def trace_node_quadrature_weight_linear(
args: Grid2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return 0.5
from warp.fem import cache
if ORDER == 1:
return cache.get_func(trace_node_quadrature_weight_linear, self.name)
return cache.get_func(trace_node_quadrature_weight, self.name)
def make_element_inner_weight(self):
ORDER = self.ORDER
NODES_PER_ELEMENT = self.NODES_PER_ELEMENT
LOBATTO_COORDS = self.LOBATTO_COORDS
LAGRANGE_SCALE = self.LAGRANGE_SCALE
def element_inner_weight(
args: Grid2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
if node_index_in_elt < 0 or node_index_in_elt >= NODES_PER_ELEMENT:
return 0.0
node_i = node_index_in_elt // (ORDER + 1)
node_j = node_index_in_elt - (ORDER + 1) * node_i
w = float(1.0)
for k in range(ORDER + 1):
if k != node_i:
w *= coords[0] - LOBATTO_COORDS[k]
if k != node_j:
w *= coords[1] - LOBATTO_COORDS[k]
w *= LAGRANGE_SCALE[node_i] * LAGRANGE_SCALE[node_j]
return w
def element_inner_weight_linear(
args: Grid2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
if node_index_in_elt < 0 or node_index_in_elt >= 4:
return 0.0
v = Grid2DFunctionSpace._vertex_coords_f(node_index_in_elt)
wx = (1.0 - coords[0]) * (1.0 - v[0]) + v[0] * coords[0]
wy = (1.0 - coords[1]) * (1.0 - v[1]) + v[1] * coords[1]
return wx * wy
from warp.fem import cache
if ORDER == 1:
return cache.get_func(element_inner_weight_linear, self.name)
return cache.get_func(element_inner_weight, self.name)
def make_element_inner_weight_gradient(self):
ORDER = self.ORDER
NODES_PER_ELEMENT = self.NODES_PER_ELEMENT
LOBATTO_COORDS = self.LOBATTO_COORDS
LAGRANGE_SCALE = self.LAGRANGE_SCALE
def element_inner_weight_gradient(
args: Grid2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
if node_index_in_elt < 0 or node_index_in_elt >= NODES_PER_ELEMENT:
return wp.vec2(0.0)
node_i = node_index_in_elt // (ORDER + 1)
node_j = node_index_in_elt - (ORDER + 1) * node_i
prefix_x = float(1.0)
prefix_y = float(1.0)
for k in range(ORDER + 1):
if k != node_i:
prefix_y *= coords[0] - LOBATTO_COORDS[k]
if k != node_j:
prefix_x *= coords[1] - LOBATTO_COORDS[k]
grad_x = float(0.0)
grad_y = float(0.0)
for k in range(ORDER + 1):
if k != node_i:
delta_x = coords[0] - LOBATTO_COORDS[k]
grad_x = grad_x * delta_x + prefix_x
prefix_x *= delta_x
if k != node_j:
delta_y = coords[1] - LOBATTO_COORDS[k]
grad_y = grad_y * delta_y + prefix_y
prefix_y *= delta_y
grad = (
LAGRANGE_SCALE[node_i]
* LAGRANGE_SCALE[node_j]
* wp.vec2(grad_x * args.inv_cell_size[0], grad_y * args.inv_cell_size[1])
)
return grad
def element_inner_weight_gradient_linear(
args: Grid2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
if node_index_in_elt < 0 or node_index_in_elt >= 4:
return wp.vec2(0.0)
v = Grid2DFunctionSpace._vertex_coords_f(node_index_in_elt)
wx = (1.0 - coords[0]) * (1.0 - v[0]) + v[0] * coords[0]
wy = (1.0 - coords[1]) * (1.0 - v[1]) + v[1] * coords[1]
dx = (2.0 * v[0] - 1.0) * args.inv_cell_size[0]
dy = (2.0 * v[1] - 1.0) * args.inv_cell_size[1]
return wp.vec2(dx * wy, dy * wx)
from warp.fem import cache
if ORDER == 1:
return cache.get_func(element_inner_weight_gradient_linear, self.name)
return cache.get_func(element_inner_weight_gradient, self.name)
class GridBipolynomialSpace(Grid2DFunctionSpace):
def __init__(
self,
grid: Grid2D,
degree: int,
family: int,
dtype: type = float,
dof_mapper: DofMapper = None,
):
super().__init__(grid, dtype, dof_mapper)
if family is None:
family = Polynomial.LOBATTO_GAUSS_LEGENDRE
if not is_closed(family):
raise ValueError("A closed polynomial family is required to defined a continuous funciton space")
self._shape = GridBipolynomialShapeFunctions(degree, family=family)
self.ORDER = self._shape.ORDER
self.NODES_PER_ELEMENT = self._shape.NODES_PER_ELEMENT
self.element_node_index = self._make_element_node_index()
self.node_coords_in_element = self._shape.make_node_coords_in_element()
self.node_quadrature_weight = self._shape.make_node_quadrature_weight()
self.element_inner_weight = self._shape.make_element_inner_weight()
self.element_inner_weight_gradient = self._shape.make_element_inner_weight_gradient()
self.element_outer_weight = self.element_inner_weight
self.element_outer_weight_gradient = self.element_inner_weight_gradient
def node_count(self) -> int:
return (self._grid.res[0] * self.ORDER + 1) * (self._grid.res[1] * self.ORDER + 1)
def node_positions(self):
res = self._grid.res
cell_coords = np.array(self._shape.LOBATTO_COORDS)[:-1]
grid_coords_x = np.repeat(np.arange(0, res[0], dtype=float), len(cell_coords)) + np.tile(
cell_coords, reps=res[0]
)
grid_coords_x = np.append(grid_coords_x, res[0])
X = grid_coords_x * self._grid.cell_size[0] + self._grid.origin[0]
grid_coords_y = np.repeat(np.arange(0, res[1], dtype=float), len(cell_coords)) + np.tile(
cell_coords, reps=res[1]
)
grid_coords_y = np.append(grid_coords_y, res[1])
Y = grid_coords_y * self._grid.cell_size[1] + self._grid.origin[1]
return np.meshgrid(X, Y, indexing="ij")
def _make_element_node_index(self):
ORDER = self.ORDER
def element_node_index(
args: Grid2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
res = args.geo_arg.cell_arg.res
cell = Grid2D.get_cell(res, element_index)
node_i = node_index_in_elt // (ORDER + 1)
node_j = node_index_in_elt - (ORDER + 1) * node_i
node_x = ORDER * cell[0] + node_i
node_y = ORDER * cell[1] + node_j
node_pitch = (res[1] * ORDER) + 1
node_index = node_pitch * node_x + node_y
return node_index
from warp.fem import cache
return cache.get_func(element_node_index, f"{self.name}_{ORDER}")
class Trace(Grid2DFunctionSpace.Trace):
def __init__(self, space: "GridBipolynomialSpace"):
super().__init__(space)
self.element_node_index = self._make_element_node_index(space)
self.node_coords_in_element = self._make_node_coords_in_element(space)
self.node_quadrature_weight = space._shape.make_trace_node_quadrature_weight()
self.element_inner_weight = self._make_element_inner_weight(space)
self.element_inner_weight_gradient = self._make_element_inner_weight_gradient(space)
self.element_outer_weight = self._make_element_outer_weight(space)
self.element_outer_weight_gradient = self._make_element_outer_weight_gradient(space)
def trace(self):
return GridBipolynomialSpace.Trace(self)
class GridDGBipolynomialSpace(Grid2DFunctionSpace):
def __init__(
self,
grid: Grid2D,
degree: int,
family: Polynomial,
dtype: type = float,
dof_mapper: DofMapper = None,
):
super().__init__(grid, dtype, dof_mapper)
if family is None:
family = Polynomial.LOBATTO_GAUSS_LEGENDRE
self._shape = GridBipolynomialShapeFunctions(degree, family=family)
self.ORDER = self._shape.ORDER
self.NODES_PER_ELEMENT = self._shape.NODES_PER_ELEMENT
self.element_node_index = self._make_element_node_index()
self.node_coords_in_element = self._shape.make_node_coords_in_element()
self.node_quadrature_weight = self._shape.make_node_quadrature_weight()
self.element_inner_weight = self._shape.make_element_inner_weight()
self.element_inner_weight_gradient = self._shape.make_element_inner_weight_gradient()
self.element_outer_weight = self.element_inner_weight
self.element_outer_weight_gradient = self.element_inner_weight_gradient
def node_count(self) -> int:
return self._grid.cell_count() * (self.ORDER + 1) ** 2
def node_positions(self):
res = self._grid.res
cell_coords = np.array(self._shape.LOBATTO_COORDS)
grid_coords_x = np.repeat(np.arange(0, res[0], dtype=float), len(cell_coords)) + np.tile(
cell_coords, reps=res[0]
)
X = grid_coords_x * self._grid.cell_size[0] + self._grid.origin[0]
grid_coords_y = np.repeat(np.arange(0, res[1], dtype=float), len(cell_coords)) + np.tile(
cell_coords, reps=res[1]
)
Y = grid_coords_y * self._grid.cell_size[1] + self._grid.origin[1]
return np.meshgrid(X, Y, indexing="ij")
def _make_element_node_index(self):
NODES_PER_ELEMENT = self.NODES_PER_ELEMENT
def element_node_index(
args: Grid2DFunctionSpace.SpaceArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return element_index * NODES_PER_ELEMENT + node_index_in_elt
from warp.fem import cache
return cache.get_func(element_node_index, f"{self.name}_{self.ORDER}")
class Trace(GridBipolynomialSpace.Trace):
def __init__(self, space: "GridBipolynomialSpace"):
super().__init__(space)
def trace(self):
return GridDGBipolynomialSpace.Trace(self)
| warp-main | warp/fem/space/grid_2d_function_space.py |
from typing import Any
import warp as wp
from warp.fem.types import DofIndex, ElementIndex, Coords
from warp.fem import geometry
class FunctionSpace:
"""
Interface class for function spaces, i.e. geometry + interpolation basis
"""
DIMENSION: int
"""Input dimension of the function space"""
NODES_PER_ELEMENT: int
"""Number of interpolation nodes per element of the geometry"""
ORDER: int
"""Order of the interpolation basis"""
VALUE_DOF_COUNT: int
"""Number of degrees of freedom per node"""
dtype: type
"""Value type of the interpolation functions"""
SpaceArg: wp.codegen.Struct
"""Structure containing arguments to be passed to device function"""
def node_count(self) -> int:
"""Number of nodes in the interpolation basis"""
raise NotImplementedError
def node_positions(self) -> Any:
"""Node positions, for visualization purposes only"""
raise NotImplementedError
def geometry(self) -> geometry.Geometry:
"""Underlying geometry"""
raise NotImplementedError
def space_arg_value(self, device) -> wp.codegen.StructInstance:
"""Value of the arguments to be passed to device functions"""
raise NotImplementedError
@property
def name(self):
return self.__class__.__name__
@property
def degree(self):
return self.ORDER
def __str__(self):
return self.name
def trace(self):
"""Trace of the function space over lower-dimensional elements of the geometry"""
raise NotImplementedError
def make_field(self, space_partition=None, geometry_partition=None):
"""Returns a zero-initialized field over this function space"""
raise NotImplementedError
def unit_dof_value(args: Any, dof: DofIndex):
"""Unit value for a given degree of freedom. Typically a rank-1 tensor"""
raise NotImplementedError
def element_node_index(args: Any, element_index: ElementIndex, node_index_in_elt: int):
"""Global node index for a given node in a given element"""
raise NotImplementedError
def node_coords_in_element(args: Any, element_index: ElementIndex, node_index_in_elt: int):
"""Coordinates inside element of a given node"""
raise NotImplementedError
def element_inner_weight(args: Any, element_index: ElementIndex, coords: Coords, node_index_in_elt: int):
"""Inner weight for a node at given coordinates"""
raise NotImplementedError
def element_inner_weight_gradient(args: Any, element_index: ElementIndex, coords: Coords, node_index_in_elt: int):
"""Inner weight gradient for a node at given coordinates"""
raise NotImplementedError
def element_outer_weight(args: Any, element_index: ElementIndex, coords: Coords, node_index_in_elt: int):
"""Outer weight for a node at given coordinates"""
raise NotImplementedError
@wp.func
def element_outer_weight_gradient(args: Any, element_index: ElementIndex, coords: Coords, node_index_in_elt: int):
"""Outer weight gradient for a node at given coordinates"""
raise NotImplementedError
| warp-main | warp/fem/space/function_space.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
# include parent path
import numpy as np
import math
import warp as wp
from warp.tests.test_base import *
import unittest
wp.init()
@wp.kernel
def make_field(field: wp.array3d(dtype=float), center: wp.vec3, radius: float):
i, j, k = wp.tid()
p = wp.vec3(float(i), float(j), float(k))
d = wp.length(p - center) - radius
field[i, j, k] = d
def test_marching_cubes(test, device):
dim = 64
max_verts = 10**6
max_tris = 10**6
field = wp.zeros(shape=(dim, dim, dim), dtype=float, device=device)
iso = wp.MarchingCubes(nx=dim, ny=dim, nz=dim, max_verts=max_verts, max_tris=max_tris, device=device)
radius = dim / 4.0
wp.launch(make_field, dim=field.shape, inputs=[field, wp.vec3(dim / 2, dim / 2, dim / 2), radius], device="cuda")
iso.surface(field=field, threshold=0.0)
# check that all returned vertices lie on the surface of the sphere
length = np.linalg.norm(iso.verts.numpy() - np.array([dim / 2, dim / 2, dim / 2]), axis=1)
error = np.abs(length - radius)
test.assertTrue(np.max(error) < 1.0)
def register(parent):
devices = ["cuda"]
class TestMarchingCubes(parent):
pass
add_function_test(TestMarchingCubes, "test_marching_cubes", test_marching_cubes, devices=devices)
return TestMarchingCubes
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_marching_cubes.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import numpy as np
import warp as wp
from warp.tests.test_base import *
import unittest
wp.init()
@wp.kernel
def inc(a: wp.array(dtype=float)):
tid = wp.tid()
a[tid] = a[tid] + 1.0
@wp.kernel
def inc_new(src: wp.array(dtype=float), dst: wp.array(dtype=float)):
tid = wp.tid()
dst[tid] = src[tid] + 1.0
@wp.kernel
def sum(a: wp.array(dtype=float), b: wp.array(dtype=float), c: wp.array(dtype=float)):
tid = wp.tid()
c[tid] = a[tid] + b[tid]
# number of elements to use for testing
N = 10 * 1024 * 1024
def test_stream_arg_implicit_sync(test, device):
# wp.zeros() and array.numpy() should not require explicit sync
a = wp.zeros(N, dtype=float, device=device)
b = wp.empty(N, dtype=float, device=device)
c = wp.empty(N, dtype=float, device=device)
new_stream = wp.Stream(device)
# launch work on new stream
wp.launch(inc, dim=a.size, inputs=[a], stream=new_stream)
wp.copy(b, a, stream=new_stream)
wp.launch(inc, dim=a.size, inputs=[a], stream=new_stream)
wp.copy(c, a, stream=new_stream)
wp.launch(inc, dim=a.size, inputs=[a], stream=new_stream)
assert_np_equal(a.numpy(), np.full(N, fill_value=3.0))
assert_np_equal(b.numpy(), np.full(N, fill_value=1.0))
assert_np_equal(c.numpy(), np.full(N, fill_value=2.0))
def test_stream_scope_implicit_sync(test, device):
# wp.zeros() and array.numpy() should not require explicit sync
with wp.ScopedDevice(device):
a = wp.zeros(N, dtype=float)
b = wp.empty(N, dtype=float)
c = wp.empty(N, dtype=float)
old_stream = wp.get_stream()
new_stream = wp.Stream()
# launch work on new stream
with wp.ScopedStream(new_stream):
assert wp.get_stream() == new_stream
wp.launch(inc, dim=a.size, inputs=[a])
wp.copy(b, a)
wp.launch(inc, dim=a.size, inputs=[a])
wp.copy(c, a)
wp.launch(inc, dim=a.size, inputs=[a])
assert wp.get_stream() == old_stream
assert_np_equal(a.numpy(), np.full(N, fill_value=3.0))
assert_np_equal(b.numpy(), np.full(N, fill_value=1.0))
assert_np_equal(c.numpy(), np.full(N, fill_value=2.0))
def test_stream_arg_synchronize(test, device):
a = wp.zeros(N, dtype=float, device=device)
b = wp.empty(N, dtype=float, device=device)
c = wp.empty(N, dtype=float, device=device)
d = wp.empty(N, dtype=float, device=device)
stream1 = wp.get_stream(device)
stream2 = wp.Stream(device)
stream3 = wp.Stream(device)
wp.launch(inc, dim=N, inputs=[a], device=device)
# b and c depend on a
wp.synchronize_stream(stream1)
wp.launch(inc_new, dim=N, inputs=[a, b], stream=stream2)
wp.launch(inc_new, dim=N, inputs=[a, c], stream=stream3)
# d depends on b and c
wp.synchronize_stream(stream2)
wp.synchronize_stream(stream3)
wp.launch(sum, dim=N, inputs=[b, c, d], device=device)
assert_np_equal(a.numpy(), np.full(N, fill_value=1.0))
assert_np_equal(b.numpy(), np.full(N, fill_value=2.0))
assert_np_equal(c.numpy(), np.full(N, fill_value=2.0))
assert_np_equal(d.numpy(), np.full(N, fill_value=4.0))
def test_stream_arg_wait_event(test, device):
a = wp.zeros(N, dtype=float, device=device)
b = wp.empty(N, dtype=float, device=device)
c = wp.empty(N, dtype=float, device=device)
d = wp.empty(N, dtype=float, device=device)
stream1 = wp.get_stream(device)
stream2 = wp.Stream(device)
stream3 = wp.Stream(device)
event1 = wp.Event(device)
event2 = wp.Event(device)
event3 = wp.Event(device)
wp.launch(inc, dim=N, inputs=[a], stream=stream1)
stream1.record_event(event1)
# b and c depend on a
stream2.wait_event(event1)
stream3.wait_event(event1)
wp.launch(inc_new, dim=N, inputs=[a, b], stream=stream2)
stream2.record_event(event2)
wp.launch(inc_new, dim=N, inputs=[a, c], stream=stream3)
stream3.record_event(event3)
# d depends on b and c
stream1.wait_event(event2)
stream1.wait_event(event3)
wp.launch(sum, dim=N, inputs=[b, c, d], stream=stream1)
assert_np_equal(a.numpy(), np.full(N, fill_value=1.0))
assert_np_equal(b.numpy(), np.full(N, fill_value=2.0))
assert_np_equal(c.numpy(), np.full(N, fill_value=2.0))
assert_np_equal(d.numpy(), np.full(N, fill_value=4.0))
def test_stream_arg_wait_stream(test, device):
a = wp.zeros(N, dtype=float, device=device)
b = wp.empty(N, dtype=float, device=device)
c = wp.empty(N, dtype=float, device=device)
d = wp.empty(N, dtype=float, device=device)
stream1 = wp.get_stream(device)
stream2 = wp.Stream(device)
stream3 = wp.Stream(device)
wp.launch(inc, dim=N, inputs=[a], stream=stream1)
# b and c depend on a
stream2.wait_stream(stream1)
stream3.wait_stream(stream1)
wp.launch(inc_new, dim=N, inputs=[a, b], stream=stream2)
wp.launch(inc_new, dim=N, inputs=[a, c], stream=stream3)
# d depends on b and c
stream1.wait_stream(stream2)
stream1.wait_stream(stream3)
wp.launch(sum, dim=N, inputs=[b, c, d], stream=stream1)
assert_np_equal(a.numpy(), np.full(N, fill_value=1.0))
assert_np_equal(b.numpy(), np.full(N, fill_value=2.0))
assert_np_equal(c.numpy(), np.full(N, fill_value=2.0))
assert_np_equal(d.numpy(), np.full(N, fill_value=4.0))
def test_stream_scope_synchronize(test, device):
with wp.ScopedDevice(device):
a = wp.zeros(N, dtype=float)
b = wp.empty(N, dtype=float)
c = wp.empty(N, dtype=float)
d = wp.empty(N, dtype=float)
stream2 = wp.Stream()
stream3 = wp.Stream()
wp.launch(inc, dim=N, inputs=[a])
# b and c depend on a
wp.synchronize_stream()
with wp.ScopedStream(stream2):
wp.launch(inc_new, dim=N, inputs=[a, b])
with wp.ScopedStream(stream3):
wp.launch(inc_new, dim=N, inputs=[a, c])
# d depends on b and c
wp.synchronize_stream(stream2)
wp.synchronize_stream(stream3)
wp.launch(sum, dim=N, inputs=[b, c, d])
assert_np_equal(a.numpy(), np.full(N, fill_value=1.0))
assert_np_equal(b.numpy(), np.full(N, fill_value=2.0))
assert_np_equal(c.numpy(), np.full(N, fill_value=2.0))
assert_np_equal(d.numpy(), np.full(N, fill_value=4.0))
def test_stream_scope_wait_event(test, device):
with wp.ScopedDevice(device):
a = wp.zeros(N, dtype=float)
b = wp.empty(N, dtype=float)
c = wp.empty(N, dtype=float)
d = wp.empty(N, dtype=float)
stream2 = wp.Stream()
stream3 = wp.Stream()
event1 = wp.Event()
event2 = wp.Event()
event3 = wp.Event()
wp.launch(inc, dim=N, inputs=[a])
wp.record_event(event1)
# b and c depend on a
with wp.ScopedStream(stream2):
wp.wait_event(event1)
wp.launch(inc_new, dim=N, inputs=[a, b])
wp.record_event(event2)
with wp.ScopedStream(stream3):
wp.wait_event(event1)
wp.launch(inc_new, dim=N, inputs=[a, c])
wp.record_event(event3)
# d depends on b and c
wp.wait_event(event2)
wp.wait_event(event3)
wp.launch(sum, dim=N, inputs=[b, c, d])
assert_np_equal(a.numpy(), np.full(N, fill_value=1.0))
assert_np_equal(b.numpy(), np.full(N, fill_value=2.0))
assert_np_equal(c.numpy(), np.full(N, fill_value=2.0))
assert_np_equal(d.numpy(), np.full(N, fill_value=4.0))
def test_stream_scope_wait_stream(test, device):
with wp.ScopedDevice(device):
a = wp.zeros(N, dtype=float)
b = wp.empty(N, dtype=float)
c = wp.empty(N, dtype=float)
d = wp.empty(N, dtype=float)
stream1 = wp.get_stream()
stream2 = wp.Stream()
stream3 = wp.Stream()
wp.launch(inc, dim=N, inputs=[a])
# b and c depend on a
with wp.ScopedStream(stream2):
wp.wait_stream(stream1)
wp.launch(inc_new, dim=N, inputs=[a, b])
with wp.ScopedStream(stream3):
wp.wait_stream(stream1)
wp.launch(inc_new, dim=N, inputs=[a, c])
# d depends on b and c
wp.wait_stream(stream2)
wp.wait_stream(stream3)
wp.launch(sum, dim=N, inputs=[b, c, d])
assert_np_equal(a.numpy(), np.full(N, fill_value=1.0))
assert_np_equal(b.numpy(), np.full(N, fill_value=2.0))
assert_np_equal(c.numpy(), np.full(N, fill_value=2.0))
assert_np_equal(d.numpy(), np.full(N, fill_value=4.0))
def test_stream_arg_graph_mgpu(test, device):
# resources on GPU 0
stream0 = wp.get_stream("cuda:0")
a0 = wp.zeros(N, dtype=float, device="cuda:0")
b0 = wp.empty(N, dtype=float, device="cuda:0")
c0 = wp.empty(N, dtype=float, device="cuda:0")
# resources on GPU 1
stream1 = wp.get_stream("cuda:1")
a1 = wp.zeros(N, dtype=float, device="cuda:1")
# start recording on stream0
wp.capture_begin(stream=stream0)
# branch into stream1
stream1.wait_stream(stream0)
# launch concurrent kernels on each stream
wp.launch(inc, dim=N, inputs=[a0], stream=stream0)
wp.launch(inc, dim=N, inputs=[a1], stream=stream1)
# wait for stream1 to finish
stream0.wait_stream(stream1)
# copy values from stream1
wp.copy(b0, a1, stream=stream0)
# compute sum
wp.launch(sum, dim=N, inputs=[a0, b0, c0], stream=stream0)
# finish recording on stream0
g = wp.capture_end(stream=stream0)
# replay
num_iters = 10
for _ in range(num_iters):
wp.capture_launch(g, stream=stream0)
# check results
assert_np_equal(c0.numpy(), np.full(N, fill_value=2 * num_iters))
def test_stream_scope_graph_mgpu(test, device):
# resources on GPU 0
with wp.ScopedDevice("cuda:0"):
stream0 = wp.get_stream()
a0 = wp.zeros(N, dtype=float)
b0 = wp.empty(N, dtype=float)
c0 = wp.empty(N, dtype=float)
# resources on GPU 1
with wp.ScopedDevice("cuda:1"):
stream1 = wp.get_stream()
a1 = wp.zeros(N, dtype=float)
# capture graph
with wp.ScopedDevice("cuda:0"):
# start recording
wp.capture_begin()
with wp.ScopedDevice("cuda:1"):
# branch into stream1
wp.wait_stream(stream0)
wp.launch(inc, dim=N, inputs=[a1])
wp.launch(inc, dim=N, inputs=[a0])
# wait for stream1 to finish
wp.wait_stream(stream1)
# copy values from stream1
wp.copy(b0, a1)
# compute sum
wp.launch(sum, dim=N, inputs=[a0, b0, c0])
# finish recording
g = wp.capture_end()
# replay
with wp.ScopedDevice("cuda:0"):
num_iters = 10
for _ in range(num_iters):
wp.capture_launch(g)
# check results
assert_np_equal(c0.numpy(), np.full(N, fill_value=2 * num_iters))
def register(parent):
devices = wp.get_cuda_devices()
class TestStreams(parent):
pass
add_function_test(TestStreams, "test_stream_arg_implicit_sync", test_stream_arg_implicit_sync, devices=devices)
add_function_test(TestStreams, "test_stream_scope_implicit_sync", test_stream_scope_implicit_sync, devices=devices)
add_function_test(TestStreams, "test_stream_arg_synchronize", test_stream_arg_synchronize, devices=devices)
add_function_test(TestStreams, "test_stream_arg_wait_event", test_stream_arg_wait_event, devices=devices)
add_function_test(TestStreams, "test_stream_arg_wait_stream", test_stream_arg_wait_stream, devices=devices)
add_function_test(TestStreams, "test_stream_scope_synchronize", test_stream_scope_synchronize, devices=devices)
add_function_test(TestStreams, "test_stream_scope_wait_event", test_stream_scope_wait_event, devices=devices)
add_function_test(TestStreams, "test_stream_scope_wait_stream", test_stream_scope_wait_stream, devices=devices)
if len(devices) > 1:
add_function_test(TestStreams, "test_stream_arg_graph_mgpu", test_stream_arg_graph_mgpu)
add_function_test(TestStreams, "test_stream_scope_graph_mgpu", test_stream_scope_graph_mgpu)
return TestStreams
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_streams.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import warp as wp
from warp.tests.test_base import *
import numpy as np
wp.init()
# float volume tests
@wp.kernel
def test_volume_lookup_f(volume: wp.uint64, points: wp.array(dtype=wp.vec3)):
tid = wp.tid()
p = points[tid]
expected = p[0] * p[1] * p[2]
if abs(p[0]) > 10.0 or abs(p[1]) > 10.0 or abs(p[2]) > 10.0:
expected = 10.0
i = int(p[0])
j = int(p[1])
k = int(p[2])
expect_eq(wp.volume_lookup_f(volume, i, j, k), expected)
@wp.kernel
def test_volume_sample_closest_f(volume: wp.uint64, points: wp.array(dtype=wp.vec3)):
tid = wp.tid()
p = points[tid]
i = round(p[0])
j = round(p[1])
k = round(p[2])
expected = i * j * k
if abs(i) > 10.0 or abs(j) > 10.0 or abs(k) > 10.0:
expected = 10.0
expect_eq(wp.volume_sample_f(volume, p, wp.Volume.CLOSEST), expected)
q = wp.volume_index_to_world(volume, p)
q_inv = wp.volume_world_to_index(volume, q)
expect_eq(p, q_inv)
@wp.kernel
def test_volume_sample_linear_f(volume: wp.uint64, points: wp.array(dtype=wp.vec3)):
tid = wp.tid()
p = points[tid]
expected = p[0] * p[1] * p[2]
if abs(p[0]) > 10.0 or abs(p[1]) > 10.0 or abs(p[2]) > 10.0:
return # not testing against background values
expect_near(wp.volume_sample_f(volume, p, wp.Volume.LINEAR), expected, 2.0e-4)
@wp.kernel
def test_volume_sample_grad_linear_f(volume: wp.uint64, points: wp.array(dtype=wp.vec3)):
tid = wp.tid()
p = points[tid]
expected_val = p[0] * p[1] * p[2]
expected_gx = p[1] * p[2]
expected_gy = p[0] * p[2]
expected_gz = p[0] * p[1]
if abs(p[0]) > 10.0 or abs(p[1]) > 10.0 or abs(p[2]) > 10.0:
return # not testing against background values
grad = wp.vec3(0.0, 0.0, 0.0)
val = wp.volume_sample_grad_f(volume, p, wp.Volume.LINEAR, grad)
expect_near(val, expected_val, 2.0e-4)
expect_near(grad[0], expected_gx, 2.0e-4)
expect_near(grad[1], expected_gy, 2.0e-4)
expect_near(grad[2], expected_gz, 2.0e-4)
@wp.kernel
def test_volume_sample_local_f_linear_values(
volume: wp.uint64, points: wp.array(dtype=wp.vec3), values: wp.array(dtype=wp.float32)
):
tid = wp.tid()
p = points[tid]
values[tid] = wp.volume_sample_f(volume, p, wp.Volume.LINEAR)
@wp.kernel
def test_volume_sample_grad_local_f_linear_values(
volume: wp.uint64, points: wp.array(dtype=wp.vec3), values: wp.array(dtype=wp.float32), case_num:int
):
tid = wp.tid()
p = points[tid]
grad = wp.vec3(0.0, 0.0, 0.0)
val = wp.volume_sample_grad_f(volume, p, wp.Volume.LINEAR, grad)
if case_num == 0:
values[tid] = val
elif case_num == 1:
values[tid] = grad[0]
elif case_num == 2:
values[tid] = grad[1]
elif case_num == 3:
values[tid] = grad[2]
@wp.kernel
def test_volume_sample_world_f_linear_values(
volume: wp.uint64, points: wp.array(dtype=wp.vec3), values: wp.array(dtype=wp.float32)
):
tid = wp.tid()
q = points[tid]
p = wp.volume_world_to_index(volume, q)
values[tid] = wp.volume_sample_f(volume, p, wp.Volume.LINEAR)
@wp.kernel
def test_volume_sample_grad_world_f_linear_values(
volume: wp.uint64, points: wp.array(dtype=wp.vec3), values: wp.array(dtype=wp.float32), case_num:int
):
tid = wp.tid()
q = points[tid]
p = wp.volume_world_to_index(volume, q)
grad = wp.vec3(0.0, 0.0, 0.0)
val = wp.volume_sample_grad_f(volume, p, wp.Volume.LINEAR, grad)
if case_num == 0:
values[tid] = val
elif case_num == 1:
values[tid] = grad[0]
elif case_num == 2:
values[tid] = grad[1]
elif case_num == 3:
values[tid] = grad[2]
# vec3f volume tests
@wp.kernel
def test_volume_lookup_v(volume: wp.uint64, points: wp.array(dtype=wp.vec3)):
tid = wp.tid()
p = points[tid]
expected = wp.vec3(
p[0] + 2.0 * p[1] + 3.0 * p[2], 4.0 * p[0] + 5.0 * p[1] + 6.0 * p[2], 7.0 * p[0] + 8.0 * p[1] + 9.0 * p[2]
)
if abs(p[0]) > 10.0 or abs(p[1]) > 10.0 or abs(p[2]) > 10.0:
expected = wp.vec3(10.8, -4.13, 10.26)
i = int(p[0])
j = int(p[1])
k = int(p[2])
expect_eq(wp.volume_lookup_v(volume, i, j, k), expected)
@wp.kernel
def test_volume_sample_closest_v(volume: wp.uint64, points: wp.array(dtype=wp.vec3)):
tid = wp.tid()
p = points[tid]
i = round(p[0])
j = round(p[1])
k = round(p[2])
expected = wp.vec3(i + 2.0 * j + 3.0 * k, 4.0 * i + 5.0 * j + 6.0 * k, 7.0 * i + 8.0 * j + 9.0 * k)
if abs(i) > 10.0 or abs(j) > 10.0 or abs(k) > 10.0:
expected = wp.vec3(10.8, -4.13, 10.26)
expect_eq(wp.volume_sample_v(volume, p, wp.Volume.CLOSEST), expected)
q = wp.volume_index_to_world(volume, p)
q_inv = wp.volume_world_to_index(volume, q)
expect_eq(p, q_inv)
@wp.kernel
def test_volume_sample_linear_v(volume: wp.uint64, points: wp.array(dtype=wp.vec3)):
tid = wp.tid()
p = points[tid]
expected = wp.vec3(
p[0] + 2.0 * p[1] + 3.0 * p[2], 4.0 * p[0] + 5.0 * p[1] + 6.0 * p[2], 7.0 * p[0] + 8.0 * p[1] + 9.0 * p[2]
)
if abs(p[0]) > 10.0 or abs(p[1]) > 10.0 or abs(p[2]) > 10.0:
return # not testing against background values
expect_near(wp.volume_sample_v(volume, p, wp.Volume.LINEAR), expected, 2.0e-4)
@wp.kernel
def test_volume_sample_local_v_linear_values(
volume: wp.uint64, points: wp.array(dtype=wp.vec3), values: wp.array(dtype=wp.float32)
):
tid = wp.tid()
p = points[tid]
ones = wp.vec3(1.0, 1.0, 1.0)
values[tid] = wp.dot(wp.volume_sample_v(volume, p, wp.Volume.LINEAR), ones)
@wp.kernel
def test_volume_sample_world_v_linear_values(
volume: wp.uint64, points: wp.array(dtype=wp.vec3), values: wp.array(dtype=wp.float32)
):
tid = wp.tid()
q = points[tid]
p = wp.volume_world_to_index(volume, q)
ones = wp.vec3(1.0, 1.0, 1.0)
values[tid] = wp.dot(wp.volume_sample_v(volume, p, wp.Volume.LINEAR), ones)
# int32 volume tests
@wp.kernel
def test_volume_lookup_i(volume: wp.uint64, points: wp.array(dtype=wp.vec3)):
tid = wp.tid()
p = points[tid]
i = int(p[0])
j = int(p[1])
k = int(p[2])
expected = i * j * k
if abs(i) > 10 or abs(j) > 10 or abs(k) > 10:
expected = 10
expect_eq(wp.volume_lookup_i(volume, i, j, k), expected)
@wp.kernel
def test_volume_sample_i(volume: wp.uint64, points: wp.array(dtype=wp.vec3)):
tid = wp.tid()
p = points[tid]
i = round(p[0])
j = round(p[1])
k = round(p[2])
expected = int(i * j * k)
if abs(i) > 10.0 or abs(j) > 10.0 or abs(k) > 10.0:
expected = 10
expect_eq(wp.volume_sample_i(volume, p), expected)
q = wp.volume_index_to_world(volume, p)
q_inv = wp.volume_world_to_index(volume, q)
expect_eq(p, q_inv)
# Index/world transformation tests
@wp.kernel
def test_volume_index_to_world(
volume: wp.uint64,
points: wp.array(dtype=wp.vec3),
values: wp.array(dtype=wp.float32),
grad_values: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
p = points[tid]
ones = wp.vec3(1.0, 1.0, 1.0)
values[tid] = wp.dot(wp.volume_index_to_world(volume, p), ones)
grad_values[tid] = wp.volume_index_to_world_dir(volume, ones)
@wp.kernel
def test_volume_world_to_index(
volume: wp.uint64,
points: wp.array(dtype=wp.vec3),
values: wp.array(dtype=wp.float32),
grad_values: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
p = points[tid]
ones = wp.vec3(1.0, 1.0, 1.0)
values[tid] = wp.dot(wp.volume_world_to_index(volume, p), ones)
grad_values[tid] = wp.volume_world_to_index_dir(volume, ones)
# Volume write tests
@wp.kernel
def test_volume_store_f(volume: wp.uint64, points: wp.array(dtype=wp.vec3), values: wp.array(dtype=wp.float32)):
tid = wp.tid()
p = points[tid]
i = int(p[0])
j = int(p[1])
k = int(p[2])
# NB: Writing outside the allocated domain overwrites the background value of the Volume
if abs(i) <= 11 and abs(j) <= 11 and abs(k) <= 11:
wp.volume_store_f(volume, i, j, k, float(i + 100 * j + 10000 * k))
values[tid] = wp.volume_lookup_f(volume, i, j, k)
@wp.kernel
def test_volume_store_v(volume: wp.uint64, points: wp.array(dtype=wp.vec3), values: wp.array(dtype=wp.vec3)):
tid = wp.tid()
p = points[tid]
i = int(p[0])
j = int(p[1])
k = int(p[2])
# NB: Writing outside the allocated domain overwrites the background value of the Volume
if abs(i) <= 11 and abs(j) <= 11 and abs(k) <= 11:
wp.volume_store_v(volume, i, j, k, p)
values[tid] = wp.volume_lookup_v(volume, i, j, k)
@wp.kernel
def test_volume_store_i(volume: wp.uint64, points: wp.array(dtype=wp.vec3), values: wp.array(dtype=wp.int32)):
tid = wp.tid()
p = points[tid]
i = int(p[0])
j = int(p[1])
k = int(p[2])
# NB: Writing outside the allocated domain overwrites the background value of the Volume
if abs(i) <= 11 and abs(j) <= 11 and abs(k) <= 11:
wp.volume_store_i(volume, i, j, k, i + 100 * j + 10000 * k)
values[tid] = wp.volume_lookup_i(volume, i, j, k)
def register(parent):
devices = get_test_devices()
rng = np.random.default_rng(101215)
# Note about the test grids:
# test_grid and test_int32_grid
# active region: [-10,10]^3
# values: v[i,j,k] = i * j * k
# voxel size: 0.25
#
# test_vec_grid
# active region: [-10,10]^3
# values: v[i,j,k] = (i + 2*j + 3*k, 4*i + 5*j + 6*k, 7*i + 8*j + 9*k)
# voxel size: 0.25
#
# torus
# index to world transformation:
# [0.1, 0, 0, 0]
# [0, 0, 0.1, 0]
# [0, 0.1, 0, 0]
# [1, 2, 3, 1]
# (-90 degrees rotation along X)
# voxel size: 0.1
volume_paths = {
"float": os.path.abspath(os.path.join(os.path.dirname(__file__), "assets/test_grid.nvdb")),
"int32": os.path.abspath(os.path.join(os.path.dirname(__file__), "assets/test_int32_grid.nvdb")),
"vec3f": os.path.abspath(os.path.join(os.path.dirname(__file__), "assets/test_vec_grid.nvdb")),
"torus": os.path.abspath(os.path.join(os.path.dirname(__file__), "assets/torus.nvdb")),
"float_write": os.path.abspath(os.path.join(os.path.dirname(__file__), "assets/test_grid.nvdb")),
}
test_volume_tiles = (
np.array([[i, j, k] for i in range(-2, 2) for j in range(-2, 2) for k in range(-2, 2)], dtype=np.int32) * 8
)
volumes = {}
points = {}
points_jittered = {}
for value_type, path in volume_paths.items():
volumes[value_type] = {}
volume_data = open(path, "rb").read()
for device in devices:
try:
volume = wp.Volume.load_from_nvdb(volume_data, device)
except RuntimeError as e:
raise RuntimeError(f'Failed to load volume from "{path}" to {device} memory:\n{e}')
volumes[value_type][device.alias] = volume
axis = np.linspace(-1, 1, 3)
point_grid = np.array([[x, y, z] for x in axis for y in axis for z in axis], dtype=np.float32)
class TestVolumes(parent):
def test_volume_sample_linear_f_gradient(self):
for device in devices:
points = rng.uniform(-10.0, 10.0, size=(100, 3))
values = wp.array(np.zeros(1), dtype=wp.float32, device=device, requires_grad=True)
for case in points:
uvws = wp.array(case, dtype=wp.vec3, device=device, requires_grad=True)
xyzs = wp.array(case * 0.25, dtype=wp.vec3, device=device, requires_grad=True)
tape = wp.Tape()
with tape:
wp.launch(
test_volume_sample_local_f_linear_values,
dim=1,
inputs=[volumes["float"][device.alias].id, uvws, values],
device=device,
)
tape.backward(values)
x, y, z = case
grad_expected = np.array([y * z, x * z, x * y])
grad_computed = tape.gradients[uvws].numpy()[0]
np.testing.assert_allclose(grad_computed, grad_expected, rtol=1e-4)
tape = wp.Tape()
with tape:
wp.launch(
test_volume_sample_world_f_linear_values,
dim=1,
inputs=[volumes["float"][device.alias].id, xyzs, values],
device=device,
)
tape.backward(values)
x, y, z = case
grad_expected = np.array([y * z, x * z, x * y]) / 0.25
grad_computed = tape.gradients[xyzs].numpy()[0]
np.testing.assert_allclose(grad_computed, grad_expected, rtol=1e-4)
def test_volume_sample_grad_linear_f_gradient(self):
for device in devices:
points = rng.uniform(-10.0, 10.0, size=(100, 3))
values = wp.array(np.zeros(1), dtype=wp.float32, device=device, requires_grad=True)
for case in points:
uvws = wp.array(case, dtype=wp.vec3, device=device, requires_grad=True)
xyzs = wp.array(case * 0.25, dtype=wp.vec3, device=device, requires_grad=True)
for case_num in range(4):
tape = wp.Tape()
with tape:
wp.launch(
test_volume_sample_grad_local_f_linear_values,
dim=1,
inputs=[volumes["float"][device.alias].id, uvws, values, case_num],
device=device,
)
tape.backward(values)
x, y, z = case
grad_computed = tape.gradients[uvws].numpy()[0]
if case_num == 0:
grad_expected = np.array([y * z, x * z, x * y])
elif case_num == 1:
grad_expected = np.array([0.0, z, y])
elif case_num == 2:
grad_expected = np.array([z, 0.0, x])
elif case_num == 3:
grad_expected = np.array([y, x, 0.0])
np.testing.assert_allclose(grad_computed, grad_expected, rtol=1e-4)
tape.zero()
for case_num in range(4):
tape = wp.Tape()
with tape:
wp.launch(
test_volume_sample_grad_world_f_linear_values,
dim=1,
inputs=[volumes["float"][device.alias].id, xyzs, values, case_num],
device=device,
)
tape.backward(values)
x, y, z = case
grad_computed = tape.gradients[xyzs].numpy()[0]
if case_num == 0:
grad_expected = np.array([y * z, x * z, x * y]) / 0.25
elif case_num == 1:
grad_expected = np.array([0.0, z, y]) / 0.25
elif case_num == 2:
grad_expected = np.array([z, 0.0, x]) / 0.25
elif case_num == 3:
grad_expected = np.array([y, x, 0.0]) / 0.25
np.testing.assert_allclose(grad_computed, grad_expected, rtol=1e-4)
tape.zero()
def test_volume_sample_linear_v_gradient(self):
for device in devices:
points = rng.uniform(-10.0, 10.0, size=(100, 3))
values = wp.zeros(1, dtype=wp.float32, device=device, requires_grad=True)
for case in points:
uvws = wp.array(case, dtype=wp.vec3, device=device, requires_grad=True)
xyzs = wp.array(case * 0.25, dtype=wp.vec3, device=device, requires_grad=True)
tape = wp.Tape()
with tape:
wp.launch(
test_volume_sample_local_v_linear_values,
dim=1,
inputs=[volumes["vec3f"][device.alias].id, uvws, values],
device=device,
)
tape.backward(values)
grad_expected = np.array([6.0, 15.0, 24.0])
grad_computed = tape.gradients[uvws].numpy()[0]
np.testing.assert_allclose(grad_computed, grad_expected, rtol=1e-4)
tape = wp.Tape()
with tape:
wp.launch(
test_volume_sample_world_v_linear_values,
dim=1,
inputs=[volumes["vec3f"][device.alias].id, xyzs, values],
device=device,
)
tape.backward(values)
grad_expected = np.array([6.0, 15.0, 24.0]) / 0.25
grad_computed = tape.gradients[xyzs].numpy()[0]
np.testing.assert_allclose(grad_computed, grad_expected, rtol=1e-4)
def test_volume_transform_gradient(self):
for device in devices:
values = wp.zeros(1, dtype=wp.float32, device=device, requires_grad=True)
grad_values = wp.zeros(1, dtype=wp.vec3, device=device)
points = rng.uniform(-10.0, 10.0, size=(10, 3))
for case in points:
points = wp.array(case, dtype=wp.vec3, device=device, requires_grad=True)
tape = wp.Tape()
with tape:
wp.launch(
test_volume_index_to_world,
dim=1,
inputs=[volumes["torus"][device.alias].id, points, values, grad_values],
device=device,
)
tape.backward(values)
grad_computed = tape.gradients[points].numpy()
grad_expected = grad_values.numpy()
np.testing.assert_allclose(grad_computed, grad_expected, rtol=1e-4)
grad_computed = tape.gradients[points].numpy()
grad_expected = grad_values.numpy()
np.testing.assert_allclose(grad_computed, grad_expected, rtol=1e-4)
def test_volume_store(self):
values_ref = np.array([x + 100 * y + 10000 * z for x, y, z in point_grid])
for device in devices:
points = wp.array(point_grid, dtype=wp.vec3, device=device)
values = wp.empty(len(point_grid), dtype=wp.float32, device=device)
wp.launch(
test_volume_store_f,
dim=len(point_grid),
inputs=[volumes["float_write"][device.alias].id, points, values],
device=device,
)
values_res = values.numpy()
np.testing.assert_equal(values_res, values_ref)
def test_volume_allocation_f(self):
bg_value = -123.0
points_np = np.append(point_grid, [[8096, 8096, 8096]], axis=0)
values_ref = np.append(np.array([x + 100 * y + 10000 * z for x, y, z in point_grid]), bg_value)
for device in devices:
if device.is_cpu:
continue
volume = wp.Volume.allocate(
min=[-11, -11, -11], max=[11, 11, 11], voxel_size=0.1, bg_value=bg_value, device=device
)
points = wp.array(points_np, dtype=wp.vec3, device=device)
values = wp.empty(len(points_np), dtype=wp.float32, device=device)
wp.launch(test_volume_store_f, dim=len(points_np), inputs=[volume.id, points, values], device=device)
values_res = values.numpy()
np.testing.assert_equal(values_res, values_ref)
def test_volume_allocation_v(self):
bg_value = (-1, 2.0, -3)
points_np = np.append(point_grid, [[8096, 8096, 8096]], axis=0)
values_ref = np.append(point_grid, [bg_value], axis=0)
for device in devices:
if device.is_cpu:
continue
volume = wp.Volume.allocate(
min=[-11, -11, -11], max=[11, 11, 11], voxel_size=0.1, bg_value=bg_value, device=device
)
points = wp.array(points_np, dtype=wp.vec3, device=device)
values = wp.empty(len(points_np), dtype=wp.vec3, device=device)
wp.launch(test_volume_store_v, dim=len(points_np), inputs=[volume.id, points, values], device=device)
values_res = values.numpy()
np.testing.assert_equal(values_res, values_ref)
def test_volume_allocation_i(self):
bg_value = -123
points_np = np.append(point_grid, [[8096, 8096, 8096]], axis=0)
values_ref = np.append(
np.array([x + 100 * y + 10000 * z for x, y, z in point_grid], dtype=np.int32), bg_value
)
for device in devices:
if device.is_cpu:
continue
volume = wp.Volume.allocate(
min=[-11, -11, -11], max=[11, 11, 11], voxel_size=0.1, bg_value=bg_value, device=device
)
points = wp.array(points_np, dtype=wp.vec3, device=device)
values = wp.empty(len(points_np), dtype=wp.int32, device=device)
wp.launch(test_volume_store_i, dim=len(points_np), inputs=[volume.id, points, values], device=device)
values_res = values.numpy()
np.testing.assert_equal(values_res, values_ref)
def test_volume_introspection(self):
for volume_names in ("float", "vec3f"):
for device in devices:
volume = volumes[volume_names][device.alias]
tiles_actual = volume.get_tiles().numpy()
tiles_sorted = tiles_actual[np.lexsort(tiles_actual.T[::-1])]
voxel_size = np.array(volume.get_voxel_size())
np.testing.assert_equal(test_volume_tiles, tiles_sorted)
np.testing.assert_equal([0.25] * 3, voxel_size)
for device in devices:
points_jittered_np = point_grid + rng.uniform(-0.5, 0.5, size=point_grid.shape)
points[device.alias] = wp.array(point_grid, dtype=wp.vec3, device=device)
points_jittered[device.alias] = wp.array(points_jittered_np, dtype=wp.vec3, device=device)
add_kernel_test(
TestVolumes,
test_volume_lookup_f,
dim=len(point_grid),
inputs=[volumes["float"][device.alias].id, points[device.alias]],
devices=[device],
)
add_kernel_test(
TestVolumes,
test_volume_sample_closest_f,
dim=len(point_grid),
inputs=[volumes["float"][device.alias].id, points_jittered[device.alias]],
devices=[device.alias],
)
add_kernel_test(
TestVolumes,
test_volume_sample_linear_f,
dim=len(point_grid),
inputs=[volumes["float"][device.alias].id, points_jittered[device.alias]],
devices=[device.alias],
)
add_kernel_test(
TestVolumes,
test_volume_sample_grad_linear_f,
dim=len(point_grid),
inputs=[volumes["float"][device.alias].id, points_jittered[device.alias]],
devices=[device.alias],
)
add_kernel_test(
TestVolumes,
test_volume_lookup_v,
dim=len(point_grid),
inputs=[volumes["vec3f"][device.alias].id, points[device.alias]],
devices=[device.alias],
)
add_kernel_test(
TestVolumes,
test_volume_sample_closest_v,
dim=len(point_grid),
inputs=[volumes["vec3f"][device.alias].id, points_jittered[device.alias]],
devices=[device.alias],
)
add_kernel_test(
TestVolumes,
test_volume_sample_linear_v,
dim=len(point_grid),
inputs=[volumes["vec3f"][device.alias].id, points_jittered[device.alias]],
devices=[device.alias],
)
add_kernel_test(
TestVolumes,
test_volume_lookup_i,
dim=len(point_grid),
inputs=[volumes["int32"][device.alias].id, points[device.alias]],
devices=[device.alias],
)
add_kernel_test(
TestVolumes,
test_volume_sample_i,
dim=len(point_grid),
inputs=[volumes["int32"][device.alias].id, points_jittered[device.alias]],
devices=[device.alias],
)
return TestVolumes
if __name__ == "__main__":
wp.force_load()
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_volume.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import warp as wp
from warp.tests.test_base import *
from warp.sim import ModelBuilder
import numpy as np
wp.init()
def register(parent):
class TestModel(parent):
def test_add_triangles(self):
pts = np.array(
[
[-0.00585869, 0.34189449, -1.17415233],
[-1.894547, 0.1788074, 0.9251329],
[-1.26141048, 0.16140787, 0.08823282],
[-0.08609255, -0.82722546, 0.65995427],
[0.78827592, -1.77375711, -0.55582718],
]
)
tris = np.array([[0, 3, 4], [0, 2, 3], [2, 1, 3], [1, 4, 3]])
builder1 = ModelBuilder()
builder2 = ModelBuilder()
for pt in pts:
builder1.add_particle(pt, [0.0, 0.0, 0.0], 1.0)
builder2.add_particle(pt, [0.0, 0.0, 0.0], 1.0)
# test add_triangle(s) with default arguments:
areas = builder2.add_triangles(tris[:, 0], tris[:, 1], tris[:, 2])
for i, t in enumerate(tris):
area = builder1.add_triangle(t[0], t[1], t[2])
self.assertAlmostEqual(area, areas[i], places=6)
# test add_triangle(s) with non default arguments:
tri_ke = np.random.randn(pts.shape[0])
tri_ka = np.random.randn(pts.shape[0])
tri_kd = np.random.randn(pts.shape[0])
tri_drag = np.random.randn(pts.shape[0])
tri_lift = np.random.randn(pts.shape[0])
for i, t in enumerate(tris):
builder1.add_triangle(
t[0],
t[1],
t[2],
tri_ke[i],
tri_ka[i],
tri_kd[i],
tri_drag[i],
tri_lift[i],
)
builder2.add_triangles(tris[:, 0], tris[:, 1], tris[:, 2], tri_ke, tri_ka, tri_kd, tri_drag, tri_lift)
assert_np_equal(np.array(builder1.tri_indices), np.array(builder2.tri_indices))
assert_np_equal(np.array(builder1.tri_poses), np.array(builder2.tri_poses), tol=1.0e-6)
assert_np_equal(np.array(builder1.tri_activations), np.array(builder2.tri_activations))
assert_np_equal(np.array(builder1.tri_materials), np.array(builder2.tri_materials))
def test_add_edges(self):
pts = np.array(
[
[-0.00585869, 0.34189449, -1.17415233],
[-1.894547, 0.1788074, 0.9251329],
[-1.26141048, 0.16140787, 0.08823282],
[-0.08609255, -0.82722546, 0.65995427],
[0.78827592, -1.77375711, -0.55582718],
]
)
edges = np.array([[0, 4, 3, 1], [3, 2, 4, 1]])
builder1 = ModelBuilder()
builder2 = ModelBuilder()
for pt in pts:
builder1.add_particle(pt, [0.0, 0.0, 0.0], 1.0)
builder2.add_particle(pt, [0.0, 0.0, 0.0], 1.0)
# test defaults:
for i in range(2):
builder1.add_edge(edges[i, 0], edges[i, 1], edges[i, 2], edges[i, 3])
builder2.add_edges(edges[:, 0], edges[:, 1], edges[:, 2], edges[:, 3])
# test non defaults:
rest = np.random.randn(2)
edge_ke = np.random.randn(2)
edge_kd = np.random.randn(2)
for i in range(2):
builder1.add_edge(edges[i, 0], edges[i, 1], edges[i, 2], edges[i, 3], rest[i], edge_ke[i], edge_kd[i])
builder2.add_edges(edges[:, 0], edges[:, 1], edges[:, 2], edges[:, 3], rest, edge_ke, edge_kd)
assert_np_equal(np.array(builder1.edge_indices), np.array(builder2.edge_indices))
assert_np_equal(np.array(builder1.edge_rest_angle), np.array(builder2.edge_rest_angle), tol=1.0e-4)
assert_np_equal(np.array(builder1.edge_bending_properties), np.array(builder2.edge_bending_properties))
return TestModel
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_model.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import numpy as np
import unittest
import warp as wp
from warp.tests.test_base import *
wp.init()
epsilon = 0.00001
@wp.kernel
def closest_point_edge_edge_kernel(
p1: wp.array(dtype=wp.vec3),
q1: wp.array(dtype=wp.vec3),
p2: wp.array(dtype=wp.vec3),
q2: wp.array(dtype=wp.vec3),
epsilon: float,
st0: wp.array(dtype=wp.vec3),
c1: wp.array(dtype=wp.vec3),
c2: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
st = wp.closest_point_edge_edge(p1[tid], q1[tid], p2[tid], q2[tid], epsilon)
s = st[0]
t = st[1]
st0[tid] = st
c1[tid] = p1[tid] + (q1[tid] - p1[tid]) * s
c2[tid] = p2[tid] + (q2[tid] - p2[tid]) * t
def closest_point_edge_edge_launch(p1, q1, p2, q2, epsilon, st0, c1, c2, device):
n = len(p1)
wp.launch(
kernel=closest_point_edge_edge_kernel,
dim=n,
inputs=[p1, q1, p2, q2, epsilon],
outputs=[st0, c1, c2],
device=device,
)
def run_closest_point_edge_edge(p1_h, q1_h, p2_h, q2_h, device):
p1 = wp.array(p1_h, dtype=wp.vec3, device=device)
q1 = wp.array(q1_h, dtype=wp.vec3, device=device)
p2 = wp.array(p2_h, dtype=wp.vec3, device=device)
q2 = wp.array(q2_h, dtype=wp.vec3, device=device)
st0 = wp.empty_like(p1)
c1 = wp.empty_like(p1)
c2 = wp.empty_like(p1)
closest_point_edge_edge_launch(p1, q1, p2, q2, epsilon, st0, c1, c2, device)
wp.synchronize()
view = st0.numpy()
return view
def test_edge_edge_middle_crossing(test, device):
p1_h = np.array([[0, 0, 0]])
q1_h = np.array([[1, 1, 0]])
p2_h = np.array([[0, 1, 0]])
q2_h = np.array([[1, 0, 0]])
res = run_closest_point_edge_edge(p1_h, q1_h, p2_h, q2_h, device)
st0 = res[0]
test.assertAlmostEqual(st0[0], 0.5) # s value
test.assertAlmostEqual(st0[1], 0.5) # t value
def test_edge_edge_parallel_s1_t0(test, device):
p1_h = np.array([[0, 0, 0]])
q1_h = np.array([[1, 1, 0]])
p2_h = np.array([[2, 2, 0]])
q2_h = np.array([[3, 3, 0]])
res = run_closest_point_edge_edge(p1_h, q1_h, p2_h, q2_h, device)
st0 = res[0]
test.assertAlmostEqual(st0[0], 1.0) # s value
test.assertAlmostEqual(st0[1], 0.0) # t value
def test_edge_edge_parallel_s0_t1(test, device):
p1_h = np.array([[0, 0, 0]])
q1_h = np.array([[1, 1, 0]])
p2_h = np.array([[-2, -2, 0]])
q2_h = np.array([[-1, -1, 0]])
res = run_closest_point_edge_edge(p1_h, q1_h, p2_h, q2_h, device)
st0 = res[0]
test.assertAlmostEqual(st0[0], 0.0) # s value
test.assertAlmostEqual(st0[1], 1.0) # t value
def test_edge_edge_both_degenerate_case(test, device):
p1_h = np.array([[0, 0, 0]])
q1_h = np.array([[0, 0, 0]])
p2_h = np.array([[1, 1, 1]])
q2_h = np.array([[1, 1, 1]])
res = run_closest_point_edge_edge(p1_h, q1_h, p2_h, q2_h, device)
st0 = res[0]
test.assertAlmostEqual(st0[0], 0.0) # s value
test.assertAlmostEqual(st0[1], 0.0) # t value
def test_edge_edge_degenerate_first_edge(test, device):
p1_h = np.array([[0, 0, 0]])
q1_h = np.array([[0, 0, 0]])
p2_h = np.array([[0, 1, 0]])
q2_h = np.array([[1, 0, 0]])
res = run_closest_point_edge_edge(p1_h, q1_h, p2_h, q2_h, device)
st0 = res[0]
test.assertAlmostEqual(st0[0], 0.0) # s value
test.assertAlmostEqual(st0[1], 0.5) # t value
def test_edge_edge_degenerate_second_edge(test, device):
p1_h = np.array([[1, 0, 0]])
q1_h = np.array([[0, 1, 0]])
p2_h = np.array([[1, 1, 0]])
q2_h = np.array([[1, 1, 0]])
res = run_closest_point_edge_edge(p1_h, q1_h, p2_h, q2_h, device)
st0 = res[0]
test.assertAlmostEqual(st0[0], 0.5) # s value
test.assertAlmostEqual(st0[1], 0.0) # t value
def test_edge_edge_parallel(test, device):
p1_h = np.array([[0, 0, 0]])
q1_h = np.array([[1, 0, 0]])
p2_h = np.array([[-0.5, 1, 0]])
q2_h = np.array([[0.5, 1, 0]])
res = run_closest_point_edge_edge(p1_h, q1_h, p2_h, q2_h, device)
st0 = res[0]
test.assertAlmostEqual(st0[0], 0.0) # s value
test.assertAlmostEqual(st0[1], 0.5) # t value
def test_edge_edge_perpendicular_s1_t0(test, device):
p1_h = np.array([[0, 0, 0]])
q1_h = np.array([[1, 1, 0]])
p2_h = np.array([[10, 1, 0]])
q2_h = np.array([[11, 0, 0]])
res = run_closest_point_edge_edge(p1_h, q1_h, p2_h, q2_h, device)
st0 = res[0]
test.assertAlmostEqual(st0[0], 1.0) # s value
test.assertAlmostEqual(st0[1], 0.0) # t value
def test_edge_edge_perpendicular_s0_t1(test, device):
p1_h = np.array([[0, 0, 0]])
q1_h = np.array([[1, 1, 0]])
p2_h = np.array([[-11, -1, 0]])
q2_h = np.array([[-5, 0, 0]])
res = run_closest_point_edge_edge(p1_h, q1_h, p2_h, q2_h, device)
st0 = res[0]
test.assertAlmostEqual(st0[0], 0.0) # s value
test.assertAlmostEqual(st0[1], 1.0) # t value
def register(parent):
devices = get_test_devices()
class TestClosestPointEdgeEdgeMethods(parent):
pass
add_function_test(
TestClosestPointEdgeEdgeMethods,
"test_edge_edge_middle_crossing",
test_edge_edge_middle_crossing,
devices=devices,
)
add_function_test(
TestClosestPointEdgeEdgeMethods, "test_edge_edge_parallel_s1_t0", test_edge_edge_parallel_s1_t0, devices=devices
)
add_function_test(
TestClosestPointEdgeEdgeMethods, "test_edge_edge_parallel_s0_t1", test_edge_edge_parallel_s0_t1, devices=devices
)
add_function_test(
TestClosestPointEdgeEdgeMethods,
"test_edge_edge_both_degenerate_case",
test_edge_edge_both_degenerate_case,
devices=devices,
)
add_function_test(
TestClosestPointEdgeEdgeMethods,
"test_edge_edge_degenerate_first_edge",
test_edge_edge_degenerate_first_edge,
devices=devices,
)
add_function_test(
TestClosestPointEdgeEdgeMethods,
"test_edge_edge_degenerate_second_edge",
test_edge_edge_degenerate_second_edge,
devices=devices,
)
add_function_test(
TestClosestPointEdgeEdgeMethods, "test_edge_edge_parallel", test_edge_edge_parallel, devices=devices
)
add_function_test(
TestClosestPointEdgeEdgeMethods,
"test_edge_edge_perpendicular_s1_t0",
test_edge_edge_perpendicular_s1_t0,
devices=devices,
)
add_function_test(
TestClosestPointEdgeEdgeMethods,
"test_edge_edge_perpendicular_s0_t1",
test_edge_edge_perpendicular_s0_t1,
devices=devices,
)
return TestClosestPointEdgeEdgeMethods
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_closest_point_edge_edge.py |
# This file is used to test reloading module references.
import warp as wp
import warp.tests.test_reference_reference as refref
wp.init()
@wp.func
def magic():
return 2.0 * refref.more_magic()
| warp-main | warp/tests/test_reference.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
from dataclasses import dataclass
from typing import Any
import unittest
import numpy as np
import warp as wp
from warp.tests.test_base import *
@dataclass
class TestData:
a: Any
b: Any
t: float
expected: Any
expected_adj_a: Any = None
expected_adj_b: Any = None
expected_adj_t: float = None
def check_backwards(self):
return self.expected_adj_a is not None and self.expected_adj_b is not None and self.expected_adj_t is not None
TEST_DATA = {
wp.float32: (
TestData(
a=1.0,
b=5.0,
t=0.75,
expected=4.0,
expected_adj_a=0.25,
expected_adj_b=0.75,
expected_adj_t=4.0,
),
TestData(
a=-2.0,
b=5.0,
t=0.25,
expected=-0.25,
expected_adj_a=0.75,
expected_adj_b=0.25,
expected_adj_t=7.0,
),
TestData(
a=1.23,
b=2.34,
t=0.5,
expected=1.785,
expected_adj_a=0.5,
expected_adj_b=0.5,
expected_adj_t=1.11,
),
),
wp.vec2: (
TestData(
a=[1, 2],
b=[3, 4],
t=0.5,
expected=[2, 3],
),
),
wp.vec3: (
TestData(
a=[1, 2, 3],
b=[3, 4, 5],
t=0.5,
expected=[2, 3, 4],
),
),
wp.vec4: (
TestData(
a=[1, 2, 3, 4],
b=[3, 4, 5, 6],
t=0.5,
expected=[2, 3, 4, 5],
),
),
wp.mat22: (
TestData(
a=[[1, 2], [2, 1]],
b=[[3, 4], [4, 3]],
t=0.5,
expected=[[2, 3], [3, 2]],
),
),
wp.mat33: (
TestData(
a=[[1, 2, 3], [3, 1, 2], [2, 3, 1]],
b=[[3, 4, 5], [5, 3, 4], [4, 5, 3]],
t=0.5,
expected=[[2, 3, 4], [4, 2, 3], [3, 4, 2]],
),
),
wp.mat44: (
TestData(
a=[[1, 2, 3, 4], [4, 1, 2, 3], [3, 4, 1, 2], [2, 3, 4, 1]],
b=[[3, 4, 5, 6], [6, 3, 4, 5], [5, 6, 3, 4], [4, 5, 6, 3]],
t=0.5,
expected=[[2, 3, 4, 5], [5, 2, 3, 4], [4, 5, 2, 3], [3, 4, 5, 2]],
),
),
wp.quat: (
TestData(
a=[1, 2, 3, 4],
b=[3, 4, 5, 6],
t=0.5,
expected=[2, 3, 4, 5],
),
),
wp.transform: (
TestData(
a=[1, 2, 3, 4, 5, 6, 7],
b=[3, 4, 5, 6, 7, 8, 9],
t=0.5,
expected=[2, 3, 4, 5, 6, 7, 8],
),
),
wp.spatial_vector: (
TestData(
a=[1, 2, 3, 4, 5, 6],
b=[3, 4, 5, 6, 7, 8],
t=0.5,
expected=[2, 3, 4, 5, 6, 7],
),
),
wp.spatial_matrix: (
TestData(
a=[
[1, 2, 3, 4, 5, 6],
[6, 1, 2, 3, 4, 5],
[5, 6, 1, 2, 3, 4],
[4, 5, 6, 1, 2, 3],
[3, 4, 5, 6, 1, 2],
[2, 3, 4, 5, 6, 1],
],
b=[
[3, 4, 5, 6, 7, 8],
[8, 3, 4, 5, 6, 7],
[7, 8, 3, 4, 5, 6],
[6, 7, 8, 3, 4, 5],
[5, 6, 7, 8, 3, 4],
[4, 5, 6, 7, 8, 3],
],
t=0.5,
expected=[
[2, 3, 4, 5, 6, 7],
[7, 2, 3, 4, 5, 6],
[6, 7, 2, 3, 4, 5],
[5, 6, 7, 2, 3, 4],
[4, 5, 6, 7, 2, 3],
[3, 4, 5, 6, 7, 2],
],
),
),
}
wp.init()
def test_lerp(test, device):
def make_kernel_fn(data_type):
def fn(
a: wp.array(dtype=data_type),
b: wp.array(dtype=data_type),
t: wp.array(dtype=float),
out: wp.array(dtype=data_type),
):
out[0] = wp.lerp(a[0], b[0], t[0])
return fn
for data_type in TEST_DATA:
kernel_fn = make_kernel_fn(data_type)
module = wp.get_module(kernel_fn.__module__)
kernel = wp.Kernel(
func=kernel_fn,
key=f"test_lerp_{data_type.__name__}_kernel",
module=module,
)
for test_data in TEST_DATA[data_type]:
a = wp.array(
[test_data.a],
dtype=data_type,
device=device,
requires_grad=True,
)
b = wp.array(
[test_data.b],
dtype=data_type,
device=device,
requires_grad=True,
)
t = wp.array(
[test_data.t],
dtype=float,
device=device,
requires_grad=True,
)
out = wp.array(
[0] * wp.types.type_length(data_type),
dtype=data_type,
device=device,
requires_grad=True,
)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[a, b, t, out],
device=device,
)
assert_np_equal(
out.numpy(),
np.array([test_data.expected]),
tol=1e-6,
)
if test_data.check_backwards():
tape.backward(out)
assert_np_equal(
tape.gradients[a].numpy(),
np.array([test_data.expected_adj_a]),
tol=1e-6,
)
assert_np_equal(
tape.gradients[b].numpy(),
np.array([test_data.expected_adj_b]),
tol=1e-6,
)
assert_np_equal(
tape.gradients[t].numpy(),
np.array([test_data.expected_adj_t]),
tol=1e-6,
)
def register(parent):
devices = get_test_devices()
class TestLerp(parent):
pass
add_function_test(TestLerp, "test_lerp", test_lerp, devices=devices)
return TestLerp
if __name__ == "__main__":
_ = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_lerp.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import unittest
# include parent path
import numpy as np
import warp as wp
from warp.tests.test_base import *
wp.init()
dim_x = wp.constant(2)
dim_y = wp.constant(2)
dim_z = wp.constant(2)
dim_w = wp.constant(2)
@wp.kernel
def kernel1d(a: wp.array(dtype=int, ndim=1)):
i = wp.tid()
wp.expect_eq(a[i], i)
@wp.kernel
def kernel2d(a: wp.array(dtype=int, ndim=2)):
i, j = wp.tid()
wp.expect_eq(a[i, j], i * dim_y + j)
@wp.kernel
def kernel3d(a: wp.array(dtype=int, ndim=3)):
i, j, k = wp.tid()
wp.expect_eq(a[i, j, k], i * dim_y * dim_z + j * dim_z + k)
@wp.kernel
def kernel4d(a: wp.array(dtype=int, ndim=4)):
i, j, k, l = wp.tid()
wp.expect_eq(a[i, j, k, l], i * dim_y * dim_z * dim_w + j * dim_z * dim_w + k * dim_w + l)
def test1d(test, device):
a = np.arange(0, dim_x).reshape(dim_x)
wp.launch(kernel1d, dim=a.shape, inputs=[wp.array(a, dtype=int, device=device)], device=device)
def test2d(test, device):
a = np.arange(0, dim_x * dim_y).reshape(dim_x, dim_y)
wp.launch(kernel2d, dim=a.shape, inputs=[wp.array(a, dtype=int, device=device)], device=device)
def test3d(test, device):
a = np.arange(0, dim_x * dim_y * dim_z).reshape(dim_x, dim_y, dim_z)
wp.launch(kernel3d, dim=a.shape, inputs=[wp.array(a, dtype=int, device=device)], device=device)
def test4d(test, device):
a = np.arange(0, dim_x * dim_y * dim_z * dim_w).reshape(dim_x, dim_y, dim_z, dim_w)
wp.launch(kernel4d, dim=a.shape, inputs=[wp.array(a, dtype=int, device=device)], device=device)
@wp.struct
class Params:
a: wp.array(dtype=int)
i: int
f: float
@wp.kernel
def kernel_cmd(params: Params, i: int, f: float, v: wp.vec3, m: wp.mat33, out: wp.array(dtype=int)):
tid = wp.tid()
wp.expect_eq(params.i, i)
wp.expect_eq(params.f, f)
wp.expect_eq(i, int(f))
wp.expect_eq(v[0], f)
wp.expect_eq(v[1], f)
wp.expect_eq(v[2], f)
wp.expect_eq(m[0, 0], f)
wp.expect_eq(m[1, 1], f)
wp.expect_eq(m[2, 2], f)
out[tid] = tid + i
def test_launch_cmd(test, device):
n = 1
ref = np.arange(0, n)
out = wp.zeros(n, dtype=int, device=device)
params = Params()
params.i = 1
params.f = 1.0
v = wp.vec3(params.f, params.f, params.f)
m = wp.mat33(params.f, 0.0, 0.0, 0.0, params.f, 0.0, 0.0, 0.0, params.f)
# standard launch
wp.launch(kernel_cmd, dim=n, inputs=[params, params.i, params.f, v, m, out], device=device)
assert_np_equal(out.numpy(), ref + params.i)
# cmd launch
out.zero_()
cmd = wp.launch(kernel_cmd, dim=n, inputs=[params, params.i, params.f, v, m, out], device=device, record_cmd=True)
cmd.launch()
assert_np_equal(out.numpy(), ref + params.i)
def test_launch_cmd_set_param(test, device):
n = 1
ref = np.arange(0, n)
params = Params()
v = wp.vec3()
m = wp.mat33()
cmd = wp.launch(kernel_cmd, dim=n, inputs=[params, 0, 0.0, v, m, None], device=device, record_cmd=True)
# cmd param modification
out = wp.zeros(n, dtype=int, device=device)
params.i = 13
params.f = 13.0
v = wp.vec3(params.f, params.f, params.f)
m = wp.mat33(params.f, 0.0, 0.0, 0.0, params.f, 0.0, 0.0, 0.0, params.f)
cmd.set_param_at_index(0, params)
cmd.set_param_at_index(1, params.i)
cmd.set_param_at_index(2, params.f)
cmd.set_param_at_index(3, v)
cmd.set_param_at_index(4, m)
cmd.set_param_by_name("out", out)
cmd.launch()
assert_np_equal(out.numpy(), ref + params.i)
# test changing params after launch directly
# because we now cache the ctypes object inside the wp.struct
# instance the command buffer will be automatically updated
params.i = 14
params.f = 14.0
v = wp.vec3(params.f, params.f, params.f)
m = wp.mat33(params.f, 0.0, 0.0, 0.0, params.f, 0.0, 0.0, 0.0, params.f)
# this is the line we explicitly leave out to
# ensure that param changes are reflected in the launch
# launch.set_param_at_index(0, params)
cmd.set_param_at_index(1, params.i)
cmd.set_param_at_index(2, params.f)
cmd.set_param_at_index(3, v)
cmd.set_param_at_index(4, m)
cmd.set_param_by_name("out", out)
cmd.launch()
assert_np_equal(out.numpy(), ref + params.i)
def test_launch_cmd_set_ctype(test, device):
n = 1
ref = np.arange(0, n)
params = Params()
v = wp.vec3()
m = wp.mat33()
cmd = wp.launch(kernel_cmd, dim=n, inputs=[params, 0, 0.0, v, m, None], device=device, record_cmd=True)
# cmd param modification
out = wp.zeros(n, dtype=int, device=device)
# cmd param modification
out.zero_()
params.i = 13
params.f = 13.0
v = wp.vec3(params.f, params.f, params.f)
m = wp.mat33(params.f, 0.0, 0.0, 0.0, params.f, 0.0, 0.0, 0.0, params.f)
cmd.set_param_at_index_from_ctype(0, params.__ctype__())
cmd.set_param_at_index_from_ctype(1, params.i)
cmd.set_param_at_index_from_ctype(2, params.f)
cmd.set_param_at_index_from_ctype(3, v)
cmd.set_param_at_index_from_ctype(4, m)
cmd.set_param_by_name_from_ctype("out", out.__ctype__())
cmd.launch()
assert_np_equal(out.numpy(), ref + params.i)
@wp.kernel
def arange(out: wp.array(dtype=int)):
tid = wp.tid()
out[tid] = tid
def test_launch_cmd_set_dim(test, device):
n = 10
ref = np.arange(0, n, dtype=int)
out = wp.zeros(n, dtype=int, device=device)
cmd = wp.launch(arange, dim=n, inputs=[out], device=device, record_cmd=True)
cmd.set_dim(5)
cmd.launch()
# check first half the array is filled while rest is still zero
assert_np_equal(out.numpy()[0:5], ref[0:5])
assert_np_equal(out.numpy()[5:], np.zeros(5))
out.zero_()
cmd.set_dim(10)
cmd.launch()
# check the whole array was filled
assert_np_equal(out.numpy(), ref)
def test_launch_cmd_empty(test, device):
n = 10
ref = np.arange(0, n, dtype=int)
out = wp.zeros(n, dtype=int, device=device)
cmd = wp.Launch(arange, device)
cmd.set_dim(5)
cmd.set_param_by_name("out", out)
cmd.launch()
# check first half the array is filled while rest is still zero
assert_np_equal(out.numpy()[0:5], ref[0:5])
assert_np_equal(out.numpy()[5:], np.zeros(5))
out.zero_()
cmd.set_dim(10)
cmd.launch()
# check the whole array was filled
assert_np_equal(out.numpy(), ref)
@wp.kernel
def kernel_mul(
values: wp.array(dtype=int),
coeff: int,
out: wp.array(dtype=int),
):
tid = wp.tid()
out[tid] = values[tid] * coeff
def test_launch_tuple_args(test, device):
values = wp.array(np.arange(0, 4), dtype=int, device=device)
coeff = 3
out = wp.empty_like(values)
wp.launch(
kernel_mul,
dim=len(values),
inputs=(
values,
coeff,
),
outputs=(out,),
device=device,
)
assert_np_equal(out.numpy(), np.array((0, 3, 6, 9)))
@wp.kernel
def conditional_sum(result: wp.array(dtype=wp.uint64)):
i, j, k = wp.tid()
if i == 0:
wp.atomic_add(result, 0, wp.uint64(1))
def test_launch_large_kernel(test, device):
"""Test tid() on kernel launch of 2**33 threads.
The function conditional sum will add 1 to result for every thread that has an i index of 0.
Due to the size of the grid, this test is not run on CPUs
"""
test_result = wp.zeros(shape=(1,), dtype=wp.uint64, device=device)
large_dim_length = 2**16
half_result = large_dim_length * large_dim_length
wp.launch(kernel=conditional_sum, dim=[2, large_dim_length, large_dim_length], inputs=[test_result], device=device)
test.assertEqual(test_result.numpy()[0], half_result)
def register(parent):
devices = get_test_devices()
class TestLaunch(parent):
pass
add_function_test(TestLaunch, "test_launch_1d", test1d, devices=devices)
add_function_test(TestLaunch, "test_launch_2d", test2d, devices=devices)
add_function_test(TestLaunch, "test_launch_3d", test3d, devices=devices)
add_function_test(TestLaunch, "test_launch_4d", test4d, devices=devices)
add_function_test(TestLaunch, "test_launch_cmd", test_launch_cmd, devices=devices)
add_function_test(TestLaunch, "test_launch_cmd_set_param", test_launch_cmd_set_param, devices=devices)
add_function_test(TestLaunch, "test_launch_cmd_set_ctype", test_launch_cmd_set_ctype, devices=devices)
add_function_test(TestLaunch, "test_launch_cmd_set_dim", test_launch_cmd_set_dim, devices=devices)
add_function_test(TestLaunch, "test_launch_cmd_empty", test_launch_cmd_empty, devices=devices)
add_function_test(TestLaunch, "test_launch_large_kernel", test_launch_large_kernel, devices=wp.get_cuda_devices())
return TestLaunch
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_launch.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import warp as wp
from warp.tests.test_base import *
import numpy as np
# import matplotlib.pyplot as plt
wp.init()
@wp.kernel
def pnoise(
kernel_seed: int, W: int, px: int, py: int, noise_values: wp.array(dtype=float), pixel_values: wp.array(dtype=float)
):
tid = wp.tid()
state = wp.rand_init(kernel_seed)
x = (float(tid % W) + 0.5) * 0.2
y = (float(tid / W) + 0.5) * 0.2
p = wp.vec2(x, y)
n = wp.pnoise(state, p, px, py)
noise_values[tid] = n
g = ((n + 1.0) / 2.0) * 255.0
pixel_values[tid] = g
@wp.kernel
def curlnoise(kernel_seed: int, W: int, noise_coords: wp.array(dtype=wp.vec2), noise_vectors: wp.array(dtype=wp.vec2)):
tid = wp.tid()
state = wp.rand_init(kernel_seed)
x = (float(tid % W) + 0.5) * 0.2
y = (float(tid / W) + 0.5) * 0.2
p = wp.vec2(x, y)
v = wp.curlnoise(state, p)
noise_coords[tid] = p
noise_vectors[tid] = v
def test_pnoise(test, device):
# image dim
W = 256
H = 256
N = W * H
seed = 42
# periodic perlin noise test
px = 16
py = 16
noise_values = wp.zeros(N, dtype=float, device=device)
pixel_values = wp.zeros(N, dtype=float, device=device)
wp.launch(kernel=pnoise, dim=N, inputs=[seed, W, px, py, noise_values, pixel_values], outputs=[], device=device)
# Perlin theoretical range is [-0.5*sqrt(n), 0.5*sqrt(n)] for n dimensions
n = noise_values.numpy()
# max = np.max(n)
# min = np.min(n)
img = pixel_values.numpy()
img = np.reshape(img, (W, H))
### Figure viewing ###
# img = img.astype(np.uint8)
# imgplot = plt.imshow(img, 'gray')
# plt.savefig("pnoise_test.png")
### Generating pnoise_test_result_true.npy ###
# np.save(os.path.join(os.path.dirname(__file__), "assets/pnoise_golden.npy"), img)
### Golden image comparison ###
img_true = np.load(os.path.join(os.path.dirname(__file__), "assets/pnoise_golden.npy"))
test.assertTrue(img.shape == img_true.shape)
err = np.max(np.abs(img - img_true))
tolerance = 1.5e-3
test.assertTrue(err < tolerance, f"err is {err} which is >= {tolerance}")
def test_curlnoise(test, device):
# image dim
W = 128
H = 128
N = W * H
seed = 42
# curl noise test
quiver_coords_host = wp.zeros(N, dtype=wp.vec2, device="cpu")
quiver_coords = wp.zeros(N, dtype=wp.vec2, device=device)
quiver_arrows_host = wp.zeros(N, dtype=wp.vec2, device="cpu")
quiver_arrows = wp.zeros(N, dtype=wp.vec2, device=device)
wp.launch(kernel=curlnoise, dim=N, inputs=[seed, W, quiver_coords, quiver_arrows], outputs=[], device=device)
wp.copy(quiver_coords_host, quiver_coords)
wp.copy(quiver_arrows_host, quiver_arrows)
wp.synchronize()
xy_coords = quiver_coords_host.numpy()
uv_coords = quiver_arrows_host.numpy()
# normalize
norms = uv_coords[:, 0] * uv_coords[:, 0] + uv_coords[:, 1] * uv_coords[:, 1]
uv_coords = uv_coords / np.sqrt(np.max(norms))
X = xy_coords[:, 0]
Y = xy_coords[:, 1]
U = uv_coords[:, 0]
V = uv_coords[:, 1]
### Figure viewing ###
# fig, ax = plt.subplots(figsize=(25,25))
# ax.quiver(X, Y, U, V)
# ax.axis([0.0, 25.0, 0.0, 25.0])
# ax.set_aspect('equal')
# plt.savefig("curlnoise_test.png")
### Generating curlnoise_test_result_true.npy ###
result = np.stack((xy_coords, uv_coords))
# np.save(os.path.join(os.path.dirname(__file__), "assets/curlnoise_golden.npy"), result)
### Golden image comparison ###
result_true = np.load(os.path.join(os.path.dirname(__file__), "assets/curlnoise_golden.npy"))
test.assertTrue(result.shape, result_true.shape)
err = np.max(np.abs(result - result_true))
test.assertTrue(err < 1e-04)
@wp.kernel
def noise_loss_kernel(
kernel_seed: int,
query_positions: wp.array(dtype=wp.vec2),
noise_values: wp.array(dtype=float),
noise_loss: wp.array(dtype=float),
):
tid = wp.tid()
state = wp.rand_init(kernel_seed)
p = query_positions[tid]
n = wp.noise(state, p)
noise_values[tid] = n
wp.atomic_add(noise_loss, 0, n)
@wp.kernel
def noise_cd(kernel_seed: int, query_positions: wp.array(dtype=wp.vec2), gradients: wp.array(dtype=wp.vec2)):
tid = wp.tid()
state = wp.rand_init(kernel_seed)
p = query_positions[tid]
eps = 1.0e-3
pl = wp.vec2(p[0] - eps, p[1])
pr = wp.vec2(p[0] + eps, p[1])
pd = wp.vec2(p[0], p[1] - eps)
pu = wp.vec2(p[0], p[1] + eps)
nl = wp.noise(state, pl)
nr = wp.noise(state, pr)
nd = wp.noise(state, pd)
nu = wp.noise(state, pu)
gx = (nr - nl) / (2.0 * eps)
gy = (nu - nd) / (2.0 * eps)
gradients[tid] = wp.vec2(gx, gy)
def test_adj_noise(test, device):
# grid dim
N = 9
seed = 42
tape = wp.Tape()
positions = np.array(
[
[-0.1, -0.1],
[0.0, -0.1],
[0.1, -0.1],
[-0.1, 0.0],
[0.0, 0.0],
[0.1, 0.0],
[-0.1, 0.1],
[0.0, 0.1],
[0.1, 0.1],
]
)
with tape:
query_positions = wp.array(positions, dtype=wp.vec2, device=device, requires_grad=True)
noise_values = wp.zeros(N, dtype=float, device=device)
noise_loss = wp.zeros(n=1, dtype=float, device=device, requires_grad=True)
wp.launch(
kernel=noise_loss_kernel, dim=N, inputs=[seed, query_positions, noise_values, noise_loss], device=device
)
# analytic
tape.backward(loss=noise_loss)
analytic = tape.gradients[query_positions].numpy().reshape((3, 3, 2))
# central difference
gradients = wp.zeros(N, dtype=wp.vec2, device=device)
wp.launch(kernel=noise_cd, dim=N, inputs=[seed, query_positions, gradients], device=device)
gradients_host = gradients.numpy().reshape((3, 3, 2))
diff = analytic - gradients_host
result = np.sum(diff * diff, axis=2)
err = np.where(result > 1.0e-3, result, 0).sum()
test.assertTrue(err < 1.0e-8)
def register(parent):
devices = get_test_devices()
class TestNoise(parent):
pass
add_function_test(TestNoise, "test_pnoise", test_pnoise, devices=devices)
add_function_test(TestNoise, "test_curlnoise", test_curlnoise, devices=devices)
add_function_test(TestNoise, "test_adj_noise", test_adj_noise, devices=devices)
return TestNoise
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_noise.py |
import numpy as np
import warp as wp
from warp.utils import array_sum, array_inner
from warp.tests.test_base import *
wp.init()
def make_test_array_sum(dtype):
N = 1000
def test_array_sum(test, device):
cols = wp.types.type_length(dtype)
values_np = np.random.rand(N, cols)
values = wp.array(values_np, device=device, dtype=dtype)
vsum = array_sum(values)
ref_vsum = values_np.sum(axis=0)
assert_np_equal(vsum / N, ref_vsum / N, 0.0001)
return test_array_sum
def make_test_array_sum_axis(dtype):
I = 5
J = 10
K = 2
N = I * J * K
def test_array_sum(test, device):
values_np = np.random.rand(I, J, K)
values = wp.array(values_np, shape=(I, J, K), device=device, dtype=dtype)
for axis in range(3):
vsum = array_sum(values, axis=axis)
ref_vsum = values_np.sum(axis=axis)
assert_np_equal(vsum.numpy() / N, ref_vsum / N, 0.0001)
return test_array_sum
def make_test_array_inner(dtype):
N = 1000
def test_array_inner(test, device):
cols = wp.types.type_length(dtype)
a_np = np.random.rand(N, cols)
b_np = np.random.rand(N, cols)
a = wp.array(a_np, device=device, dtype=dtype)
b = wp.array(b_np, device=device, dtype=dtype)
ab = array_inner(a, b)
ref_ab = np.dot(a_np.flatten(), b_np.flatten())
test.assertAlmostEqual(ab / N, ref_ab / N, places=5)
return test_array_inner
def make_test_array_inner_axis(dtype):
I = 5
J = 10
K = 2
N = I * J * K
def test_array_inner(test, device):
a_np = np.random.rand(I, J, K)
b_np = np.random.rand(I, J, K)
a = wp.array(a_np, shape=(I, J, K), device=device, dtype=dtype)
b = wp.array(b_np, shape=(I, J, K), device=device, dtype=dtype)
ab = array_inner(a, b, axis=0)
ref_ab = np.einsum(a_np, [0, 1, 2], b_np, [0, 1, 2], [1, 2])
assert_np_equal(ab.numpy() / N, ref_ab / N, 0.0001)
ab = array_inner(a, b, axis=1)
ref_ab = np.einsum(a_np, [0, 1, 2], b_np, [0, 1, 2], [0, 2])
assert_np_equal(ab.numpy() / N, ref_ab / N, 0.0001)
ab = array_inner(a, b, axis=2)
ref_ab = np.einsum(a_np, [0, 1, 2], b_np, [0, 1, 2], [0, 1])
assert_np_equal(ab.numpy() / N, ref_ab / N, 0.0001)
return test_array_inner
def register(parent):
devices = get_test_devices()
class TestArraySym(parent):
pass
add_function_test(TestArraySym, "test_array_sum_double", make_test_array_sum(wp.float64), devices=devices)
add_function_test(TestArraySym, "test_array_sum_vec3", make_test_array_sum(wp.vec3), devices=devices)
add_function_test(TestArraySym, "test_array_sum_axis_float", make_test_array_sum_axis(wp.float32), devices=devices)
add_function_test(TestArraySym, "test_array_inner_double", make_test_array_inner(wp.float64), devices=devices)
add_function_test(TestArraySym, "test_array_inner_vec3", make_test_array_inner(wp.vec3), devices=devices)
add_function_test(
TestArraySym, "test_array_inner_axis_float", make_test_array_inner_axis(wp.float32), devices=devices
)
return TestArraySym
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_array_reduce.py |
import warp as wp
import numpy as np
wp.init()
@wp.kernel
def arange(out: wp.array(dtype=int)):
tid = wp.tid()
out[tid] = tid
device = "cuda:0"
cmds = []
n = 10
arrays = []
for i in range(5):
arrays.append(wp.zeros(n, dtype=int, device=device))
# setup CUDA graph
wp.capture_begin()
# launch kernels and keep command object around
for i in range(5):
cmd = wp.launch(arange, dim=n, inputs=[arrays[i]], device=device, record_cmd=True)
cmds.append(cmd)
graph = wp.capture_end()
#---------------------------------------
ref = np.arange(0, n, dtype=int)
wp.capture_launch(graph)
for i in range(5):
print(arrays[i].numpy())
#---------------------------------------
n = 16
arrays = []
for i in range(5):
arrays.append(wp.zeros(n, dtype=int, device=device))
# update graph params
for i in range(5):
cmd.set_dim(n)
cmd.set_param(arrays[i])
cmd.update_graph()
wp.capture_launch(graph)
wp.synchronize()
ref = np.arange(0, n, dtype=int)
for i in range(5):
print(arrays[i].numpy())
| warp-main | warp/tests/test_misc.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
# include parent path
import numpy as np
import math
import warp as wp
from warp.tests.test_base import *
np.random.seed(42)
wp.init()
wp.verify_cuda = True
@wp.kernel
def test_print():
wp.print(1.0)
wp.print("this is a string")
wp.printf("this is a float %f\n", 457.5)
wp.printf("this is an int %d\n", 123)
wp.launch(kernel=test_print, dim=1, inputs=[], outputs=[], device="cuda")
wp.synchronize()
print("finished")
| warp-main | warp/tests/test_print.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
####################################################################################################
#
# This file demonstrates step-through debugging support of the C++ code generated for a Warp kernel
# running on the CPU.
#
# This is not a unit test; it should be run interactively.
#
# For a fully integrated experience use Visual Studio Code and install the "Python C++ Debugger"
# and "CodeLLDB" extensions. Add the following configurations to your .vscode/launch.json file:
#
"""
{
"name": "Warp Debugger",
"type": "pythoncpp",
"request": "launch",
"pythonLaunchName": "Python: Current File",
"cppAttachName": "(lldb) Attach",
},
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"stopOnEntry": false,
},
{
"name": "(lldb) Attach",
"type": "lldb",
"request": "attach",
},
"""
#
# Then run this .py file using the "Warp Debugger" configuration.
#
# Check out the following resources for more information about launch configurations and
# troubleshooting common VSCode debugger integration issues:
# • https://vscode-docs.readthedocs.io/en/stable/editor/debugging/#launch-configurations
# • https://code.visualstudio.com/docs/cpp/cpp-debug#_debugging
#
####################################################################################################
import unittest
import warp as wp
from warp.tests.test_base import *
# The init() function prints the directory of the kernel cache which contains the .cpp files
# generated from Warp kernels. You can put breakpoints in these C++ files through Visual Studio Code,
# but it's generally more convenient to use wp.breakpoint(). See the example below.
wp.init()
# Enable kernels to be compiled with debug info and disable optimizations
wp.config.mode = "debug"
# Make sure Warp was built with `build_lib.py --mode=debug`
assert wp.context.runtime.core.is_debug_enabled(), "Warp must be built in debug mode to enable debugging kernels"
@wp.kernel
def test_breakpoint(n: int):
a = int(0)
for i in range(0, n):
if a == 5:
# Your debugger should halt at the C++ code corresponding with the next line,
# namely a call to the __debugbreak() intrinsic function.
wp.breakpoint()
break
a += 1
wp.expect_eq(a, 5)
def register(parent):
class TestDebug(parent):
pass
wp.build.clear_kernel_cache()
add_kernel_test(TestDebug, name="test_breakpoint", kernel=test_breakpoint, dim=1, inputs=[10], devices=["cpu"])
return TestDebug
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2, failfast=True)
| warp-main | warp/tests/test_debug.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
# include parent path
import numpy as np
import warp as wp
from warp.tests.test_base import *
np.random.seed(42)
wp.init()
@wp.kernel
def bvh_query_aabb(bvh_id: wp.uint64, lower: wp.vec3, upper: wp.vec3, bounds_intersected: wp.array(dtype=int)):
query = wp.bvh_query_aabb(bvh_id, lower, upper)
bounds_nr = int(0)
while wp.bvh_query_next(query, bounds_nr):
bounds_intersected[bounds_nr] = 1
@wp.kernel
def bvh_query_ray(bvh_id: wp.uint64, start: wp.vec3, dir: wp.vec3, bounds_intersected: wp.array(dtype=int)):
query = wp.bvh_query_ray(bvh_id, start, dir)
bounds_nr = int(0)
while wp.bvh_query_next(query, bounds_nr):
bounds_intersected[bounds_nr] = 1
def aabb_overlap(a_lower, a_upper, b_lower, b_upper):
if (
a_lower[0] > b_upper[0]
or a_lower[1] > b_upper[1]
or a_lower[2] > b_upper[2]
or a_upper[0] < b_lower[0]
or a_upper[1] < b_lower[1]
or a_upper[2] < b_lower[2]
):
return 0
else:
return 1
def intersect_ray_aabb(start, dir, lower, upper):
l1 = (lower[0] - start[0]) * dir[0]
l2 = (upper[0] - start[0]) * dir[0]
lmin = min(l1, l2)
lmax = max(l1, l2)
l1 = (lower[1] - start[1]) * dir[1]
l2 = (upper[1] - start[1]) * dir[1]
lmin = max(min(l1, l2), lmin)
lmax = min(max(l1, l2), lmax)
l1 = (lower[2] - start[2]) * dir[2]
l2 = (upper[2] - start[2]) * dir[2]
lmin = max(min(l1, l2), lmin)
lmax = min(max(l1, l2), lmax)
if lmax >= 0.0 and lmax >= lmin:
return 1
else:
return 0
def test_bvh(test, type, device):
num_bounds = 100
lowers = np.random.rand(num_bounds, 3) * 5.0
uppers = lowers + np.random.rand(num_bounds, 3) * 5.0
device_lowers = wp.array(lowers, dtype=wp.vec3, device=device)
device_uppers = wp.array(uppers, dtype=wp.vec3, device=device)
bvh = wp.Bvh(device_lowers, device_uppers)
bounds_intersected = wp.zeros(shape=(num_bounds), dtype=int, device=device)
query_lower = wp.vec3(2.0, 2.0, 2.0)
query_upper = wp.vec3(8.0, 8.0, 8.0)
query_start = wp.vec3(0.0, 0.0, 0.0)
query_dir = wp.normalize(wp.vec3(1.0, 1.0, 1.0))
for test_case in range(2):
if type == "AABB":
wp.launch(
kernel=bvh_query_aabb,
dim=1,
inputs=[bvh.id, query_lower, query_upper, bounds_intersected],
device=device,
)
else:
wp.launch(
kernel=bvh_query_ray, dim=1, inputs=[bvh.id, query_start, query_dir, bounds_intersected], device=device
)
device_intersected = bounds_intersected.numpy()
for i in range(num_bounds):
lower = lowers[i]
upper = uppers[i]
if type == "AABB":
host_intersected = aabb_overlap(lower, upper, query_lower, query_upper)
else:
host_intersected = intersect_ray_aabb(query_start, query_dir, lower, upper)
test.assertEqual(host_intersected, device_intersected[i])
if test_case == 0:
lowers = np.random.rand(num_bounds, 3) * 5.0
uppers = lowers + np.random.rand(num_bounds, 3) * 5.0
wp.copy(device_lowers, wp.array(lowers, dtype=wp.vec3))
wp.copy(device_uppers, wp.array(uppers, dtype=wp.vec3))
bvh.refit()
bounds_intersected.zero_()
def test_bvh_query_aabb(test, device):
test_bvh(test, "AABB", device)
def test_bvh_query_ray(test, device):
test_bvh(test, "ray", device)
def register(parent):
devices = get_test_devices()
class TestBvh(parent):
pass
add_function_test(TestBvh, "test_bvh_aabb", test_bvh_query_aabb, devices=devices)
add_function_test(TestBvh, "test_bvh_ray", test_bvh_query_ray, devices=devices)
return TestBvh
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_bvh.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import warp as wp
MINUS_ONE = wp.constant(-1)
| warp-main | warp/tests/test_compile_consts_dummy.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import warp as wp
from warp.tests.test_base import *
import numpy as np
compare_to_numpy = False
print_results = False
wp.init()
@wp.kernel
def test_kernel(
x: wp.array(dtype=float),
x_round: wp.array(dtype=float),
x_rint: wp.array(dtype=float),
x_trunc: wp.array(dtype=float),
x_cast: wp.array(dtype=float),
x_floor: wp.array(dtype=float),
x_ceil: wp.array(dtype=float),
):
tid = wp.tid()
x_round[tid] = wp.round(x[tid])
x_rint[tid] = wp.rint(x[tid])
x_trunc[tid] = wp.trunc(x[tid])
x_cast[tid] = float(int(x[tid]))
x_floor[tid] = wp.floor(x[tid])
x_ceil[tid] = wp.ceil(x[tid])
def test_rounding(test, device):
nx = np.array(
[
4.9,
4.5,
4.1,
3.9,
3.5,
3.1,
2.9,
2.5,
2.1,
1.9,
1.5,
1.1,
0.9,
0.5,
0.1,
-0.1,
-0.5,
-0.9,
-1.1,
-1.5,
-1.9,
-2.1,
-2.5,
-2.9,
-3.1,
-3.5,
-3.9,
-4.1,
-4.5,
-4.9,
],
dtype=np.float32,
)
x = wp.array(nx, device=device)
N = len(x)
x_round = wp.empty(N, dtype=float, device=device)
x_rint = wp.empty(N, dtype=float, device=device)
x_trunc = wp.empty(N, dtype=float, device=device)
x_cast = wp.empty(N, dtype=float, device=device)
x_floor = wp.empty(N, dtype=float, device=device)
x_ceil = wp.empty(N, dtype=float, device=device)
wp.launch(kernel=test_kernel, dim=N, inputs=[x, x_round, x_rint, x_trunc, x_cast, x_floor, x_ceil], device=device)
wp.synchronize()
nx_round = x_round.numpy().reshape(N)
nx_rint = x_rint.numpy().reshape(N)
nx_trunc = x_trunc.numpy().reshape(N)
nx_cast = x_cast.numpy().reshape(N)
nx_floor = x_floor.numpy().reshape(N)
nx_ceil = x_ceil.numpy().reshape(N)
tab = np.stack([nx, nx_round, nx_rint, nx_trunc, nx_cast, nx_floor, nx_ceil], axis=1)
golden = np.array(
[
[4.9, 5.0, 5.0, 4.0, 4.0, 4.0, 5.0],
[4.5, 5.0, 4.0, 4.0, 4.0, 4.0, 5.0],
[4.1, 4.0, 4.0, 4.0, 4.0, 4.0, 5.0],
[3.9, 4.0, 4.0, 3.0, 3.0, 3.0, 4.0],
[3.5, 4.0, 4.0, 3.0, 3.0, 3.0, 4.0],
[3.1, 3.0, 3.0, 3.0, 3.0, 3.0, 4.0],
[2.9, 3.0, 3.0, 2.0, 2.0, 2.0, 3.0],
[2.5, 3.0, 2.0, 2.0, 2.0, 2.0, 3.0],
[2.1, 2.0, 2.0, 2.0, 2.0, 2.0, 3.0],
[1.9, 2.0, 2.0, 1.0, 1.0, 1.0, 2.0],
[1.5, 2.0, 2.0, 1.0, 1.0, 1.0, 2.0],
[1.1, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0],
[0.9, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0],
[0.5, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0],
[0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0],
[-0.1, -0.0, -0.0, -0.0, 0.0, -1.0, -0.0],
[-0.5, -1.0, -0.0, -0.0, 0.0, -1.0, -0.0],
[-0.9, -1.0, -1.0, -0.0, 0.0, -1.0, -0.0],
[-1.1, -1.0, -1.0, -1.0, -1.0, -2.0, -1.0],
[-1.5, -2.0, -2.0, -1.0, -1.0, -2.0, -1.0],
[-1.9, -2.0, -2.0, -1.0, -1.0, -2.0, -1.0],
[-2.1, -2.0, -2.0, -2.0, -2.0, -3.0, -2.0],
[-2.5, -3.0, -2.0, -2.0, -2.0, -3.0, -2.0],
[-2.9, -3.0, -3.0, -2.0, -2.0, -3.0, -2.0],
[-3.1, -3.0, -3.0, -3.0, -3.0, -4.0, -3.0],
[-3.5, -4.0, -4.0, -3.0, -3.0, -4.0, -3.0],
[-3.9, -4.0, -4.0, -3.0, -3.0, -4.0, -3.0],
[-4.1, -4.0, -4.0, -4.0, -4.0, -5.0, -4.0],
[-4.5, -5.0, -4.0, -4.0, -4.0, -5.0, -4.0],
[-4.9, -5.0, -5.0, -4.0, -4.0, -5.0, -4.0],
],
dtype=np.float32,
)
assert_np_equal(tab, golden)
if print_results:
np.set_printoptions(formatter={"float": lambda x: "{:6.1f}".format(x).replace(".0", ".")})
print("----------------------------------------------")
print(" %5s %5s %5s %5s %5s %5s %5s" % ("x ", "round", "rint", "trunc", "cast", "floor", "ceil"))
print(tab)
print("----------------------------------------------")
if compare_to_numpy:
nx_round = np.round(nx)
nx_rint = np.rint(nx)
nx_trunc = np.trunc(nx)
nx_fix = np.fix(nx)
nx_floor = np.floor(nx)
nx_ceil = np.ceil(nx)
tab = np.stack([nx, nx_round, nx_rint, nx_trunc, nx_fix, nx_floor, nx_ceil], axis=1)
print(" %5s %5s %5s %5s %5s %5s %5s" % ("x ", "round", "rint", "trunc", "fix", "floor", "ceil"))
print(tab)
print("----------------------------------------------")
def register(parent):
class TestRounding(parent):
pass
devices = get_test_devices()
add_function_test(TestRounding, "test_rounding", test_rounding, devices=devices)
return TestRounding
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_rounding.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import unittest
import warp as wp
from warp.tests.test_base import *
wp.init()
@wp.kernel
def scale(
x: wp.array(dtype=float),
y: wp.array(dtype=float),
):
y[0] = x[0] ** 2.0
@wp.kernel(enable_backward=True)
def scale_1(
x: wp.array(dtype=float),
y: wp.array(dtype=float),
):
y[0] = x[0] ** 2.0
@wp.kernel(enable_backward=False)
def scale_2(
x: wp.array(dtype=float),
y: wp.array(dtype=float),
):
y[0] = x[0] ** 2.0
def test_options_1(test, device):
x = wp.array([3.0], dtype=float, requires_grad=True, device=device)
y = wp.zeros_like(x)
wp.set_module_options({"enable_backward": False})
tape = wp.Tape()
with tape:
wp.launch(scale, dim=1, inputs=[x, y], device=device)
tape.backward(y)
assert_np_equal(tape.gradients[x].numpy(), np.array(0.0))
def test_options_2(test, device):
x = wp.array([3.0], dtype=float, requires_grad=True, device=device)
y = wp.zeros_like(x)
wp.set_module_options({"enable_backward": True})
tape = wp.Tape()
with tape:
wp.launch(scale, dim=1, inputs=[x, y], device=device)
tape.backward(y)
assert_np_equal(tape.gradients[x].numpy(), np.array(6.0))
def test_options_3(test, device):
x = wp.array([3.0], dtype=float, requires_grad=True, device=device)
y = wp.zeros_like(x)
wp.set_module_options({"enable_backward": False})
tape = wp.Tape()
with tape:
wp.launch(scale_1, dim=1, inputs=[x, y], device=device)
tape.backward(y)
assert_np_equal(tape.gradients[x].numpy(), np.array(6.0))
def test_options_4(test, device):
x = wp.array([3.0], dtype=float, requires_grad=True, device=device)
y = wp.zeros_like(x)
wp.set_module_options({"enable_backward": True})
tape = wp.Tape()
with tape:
wp.launch(scale_2, dim=1, inputs=[x, y], device=device)
tape.backward(y)
assert_np_equal(tape.gradients[x].numpy(), np.array(0.0))
def register(parent):
devices = get_test_devices()
class TestOptions(parent):
pass
add_function_test(TestOptions, "test_options_1", test_options_1, devices=devices)
add_function_test(TestOptions, "test_options_2", test_options_2, devices=devices)
add_function_test(TestOptions, "test_options_3", test_options_3, devices=devices)
add_function_test(TestOptions, "test_options_4", test_options_4, devices=devices)
return TestOptions
if __name__ == "__main__":
_ = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_options.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import unittest
import os
import warp as wp
# Uncomment to run the tests on all devices
# import warp.tests.test_base
# warp.tests.test_base.test_mode = "all"
from warp.tests.test_base import get_test_devices
import warp.tests.test_codegen
import warp.tests.test_mesh_query_aabb
import warp.tests.test_mesh_query_point
import warp.tests.test_mesh_query_ray
import warp.tests.test_bvh
import warp.tests.test_conditional
import warp.tests.test_operators
import warp.tests.test_rounding
import warp.tests.test_hash_grid
import warp.tests.test_ctypes
import warp.tests.test_rand
import warp.tests.test_noise
import warp.tests.test_tape
import warp.tests.test_compile_consts
import warp.tests.test_volume
import warp.tests.test_mlp
import warp.tests.test_grad
import warp.tests.test_intersect
import warp.tests.test_array
import warp.tests.test_launch
import warp.tests.test_import
import warp.tests.test_func
import warp.tests.test_fp16
import warp.tests.test_reload
import warp.tests.test_struct
import warp.tests.test_closest_point_edge_edge
import warp.tests.test_multigpu
import warp.tests.test_quat
import warp.tests.test_atomic
import warp.tests.test_adam
import warp.tests.test_transient_module
import warp.tests.test_lerp
import warp.tests.test_smoothstep
import warp.tests.test_model
import warp.tests.test_fast_math
import warp.tests.test_streams
import warp.tests.test_torch
import warp.tests.test_pinned
import warp.tests.test_matmul
import warp.tests.test_options
import warp.tests.test_dlpack
import warp.tests.test_vec
import warp.tests.test_mat
import warp.tests.test_arithmetic
import warp.tests.test_spatial
import warp.tests.test_sparse
import warp.tests.test_math
import warp.tests.test_generics
import warp.tests.test_indexedarray
import warp.tests.test_copy
import warp.tests.test_mesh
import warp.tests.test_fabricarray
import warp.tests.test_bool
def register_tests(parent):
tests = []
tests.append(warp.tests.test_codegen.register(parent))
tests.append(warp.tests.test_mesh_query_aabb.register(parent))
tests.append(warp.tests.test_mesh_query_point.register(parent))
tests.append(warp.tests.test_mesh_query_ray.register(parent))
tests.append(warp.tests.test_bvh.register(parent))
tests.append(warp.tests.test_conditional.register(parent))
tests.append(warp.tests.test_operators.register(parent))
tests.append(warp.tests.test_rounding.register(parent))
tests.append(warp.tests.test_hash_grid.register(parent))
tests.append(warp.tests.test_ctypes.register(parent))
tests.append(warp.tests.test_rand.register(parent))
tests.append(warp.tests.test_noise.register(parent))
tests.append(warp.tests.test_tape.register(parent))
tests.append(warp.tests.test_compile_consts.register(parent))
tests.append(warp.tests.test_volume.register(parent))
tests.append(warp.tests.test_mlp.register(parent))
tests.append(warp.tests.test_grad.register(parent))
tests.append(warp.tests.test_intersect.register(parent))
tests.append(warp.tests.test_array.register(parent))
tests.append(warp.tests.test_launch.register(parent))
tests.append(warp.tests.test_import.register(parent))
tests.append(warp.tests.test_func.register(parent))
tests.append(warp.tests.test_fp16.register(parent))
tests.append(warp.tests.test_reload.register(parent))
tests.append(warp.tests.test_struct.register(parent))
tests.append(warp.tests.test_closest_point_edge_edge.register(parent))
tests.append(warp.tests.test_multigpu.register(parent))
tests.append(warp.tests.test_quat.register(parent))
tests.append(warp.tests.test_atomic.register(parent))
tests.append(warp.tests.test_adam.register(parent))
tests.append(warp.tests.test_transient_module.register(parent))
tests.append(warp.tests.test_lerp.register(parent))
tests.append(warp.tests.test_smoothstep.register(parent))
tests.append(warp.tests.test_model.register(parent))
tests.append(warp.tests.test_fast_math.register(parent))
tests.append(warp.tests.test_streams.register(parent))
tests.append(warp.tests.test_torch.register(parent))
tests.append(warp.tests.test_pinned.register(parent))
tests.append(warp.tests.test_matmul.register(parent))
tests.append(warp.tests.test_options.register(parent))
tests.append(warp.tests.test_dlpack.register(parent))
tests.append(warp.tests.test_vec.register(parent))
tests.append(warp.tests.test_mat.register(parent))
tests.append(warp.tests.test_arithmetic.register(parent))
tests.append(warp.tests.test_spatial.register(parent))
tests.append(warp.tests.test_sparse.register(parent))
tests.append(warp.tests.test_math.register(parent))
tests.append(warp.tests.test_generics.register(parent))
tests.append(warp.tests.test_indexedarray.register(parent))
tests.append(warp.tests.test_copy.register(parent))
tests.append(warp.tests.test_mesh.register(parent))
tests.append(warp.tests.test_fabricarray.register(parent))
tests.append(warp.tests.test_bool.register(parent))
return tests
class TeamCityTestResult(unittest.TextTestResult):
"""This class will report each test result to TeamCity"""
def __init__(self, stream, descriptions, verbosity):
super(TeamCityTestResult, self).__init__(stream, descriptions, verbosity)
def addSuccess(self, test):
super(TeamCityTestResult, self).addSuccess(test)
self.reportSuccess(test)
def addError(self, test, err):
super(TeamCityTestResult, self).addError(test, err)
self.reportFailure(test)
def addFailure(self, test, err):
super(TeamCityTestResult, self).addFailure(test, err)
self.reportFailure(test)
def addSkip(self, test, reason):
super(TeamCityTestResult, self).addSkip(test, reason)
def addExpectedFailure(self, test, err):
super(TeamCityTestResult, self).addExpectedFailure(test, err)
self.reportSuccess(test)
def addUnexpectedSuccess(self, test):
super(TeamCityTestResult, self).addUnexpectedSuccess(test)
self.reportFailure(test)
def reportSuccess(self, test):
test_id = test.id()
print(f"##teamcity[testStarted name='{test_id}']")
print(f"##teamcity[testFinished name='{test_id}']")
def reportFailure(self, test):
test_id = test.id()
print(f"##teamcity[testStarted name='{test_id}']")
print(f"##teamcity[testFailed name='{test_id}']")
print(f"##teamcity[testFinished name='{test_id}']")
class TeamCityTestRunner(unittest.TextTestRunner):
"""Test runner that will report test results to TeamCity if running in TeamCity"""
def __init__(self, **kwargs):
self.running_in_teamcity = os.environ.get("TEAMCITY_VERSION") is not None
if self.running_in_teamcity:
kwargs["resultclass"] = TeamCityTestResult
super(TeamCityTestRunner, self).__init__(**kwargs)
def run(self, test, name):
if self.running_in_teamcity:
print(f"##teamcity[testSuiteStarted name='{name}']")
result = super(TeamCityTestRunner, self).run(test)
if self.running_in_teamcity:
print(f"##teamcity[testSuiteFinished name='{name}']")
if not result.wasSuccessful():
print(f"##teamcity[buildStatus status='FAILURE']")
return result
def run():
test_suite = unittest.TestSuite()
tests = register_tests(unittest.TestCase)
for test in tests:
test_suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(test))
# force rebuild of all kernels
wp.build.clear_kernel_cache()
# load all modules
for device in get_test_devices():
wp.force_load(device)
runner = TeamCityTestRunner(verbosity=2, failfast=False)
ret = not runner.run(test_suite, "WarpTests").wasSuccessful()
return ret
if __name__ == "__main__":
ret = run()
import sys
sys.exit(ret)
| warp-main | warp/tests/test_all.py |
import numpy as np
import warp as wp
from warp.sparse import bsr_zeros, bsr_set_from_triplets, bsr_get_diag, bsr_diag, bsr_set_transpose, bsr_axpy, bsr_mm
from warp.tests.test_base import *
wp.init()
def _get_block(mat, row, col, block_shape):
return mat[row * block_shape[0] : (row + 1) * block_shape[0], col * block_shape[1] : (col + 1) * block_shape[1]]
def _triplets_to_dense(shape, rows, cols, values):
mat = np.zeros(shape)
rows = rows.numpy()
cols = cols.numpy()
values = values.numpy()
block_shape = values.shape[1:] if values.ndim == 3 else (1, 1)
for row, col, val in zip(rows, cols, values):
mat_block = _get_block(mat, row, col, block_shape)
mat_block += val
return mat
def _bsr_to_dense(bsr):
mat = np.zeros(bsr.shape)
offsets = bsr.offsets.numpy()
columns = bsr.columns.numpy()
values = bsr.values.numpy()
for row in range(bsr.nrow):
beg = offsets[row]
end = offsets[row + 1]
for block in range(beg, end):
mat_block = _get_block(mat, row, columns[block], bsr.block_shape)
mat_block += values[block]
return mat
def test_csr_from_triplets(test, device):
shape = (8, 6)
n = 100
rows = wp.array(np.random.randint(0, shape[0], n, dtype=int), dtype=int, device=device)
cols = wp.array(np.random.randint(0, shape[1], n, dtype=int), dtype=int, device=device)
vals = wp.array(np.random.rand(n), dtype=float, device=device)
ref = _triplets_to_dense(shape, rows, cols, vals)
csr = bsr_zeros(shape[0], shape[1], float, device=device)
bsr_set_from_triplets(csr, rows, cols, vals)
res = _bsr_to_dense(csr)
assert_np_equal(ref, res, 0.0001)
def test_bsr_from_triplets(test, device):
block_shape = (3, 2)
nrow = 4
ncol = 9
shape = (block_shape[0] * nrow, block_shape[1] * ncol)
n = 50
rows = wp.array(np.random.randint(0, nrow, n, dtype=int), dtype=int, device=device)
cols = wp.array(np.random.randint(0, ncol, n, dtype=int), dtype=int, device=device)
vals = wp.array(np.random.rand(n, block_shape[0], block_shape[1]), dtype=float, device=device)
ref = _triplets_to_dense(shape, rows, cols, vals)
bsr = bsr_zeros(nrow, ncol, wp.types.matrix(shape=block_shape, dtype=float), device=device)
bsr_set_from_triplets(bsr, rows, cols, vals)
res = _bsr_to_dense(bsr)
assert_np_equal(ref, res, 0.0001)
def test_bsr_get_diag(test, device):
block_shape = (3, 3)
nrow = 4
ncol = 4
nnz = 6
rows = wp.array([0, 1, 2, 3, 2, 1], dtype=int, device=device)
cols = wp.array([1, 1, 1, 3, 2, 2], dtype=int, device=device)
vals_np = np.random.rand(nnz, block_shape[0], block_shape[1])
vals = wp.array(vals_np, dtype=float, device=device)
bsr = bsr_zeros(nrow, ncol, wp.types.matrix(shape=block_shape, dtype=float), device=device)
bsr_set_from_triplets(bsr, rows, cols, vals)
diag = bsr_get_diag(bsr)
diag_np = diag.numpy()
assert_np_equal(diag_np[0], np.zeros(block_shape))
assert_np_equal(diag_np[1], vals_np[1], tol=0.00001)
assert_np_equal(diag_np[2], vals_np[4], tol=0.00001)
assert_np_equal(diag_np[3], vals_np[3], tol=0.00001)
# Test round-trip
diag_bsr = bsr_diag(diag)
diag = bsr_get_diag(diag_bsr)
assert_np_equal(diag_np, diag.numpy())
def make_test_bsr_transpose(block_shape, scalar_type):
def test_bsr_transpose(test, device):
nrow = 4
ncol = 5
nnz = 6
rows = wp.array([0, 1, 2, 3, 2, 1], dtype=int, device=device)
cols = wp.array([1, 4, 1, 3, 0, 2], dtype=int, device=device)
vals_np = np.random.rand(nnz, block_shape[0], block_shape[1])
vals = wp.array(vals_np, dtype=scalar_type, device=device).reshape((nnz, block_shape[0], block_shape[1]))
bsr = bsr_zeros(nrow, ncol, wp.types.matrix(shape=block_shape, dtype=scalar_type), device=device)
bsr_set_from_triplets(bsr, rows, cols, vals)
ref = np.transpose(_bsr_to_dense(bsr))
bsr_transposed = bsr_zeros(
ncol, nrow, wp.types.matrix(shape=block_shape[::-1], dtype=scalar_type), device=device
)
bsr_set_transpose(dest=bsr_transposed, src=bsr)
res = _bsr_to_dense(bsr_transposed)
assert_np_equal(ref, res, 0.0001)
return test_bsr_transpose
def make_test_bsr_axpy(block_shape, scalar_type):
def test_bsr_axpy(test, device):
nrow = 2
ncol = 3
nnz = 6
alpha = -1.0
beta = 2.0
x_rows = wp.array(np.random.randint(0, nrow, nnz, dtype=int), dtype=int, device=device)
x_cols = wp.array(np.random.randint(0, ncol, nnz, dtype=int), dtype=int, device=device)
x_vals = wp.array(np.random.rand(nnz, block_shape[0], block_shape[1]), dtype=scalar_type, device=device)
x_vals = x_vals.reshape((nnz, block_shape[0], block_shape[1]))
x = bsr_zeros(nrow, ncol, wp.types.matrix(shape=block_shape, dtype=scalar_type), device=device)
bsr_set_from_triplets(x, x_rows, x_cols, x_vals)
y_rows = wp.array(np.random.randint(0, nrow, nnz, dtype=int), dtype=int, device=device)
y_cols = wp.array(np.random.randint(0, ncol, nnz, dtype=int), dtype=int, device=device)
y_vals = wp.array(np.random.rand(nnz, block_shape[0], block_shape[1]), dtype=scalar_type, device=device)
y_vals = y_vals.reshape((nnz, block_shape[0], block_shape[1]))
y = bsr_zeros(nrow, ncol, wp.types.matrix(shape=block_shape, dtype=scalar_type), device=device)
bsr_set_from_triplets(y, y_rows, y_cols, y_vals)
ref = alpha * _bsr_to_dense(x) + beta * _bsr_to_dense(y)
bsr_axpy(x, y, alpha, beta)
res = _bsr_to_dense(y)
assert_np_equal(ref, res, 0.0001)
return test_bsr_axpy
def make_test_bsr_mm(block_shape, scalar_type):
def test_bsr_mm(test, device):
x_nrow = 3
x_ncol = 2
x_block_shape = block_shape
y_nrow = 2
y_ncol = 3
y_block_shape = block_shape[::-1]
z_nrow = x_nrow
z_ncol = y_ncol
z_block_shape = (x_block_shape[0], y_block_shape[1])
nnz = 6
alpha = -1.0
beta = 2.0
x_rows = wp.array(np.random.randint(0, x_nrow, nnz, dtype=int), dtype=int, device=device)
x_cols = wp.array(np.random.randint(0, x_ncol, nnz, dtype=int), dtype=int, device=device)
x_vals = wp.array(np.random.rand(nnz, x_block_shape[0], x_block_shape[1]), dtype=scalar_type, device=device)
x_vals = x_vals.reshape((nnz, x_block_shape[0], x_block_shape[1]))
x = bsr_zeros(x_nrow, x_ncol, wp.types.matrix(shape=x_block_shape, dtype=scalar_type), device=device)
bsr_set_from_triplets(x, x_rows, x_cols, x_vals)
y_rows = wp.array(np.random.randint(0, y_nrow, nnz, dtype=int), dtype=int, device=device)
y_cols = wp.array(np.random.randint(0, y_ncol, nnz, dtype=int), dtype=int, device=device)
y_vals = wp.array(np.random.rand(nnz, y_block_shape[0], y_block_shape[1]), dtype=scalar_type, device=device)
y_vals = y_vals.reshape((nnz, y_block_shape[0], y_block_shape[1]))
y = bsr_zeros(y_nrow, y_ncol, wp.types.matrix(shape=y_block_shape, dtype=scalar_type), device=device)
bsr_set_from_triplets(y, y_rows, y_cols, y_vals)
z_rows = wp.array(np.random.randint(0, z_nrow, nnz, dtype=int), dtype=int, device=device)
z_cols = wp.array(np.random.randint(0, z_ncol, nnz, dtype=int), dtype=int, device=device)
z_vals = wp.array(np.random.rand(nnz, z_block_shape[0], z_block_shape[1]), dtype=scalar_type, device=device)
z_vals = z_vals.reshape((nnz, z_block_shape[0], z_block_shape[1]))
z = bsr_zeros(z_nrow, z_ncol, wp.types.matrix(shape=z_block_shape, dtype=scalar_type), device=device)
bsr_set_from_triplets(z, z_rows, z_cols, z_vals)
ref = alpha * (_bsr_to_dense(x) @ _bsr_to_dense(y)) + beta * _bsr_to_dense(z)
bsr_mm(x, y, z, alpha, beta)
res = _bsr_to_dense(z)
assert_np_equal(ref, res, 0.0001)
return test_bsr_mm
def register(parent):
devices = get_test_devices()
class TestSparse(parent):
pass
add_function_test(TestSparse, "test_csr_from_triplets", test_csr_from_triplets, devices=devices)
add_function_test(TestSparse, "test_bsr_from_triplets", test_bsr_from_triplets, devices=devices)
add_function_test(TestSparse, "test_bsr_get_diag", test_bsr_get_diag, devices=devices)
add_function_test(TestSparse, "test_csr_transpose", make_test_bsr_transpose((1, 1), wp.float32), devices=devices)
add_function_test(
TestSparse, "test_bsr_transpose_1_3", make_test_bsr_transpose((1, 3), wp.float32), devices=devices
)
add_function_test(
TestSparse, "test_bsr_transpose_3_3", make_test_bsr_transpose((3, 3), wp.float64), devices=devices
)
add_function_test(TestSparse, "test_csr_axpy", make_test_bsr_axpy((1, 1), wp.float32), devices=devices)
add_function_test(TestSparse, "test_bsr_axpy_1_3", make_test_bsr_axpy((1, 3), wp.float32), devices=devices)
add_function_test(TestSparse, "test_bsr_axpy_3_3", make_test_bsr_axpy((3, 3), wp.float64), devices=devices)
add_function_test(TestSparse, "test_csr_mm", make_test_bsr_mm((1, 1), wp.float32), devices=devices)
add_function_test(TestSparse, "test_bsr_mm_1_3", make_test_bsr_mm((1, 3), wp.float32), devices=devices)
add_function_test(TestSparse, "test_bsr_mm_3_3", make_test_bsr_mm((3, 3), wp.float64), devices=devices)
return TestSparse
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_sparse.py |
import warp as wp
# dummy class used in test_reload.py
class ClassKernelTest:
def __init__(self, device):
# 3x3 frames in the rest pose:
self.identities = wp.zeros(shape=10, dtype=wp.mat33, device=device)
wp.launch(kernel=self.gen_identities_kernel, dim=10, inputs=[self.identities], device=device)
@wp.func
def return_identity(e: int):
return wp.mat33(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0)
@wp.kernel
def gen_identities_kernel(s: wp.array(dtype=wp.mat33)):
tid = wp.tid()
s[tid] = ClassKernelTest.return_identity(tid)
| warp-main | warp/tests/test_class_kernel.py |
import warp as wp
import numpy as np
from warp.tests.test_base import *
wp.init()
@wp.kernel
def intersect_tri(
v0: wp.vec3, v1: wp.vec3, v2: wp.vec3, u0: wp.vec3, u1: wp.vec3, u2: wp.vec3, result: wp.array(dtype=int)
):
tid = wp.tid()
result[0] = wp.intersect_tri_tri(v0, v1, v2, u0, u1, u2)
def test_intersect_tri(test, device):
points_intersect = [
wp.vec3(0.0, 0.0, 0.0),
wp.vec3(1.0, 0.0, 0.0),
wp.vec3(0.0, 0.0, 1.0),
wp.vec3(0.5, -0.5, 0.0),
wp.vec3(0.5, -0.5, 1.0),
wp.vec3(0.5, 0.5, 0.0),
]
points_separated = [
wp.vec3(0.0, 0.0, 0.0),
wp.vec3(1.0, 0.0, 0.0),
wp.vec3(0.0, 0.0, 1.0),
wp.vec3(-0.5, -0.5, 0.0),
wp.vec3(-0.5, -0.5, 1.0),
wp.vec3(-0.5, 0.5, 0.0),
]
result = wp.zeros(1, dtype=int, device=device)
wp.launch(intersect_tri, dim=1, inputs=[*points_intersect, result], device=device)
assert_np_equal(result.numpy(), np.array([1]))
wp.launch(intersect_tri, dim=1, inputs=[*points_separated, result], device=device)
assert_np_equal(result.numpy(), np.array([0]))
def register(parent):
devices = get_test_devices()
class TestIntersect(parent):
pass
add_function_test(TestIntersect, "test_intersect_tri", test_intersect_tri, devices=devices)
return TestIntersect
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2, failfast=False)
| warp-main | warp/tests/test_intersect.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import numpy as np
import warp as wp
from warp.tests.test_base import *
wp.init()
@wp.func
def mlp_activation(z: float):
return wp.tanh(z)
@wp.kernel
def mlp_kernel(
weights: wp.array2d(dtype=float),
bias: wp.array(dtype=float),
x: wp.array2d(dtype=float),
y: wp.array2d(dtype=float),
):
wp.mlp(weights, bias, mlp_activation, wp.tid(), x, y)
@wp.kernel
def loss_kernel(x: wp.array2d(dtype=float), loss: wp.array(dtype=float)):
i, j = wp.tid()
wp.atomic_add(loss, 0, x[i, j] * x[i, j])
def test_mlp(test, device):
np.random.seed(0)
m = 10
n = 200
batches = 20000
weights = wp.array(np.random.rand(m, n) * 0.5 - 0.5, dtype=float, device=device)
bias = wp.array(np.random.rand(m) * 0.5 - 0.5, dtype=float, device=device)
x = wp.array(np.random.rand(n, batches), dtype=float, device=device)
y = wp.zeros(shape=(m, batches), device=device)
with wp.ScopedTimer("warp", active=False):
wp.launch(mlp_kernel, dim=batches, inputs=[weights, bias, x, y], device=device)
wp.synchronize()
# A*x + b
with wp.ScopedTimer("numpy", active=False):
expect = np.tanh(weights.numpy().reshape(m, n) @ x.numpy().reshape(-1, batches) + bias.numpy().reshape(m, 1))
result = y.numpy().reshape(-1, batches)
assert_np_equal(result, expect, tol=1.0e-6)
def create_mlp(m, n):
import torch
torch.manual_seed(0)
class FeedForward(torch.nn.Module):
def __init__(self, input_size, hidden_size):
super(FeedForward, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.fc1 = torch.nn.Linear(self.input_size, self.hidden_size)
self.act = torch.nn.Tanh()
def forward(self, x):
out = self.fc1(x)
out = self.act(out)
return out
return FeedForward(m, n)
def create_golden():
import torch
input_size = 32
hidden_size = 16
batch_size = 64
network = create_mlp(input_size, hidden_size)
x = torch.Tensor(np.random.rand(batch_size, input_size))
x.requires_grad = True
y = network.forward(x)
y.retain_grad()
loss = torch.inner(y.flatten(), y.flatten())
loss.backward(retain_graph=True)
results = {}
results["weights"] = network.fc1.weight.cpu().detach().numpy()
results["weights_grad"] = network.fc1.weight.grad.cpu().detach().numpy()
results["bias"] = network.fc1.bias.cpu().detach().numpy()
results["bias_grad"] = network.fc1.bias.grad.cpu().detach().numpy()
results["x"] = x.cpu().detach().numpy()
results["x_grad"] = x.grad.cpu().detach().numpy()
results["y"] = y.cpu().detach().numpy()
results["y_grad"] = y.grad.cpu().detach().numpy()
results["loss"] = loss.cpu().detach().numpy()
np.save(os.path.join(os.path.dirname(__file__), "assets/mlp_golden.npy"), results, allow_pickle=True)
def load_golden():
return np.load(os.path.join(os.path.dirname(__file__), "assets/mlp_golden.npy"), allow_pickle=True).item()
def test_mlp_grad(test, device):
# uncomment to re-build golden files
# create_golden()
results = load_golden()
torch_weights = results["weights"]
torch_weights_grad = results["weights_grad"]
torch_bias = results["bias"]
torch_bias_grad = results["bias_grad"]
torch_x = results["x"].T
torch_x_grad = results["x_grad"].T
torch_y = results["y"].T
torch_y_grad = results["y_grad"].T
torch_loss = results["loss"].T
weights = wp.array(torch_weights, dtype=float, device=device, requires_grad=True)
bias = wp.array(torch_bias, dtype=float, device=device, requires_grad=True)
x = wp.array(torch_x, dtype=float, device=device, requires_grad=True)
y = wp.array(torch_y, dtype=float, device=device, requires_grad=True)
y.zero_()
loss = wp.zeros(1, dtype=float, device=device, requires_grad=True)
m = torch_weights.shape[0]
n = torch_weights.shape[1]
b = torch_x.shape[1]
tape = wp.Tape()
with tape:
wp.launch(mlp_kernel, dim=b, inputs=[weights, bias, x, y], device=device)
wp.launch(loss_kernel, dim=y.shape, inputs=[y, loss], device=device)
tape.backward(loss=loss)
# check forward result
assert_np_equal(y.numpy().reshape(-1, b), torch_y, tol=1.0e-1)
assert_np_equal(loss.numpy(), torch_loss, tol=1.0e-1)
# check backward result
assert_np_equal(tape.gradients[weights].numpy().reshape(m, n), torch_weights_grad, tol=1.0e-1)
assert_np_equal(tape.gradients[bias].numpy(), torch_bias_grad, tol=1.0e-1)
assert_np_equal(tape.gradients[x].numpy().reshape(n, b), torch_x_grad, tol=1.0e-1)
assert_np_equal(tape.gradients[y].numpy().reshape(m, b), torch_y_grad, tol=1.0e-1)
def profile_mlp_torch(device):
import torch
m = 128
n = 64
steps = 20
for i in range(steps):
b = 2**i
network = create_mlp(m, n)
x = torch.Tensor(np.random.rand(b, m))
with wp.ScopedTimer("torch_forward" + str(b)):
y = network.forward(x)
torch.cuda.synchronize()
for i in range(steps):
b = 2**i
network = create_mlp(m, n)
x = torch.Tensor(np.random.rand(b, m))
y = network.forward(x)
loss = torch.norm(y)
# run once to alloc all gradients
loss.backward(retain_graph=True)
with wp.ScopedTimer("torch-backward" + str(b)):
loss.backward()
torch.cuda.synchronize()
def profile_mlp_warp(device):
m = 128
n = 64
steps = 20
for i in range(steps):
b = 2**i
weights = wp.array(np.random.rand(m, n) * 0.5 - 0.5, dtype=float, device=device)
bias = wp.array(np.random.rand(m) * 0.5 - 0.5, dtype=float, device=device)
x = wp.array(np.random.rand(n, b), dtype=float, device=device)
y = wp.zeros(shape=(m, b), device=device)
with wp.ScopedTimer("warp-forward" + str(b)):
wp.launch(mlp_kernel, dim=b, inputs=[weights, bias, x, y], device=device)
wp.synchronize()
for i in range(steps):
b = 2**i
weights = wp.array(np.random.rand(m, n) * 0.5 - 0.5, dtype=float, device=device, requires_grad=True)
bias = wp.array(np.random.rand(m) * 0.5 - 0.5, dtype=float, device=device, requires_grad=True)
x = wp.array(np.random.rand(n, b), dtype=float, device=device, requires_grad=True)
y = wp.zeros(shape=(m, b), device=device, requires_grad=True)
loss = wp.zeros(1, dtype=float, device=device)
tape = wp.Tape()
with tape:
wp.launch(mlp_kernel, dim=b, inputs=[weights, bias, x, y], device=device)
wp.launch(loss_kernel, dim=y.size, inputs=[y.flatten(), loss], device=device)
# run backward once to ensure all adjoints are allocated
tape.backward(loss)
wp.synchronize()
with wp.ScopedTimer("warp-backward" + str(b)):
tape.backward(loss)
wp.synchronize()
# profile_mlp_warp("cuda")
# profile_mlp_torch("cuda")
def register(parent):
devices = get_test_devices()
class TestMLP(parent):
pass
add_function_test(TestMLP, "test_mlp", test_mlp, devices=devices)
add_function_test(TestMLP, "test_mlp_grad", test_mlp_grad, devices=devices)
return TestMLP
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2, failfast=False)
| warp-main | warp/tests/test_mlp.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import unittest
import numpy as np
import warp as wp
from warp.tests.test_base import *
# fmt: off
POINT_POSITIONS = (
( 0.5, -0.5, 0.5),
(-0.5, -0.5, 0.5),
( 0.5, 0.5, 0.5),
(-0.5, 0.5, 0.5),
(-0.5, -0.5, -0.5),
( 0.5, -0.5, -0.5),
(-0.5, 0.5, -0.5),
( 0.5, 0.5, -0.5),
)
# Right-hand winding order. This corresponds to USD's (and others).
RIGHT_HANDED_FACE_VERTEX_INDICES = (
0, 3, 1,
0, 2, 3,
4, 7, 5,
4, 6, 7,
6, 2, 7,
6, 3, 2,
5, 1, 4,
5, 0, 1,
5, 2, 0,
5, 7, 2,
1, 6, 4,
1, 3, 6,
)
# Left-hand winding order. This corresponds to Houdini's (and others).
LEFT_HANDED_FACE_VERTEX_INDICES = (
0, 1, 3,
0, 3, 2,
4, 5, 7,
4, 7, 6,
6, 7, 2,
6, 2, 3,
5, 4, 1,
5, 1, 0,
5, 0, 2,
5, 2, 7,
1, 4, 6,
1, 6, 3,
)
# fmt: on
POINT_COUNT = 8
VERTEX_COUNT = 36
FACE_COUNT = 12
wp.init()
@wp.kernel(enable_backward=False)
def read_points_kernel(
mesh_id: wp.uint64,
out_points: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
mesh = wp.mesh_get(mesh_id)
out_points[tid] = mesh.points[tid]
@wp.kernel(enable_backward=False)
def read_indices_kernel(
mesh_id: wp.uint64,
out_indices: wp.array(dtype=int),
):
tid = wp.tid()
mesh = wp.mesh_get(mesh_id)
out_indices[tid * 3 + 0] = mesh.indices[tid * 3 + 0]
out_indices[tid * 3 + 1] = mesh.indices[tid * 3 + 1]
out_indices[tid * 3 + 2] = mesh.indices[tid * 3 + 2]
def test_mesh_read_properties(test, device):
points = wp.array(POINT_POSITIONS, dtype=wp.vec3)
indices = wp.array(RIGHT_HANDED_FACE_VERTEX_INDICES, dtype=int)
mesh = wp.Mesh(points=points, indices=indices)
assert mesh.points.size == POINT_COUNT
assert mesh.indices.size == VERTEX_COUNT
assert int(mesh.indices.size / 3) == FACE_COUNT
out_points = wp.empty(POINT_COUNT, dtype=wp.vec3)
wp.launch(
read_points_kernel,
dim=POINT_COUNT,
inputs=[
mesh.id,
],
outputs=[
out_points,
],
)
assert_np_equal(out_points.numpy(), np.array(POINT_POSITIONS))
out_indices = wp.empty(VERTEX_COUNT, dtype=int)
wp.launch(
read_indices_kernel,
dim=FACE_COUNT,
inputs=[
mesh.id,
],
outputs=[
out_indices,
],
)
assert_np_equal(out_indices.numpy(), np.array(RIGHT_HANDED_FACE_VERTEX_INDICES))
@wp.kernel(enable_backward=False)
def query_point_kernel(
mesh_id: wp.uint64,
expected_sign: float,
):
point = wp.vec3(0.1, 0.2, 0.3)
expected_pos = wp.vec3(0.1, 0.2, 0.5)
sign = float(0.0)
face = int(0)
bary_u = float(0.0)
bary_v = float(0.0)
wp.mesh_query_point(
mesh_id,
point,
1e6,
sign,
face,
bary_u,
bary_v,
)
pos = wp.mesh_eval_position(mesh_id, face, bary_u, bary_v)
wp.expect_eq(wp.sign(sign), expected_sign)
wp.expect_eq(face, 1)
wp.expect_near(wp.length(pos - expected_pos), 0.0)
def test_mesh_query_point(test, device):
points = wp.array(POINT_POSITIONS, dtype=wp.vec3)
indices = wp.array(RIGHT_HANDED_FACE_VERTEX_INDICES, dtype=int)
mesh = wp.Mesh(points=points, indices=indices)
expected_sign = -1.0
wp.launch(
query_point_kernel,
dim=1,
inputs=[
mesh.id,
expected_sign,
],
)
indices = wp.array(LEFT_HANDED_FACE_VERTEX_INDICES, dtype=int)
mesh = wp.Mesh(points=points, indices=indices)
expected_sign = 1.0
wp.launch(
query_point_kernel,
dim=1,
inputs=[
mesh.id,
expected_sign,
],
)
@wp.kernel(enable_backward=False)
def query_ray_kernel(
mesh_id: wp.uint64,
expected_sign: float,
):
start = wp.vec3(0.1, 0.2, 0.3)
dir = wp.normalize(wp.vec3(-1.2, 2.3, -3.4))
expected_t = 0.557828
expected_pos = wp.vec3(-0.0565217, 0.5, -0.143478)
t = float(0.0)
bary_u = float(0.0)
bary_v = float(0.0)
sign = float(0.0)
normal = wp.vec3(0.0, 0.0, 0.0)
face = int(0)
wp.mesh_query_ray(
mesh_id,
start,
dir,
1e6,
t,
bary_u,
bary_v,
sign,
normal,
face,
)
pos = wp.mesh_eval_position(mesh_id, face, bary_u, bary_v)
wp.expect_near(t, expected_t)
wp.expect_near(t, wp.length(pos - start), 1e-6)
wp.expect_eq(wp.sign(sign), expected_sign)
wp.expect_eq(face, 4)
wp.expect_near(wp.length(pos - expected_pos), 0.0, 1e-6)
def test_mesh_query_ray(test, device):
points = wp.array(POINT_POSITIONS, dtype=wp.vec3)
indices = wp.array(RIGHT_HANDED_FACE_VERTEX_INDICES, dtype=int)
mesh = wp.Mesh(points=points, indices=indices)
expected_sign = -1.0
wp.launch(
query_ray_kernel,
dim=1,
inputs=[
mesh.id,
expected_sign,
],
)
indices = wp.array(LEFT_HANDED_FACE_VERTEX_INDICES, dtype=int)
mesh = wp.Mesh(points=points, indices=indices)
expected_sign = 1.0
wp.launch(
query_ray_kernel,
dim=1,
inputs=[
mesh.id,
expected_sign,
],
)
def test_mesh_refit_graph(test, device):
points = wp.array(POINT_POSITIONS, dtype=wp.vec3)
indices = wp.array(RIGHT_HANDED_FACE_VERTEX_INDICES, dtype=int)
mesh = wp.Mesh(points=points, indices=indices)
wp.capture_begin()
mesh.refit()
graph = wp.capture_end()
# replay
num_iters = 10
for _ in range(num_iters):
wp.capture_launch(graph)
def register(parent):
devices = get_test_devices()
class TestMesh(parent):
pass
add_function_test(TestMesh, "test_mesh_read_properties", test_mesh_read_properties, devices=devices)
add_function_test(TestMesh, "test_mesh_query_point", test_mesh_query_point, devices=devices)
add_function_test(TestMesh, "test_mesh_query_ray", test_mesh_query_ray, devices=devices)
add_function_test(TestMesh, "test_mesh_refit_graph", test_mesh_refit_graph, devices=wp.get_cuda_devices())
return TestMesh
if __name__ == "__main__":
_ = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_mesh.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import warp as wp
from warp.tests.test_base import *
import numpy as np
wp.init()
# wp.config.cache_kernels = False
# Volume write tests
@wp.kernel
def test_volume_store_f(volume: wp.uint64, points: wp.array(dtype=wp.vec3)):
tid = wp.tid()
p = points[tid]
i = int(p[0])
j = int(p[1])
k = int(p[2])
wp.volume_store_f(volume, i, j, k, float(i + 100 * j + 10000 * k))
@wp.kernel
def test_volume_readback_f(volume: wp.uint64, points: wp.array(dtype=wp.vec3), values: wp.array(dtype=wp.float32)):
tid = wp.tid()
p = points[tid]
i = int(p[0])
j = int(p[1])
k = int(p[2])
values[tid] = wp.volume_lookup_f(volume, i, j, k)
@wp.kernel
def test_get_list_of_tiles(
volume: wp.uint64,
points_is: wp.array2d(dtype=wp.int32),
points_ws: wp.array(dtype=wp.vec3),
tiles_is: wp.array2d(dtype=wp.int32),
tiles_ws: wp.array2d(dtype=wp.int32),
):
tid = wp.tid()
tiles_is[tid, 0] = points_is[tid, 0]
tiles_is[tid, 1] = points_is[tid, 1]
tiles_is[tid, 2] = points_is[tid, 2]
q = wp.volume_world_to_index(volume, points_ws[tid])
tiles_ws[tid, 0] = int(q[0] / 8.0) * 8
tiles_ws[tid, 1] = int(q[1] / 8.0) * 8
tiles_ws[tid, 2] = int(q[2] / 8.0) * 8
@wp.kernel
def test_volume_tile_store_f(volume: wp.uint64, tiles: wp.array2d(dtype=wp.int32)):
tid = wp.tid()
ti = tiles[tid, 0]
tj = tiles[tid, 1]
tk = tiles[tid, 2]
for r in range(512):
ii = ti + (r / 64) % 8
jj = tj + (r / 8) % 8
kk = tk + r % 8
wp.volume_store_f(volume, ii, jj, kk, float(100 * ii + 10 * jj + kk))
@wp.kernel
def test_volume_tile_store_ws_f(volume: wp.uint64, tiles: wp.array(dtype=wp.vec3)):
tid = wp.tid()
q = wp.volume_world_to_index(volume, tiles[tid])
ti = int(wp.round(q[0]))
tj = int(wp.round(q[1]))
tk = int(wp.round(q[2]))
for r in range(512):
ii = ti + (r / 64) % 8
jj = tj + (r / 8) % 8
kk = tk + r % 8
wp.volume_store_f(volume, ii, jj, kk, float(100 * ii + 10 * jj + kk))
@wp.kernel
def test_volume_tile_readback_f(
volume: wp.uint64, tiles: wp.array2d(dtype=wp.int32), values: wp.array(dtype=wp.float32)
):
tid = wp.tid()
ti = tiles[tid, 0]
tj = tiles[tid, 1]
tk = tiles[tid, 2]
for r in range(512):
ii = ti + (r / 64) % 8
jj = tj + (r / 8) % 8
kk = tk + r % 8
values[tid * 512 + r] = wp.volume_lookup_f(volume, ii, jj, kk)
@wp.kernel
def test_volume_tile_store_v(volume: wp.uint64, tiles: wp.array2d(dtype=wp.int32)):
tid = wp.tid()
ti = tiles[tid, 0]
tj = tiles[tid, 1]
tk = tiles[tid, 2]
for r in range(512):
ii = ti + (r / 64) % 8
jj = tj + (r / 8) % 8
kk = tk + r % 8
wp.volume_store_v(volume, ii, jj, kk, wp.vec3(float(ii), float(jj), float(kk)))
@wp.kernel
def test_volume_tile_readback_v(volume: wp.uint64, tiles: wp.array2d(dtype=wp.int32), values: wp.array(dtype=wp.vec3)):
tid = wp.tid()
ti = tiles[tid, 0]
tj = tiles[tid, 1]
tk = tiles[tid, 2]
for r in range(512):
ii = ti + (r / 64) % 8
jj = tj + (r / 8) % 8
kk = tk + r % 8
values[tid * 512 + r] = wp.volume_lookup_v(volume, ii, jj, kk)
rng = np.random.default_rng(101215)
def register(parent):
devices = get_test_devices()
class TestVolumes(parent):
def test_volume_allocation(self):
voxel_size = 0.125
background_value = 123.456
translation = wp.vec3(-12.3, 4.56, -789)
axis = np.linspace(-11, 11, 23)
points_ref = np.array([[x, y, z] for x in axis for y in axis for z in axis])
values_ref = np.array([x + 100 * y + 10000 * z for x in axis for y in axis for z in axis])
num_points = len(points_ref)
bb_max = np.array([11, 11, 11])
for device in devices:
if device.is_cpu:
continue
volume_a = wp.Volume.allocate(
-bb_max,
bb_max,
voxel_size=voxel_size,
bg_value=background_value,
translation=translation,
device=device,
)
volume_b = wp.Volume.allocate(
-bb_max * voxel_size + translation,
bb_max * voxel_size + translation,
voxel_size=voxel_size,
bg_value=background_value,
translation=translation,
points_in_world_space=True,
device=device,
)
points = wp.array(points_ref, dtype=wp.vec3, device=device)
values_a = wp.empty(num_points, dtype=wp.float32, device=device)
values_b = wp.empty(num_points, dtype=wp.float32, device=device)
wp.launch(test_volume_store_f, dim=num_points, inputs=[volume_a.id, points], device=device)
wp.launch(test_volume_store_f, dim=num_points, inputs=[volume_b.id, points], device=device)
wp.launch(test_volume_readback_f, dim=num_points, inputs=[volume_a.id, points, values_a], device=device)
wp.launch(test_volume_readback_f, dim=num_points, inputs=[volume_b.id, points, values_b], device=device)
np.testing.assert_equal(values_a.numpy(), values_ref)
np.testing.assert_equal(values_b.numpy(), values_ref)
def test_volume_allocate_by_tiles_f(self):
voxel_size = 0.125
background_value = 123.456
translation = wp.vec3(-12.3, 4.56, -789)
num_tiles = 1000
tiles = rng.integers(-512, 512, size=(num_tiles, 3), dtype=np.int32)
points_is = tiles * 8 # points in index space
points_ws = points_is * voxel_size + translation # points in world space
values_ref = np.empty(num_tiles * 512)
for t in range(num_tiles):
ti, tj, tk = points_is[t]
for i in range(8):
for j in range(8):
for k in range(8):
values_ref[t * 512 + i * 64 + j * 8 + k] = float(100 * (ti + i) + 10 * (tj + j) + (tk + k))
for device in devices:
if device.is_cpu:
continue
points_is_d = wp.array(points_is, dtype=wp.int32, device=device)
points_ws_d = wp.array(points_ws, dtype=wp.vec3, device=device)
volume_a = wp.Volume.allocate_by_tiles(
points_is_d, voxel_size, background_value, translation, device=device
)
volume_b = wp.Volume.allocate_by_tiles(
points_ws_d, voxel_size, background_value, translation, device=device
)
values_a = wp.empty(num_tiles * 512, dtype=wp.float32, device=device)
values_b = wp.empty(num_tiles * 512, dtype=wp.float32, device=device)
wp.launch(test_volume_tile_store_f, dim=num_tiles, inputs=[volume_a.id, points_is_d], device=device)
wp.launch(test_volume_tile_store_ws_f, dim=num_tiles, inputs=[volume_b.id, points_ws_d], device=device)
wp.launch(
test_volume_tile_readback_f,
dim=num_tiles,
inputs=[volume_a.id, points_is_d, values_a],
device=device,
)
wp.launch(
test_volume_tile_readback_f,
dim=num_tiles,
inputs=[volume_b.id, points_is_d, values_b],
device=device,
)
np.testing.assert_equal(values_a.numpy(), values_ref)
np.testing.assert_equal(values_b.numpy(), values_ref)
def test_volume_allocate_by_tiles_v(self):
num_tiles = 1000
tiles = rng.integers(-512, 512, size=(num_tiles, 3), dtype=np.int32)
points_is = tiles * 8
values_ref = np.empty((len(tiles) * 512, 3))
for t in range(len(tiles)):
ti, tj, tk = points_is[t]
for i in range(8):
for j in range(8):
for k in range(8):
values_ref[t * 512 + i * 64 + j * 8 + k] = [ti + i, tj + j, tk + k]
for device in devices:
if device.is_cpu:
continue
points_d = wp.array(points_is, dtype=wp.int32, device=device)
volume = wp.Volume.allocate_by_tiles(points_d, 0.1, wp.vec3(1, 2, 3), device=device)
values = wp.empty(len(points_d) * 512, dtype=wp.vec3, device=device)
wp.launch(test_volume_tile_store_v, dim=len(points_d), inputs=[volume.id, points_d], device=device)
wp.launch(
test_volume_tile_readback_v, dim=len(points_d), inputs=[volume.id, points_d, values], device=device
)
values_res = values.numpy()
np.testing.assert_equal(values_res, values_ref)
return TestVolumes
if __name__ == "__main__":
wp.force_load()
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_volume_write.py |
import warp as wp
wp.init()
@wp.func
def multiply(x: float):
return x * x
@wp.kernel
def kern(expect: float):
wp.expect_eq(multiply(4.0), expect)
def run(expect, device):
wp.launch(kern, dim=1, inputs=[expect], device=device)
| warp-main | warp/tests/test_square.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
# include parent path
import numpy as np
import math
import warp as wp
from warp.tests.test_base import *
import unittest
wp.init()
# construct kernel + test function for atomic ops on each vec/matrix type
def make_atomic_test(type):
def test_atomic_kernel(
out_add: wp.array(dtype=type),
out_min: wp.array(dtype=type),
out_max: wp.array(dtype=type),
val: wp.array(dtype=type),
):
tid = wp.tid()
wp.atomic_add(out_add, 0, val[tid])
wp.atomic_min(out_min, 0, val[tid])
wp.atomic_max(out_max, 0, val[tid])
# register a custom kernel (no decorator) function
# this lets us register the same function definition
# against multiple symbols, with different arg types
module = wp.get_module(test_atomic_kernel.__module__)
kernel = wp.Kernel(func=test_atomic_kernel, key=f"test_atomic_{type.__name__}_kernel", module=module)
def test_atomic(test, device):
n = 1024
rng = np.random.default_rng(42)
if type == wp.int32:
base = (rng.random(size=1, dtype=np.float32) * 100.0).astype(np.int32)
val = (rng.random(size=n, dtype=np.float32) * 100.0).astype(np.int32)
elif type == wp.float32:
base = rng.random(size=1, dtype=np.float32)
val = rng.random(size=n, dtype=np.float32)
else:
base = rng.random(size=(1, *type._shape_), dtype=float)
val = rng.random(size=(n, *type._shape_), dtype=float)
add_array = wp.array(base, dtype=type, device=device)
min_array = wp.array(base, dtype=type, device=device)
max_array = wp.array(base, dtype=type, device=device)
val_array = wp.array(val, dtype=type, device=device)
wp.launch(kernel, n, inputs=[add_array, min_array, max_array, val_array], device=device)
val = np.append(val, [base[0]], axis=0)
assert_np_equal(add_array.numpy(), np.sum(val, axis=0), tol=1.0e-2)
assert_np_equal(min_array.numpy(), np.min(val, axis=0), tol=1.0e-2)
assert_np_equal(max_array.numpy(), np.max(val, axis=0), tol=1.0e-2)
return test_atomic
# generate test functions for atomic types
test_atomic_int = make_atomic_test(wp.int32)
test_atomic_float = make_atomic_test(wp.float32)
test_atomic_vec2 = make_atomic_test(wp.vec2)
test_atomic_vec3 = make_atomic_test(wp.vec3)
test_atomic_vec4 = make_atomic_test(wp.vec4)
test_atomic_mat22 = make_atomic_test(wp.mat22)
test_atomic_mat33 = make_atomic_test(wp.mat33)
test_atomic_mat44 = make_atomic_test(wp.mat44)
def register(parent):
devices = get_test_devices()
class TestAtomic(parent):
pass
add_function_test(TestAtomic, "test_atomic_int", test_atomic_int, devices=devices)
add_function_test(TestAtomic, "test_atomic_float", test_atomic_float, devices=devices)
add_function_test(TestAtomic, "test_atomic_vec2", test_atomic_vec2, devices=devices)
add_function_test(TestAtomic, "test_atomic_vec3", test_atomic_vec3, devices=devices)
add_function_test(TestAtomic, "test_atomic_vec4", test_atomic_vec4, devices=devices)
add_function_test(TestAtomic, "test_atomic_mat22", test_atomic_mat22, devices=devices)
add_function_test(TestAtomic, "test_atomic_mat33", test_atomic_mat33, devices=devices)
add_function_test(TestAtomic, "test_atomic_mat44", test_atomic_mat44, devices=devices)
return TestAtomic
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_atomic.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import math
import unittest
# include parent path
import numpy as np
import warp as wp
from warp.tests.test_base import *
wp.init()
@wp.kernel
def kernel_1d(a: wp.array(dtype=int, ndim=1)):
i = wp.tid()
wp.expect_eq(a[i], wp.tid())
a[i] = a[i] * 2
wp.atomic_add(a, i, 1)
wp.expect_eq(a[i], wp.tid() * 2 + 1)
def test_1d(test, device):
dim_x = 4
a = np.arange(0, dim_x, dtype=np.int32)
arr = wp.array(a, device=device)
test.assertEqual(arr.shape, a.shape)
test.assertEqual(arr.size, a.size)
test.assertEqual(arr.ndim, a.ndim)
with CheckOutput(test):
wp.launch(kernel_1d, dim=arr.size, inputs=[arr], device=device)
@wp.kernel
def kernel_2d(a: wp.array(dtype=int, ndim=2), m: int, n: int):
i = wp.tid() // n
j = wp.tid() % n
wp.expect_eq(a[i, j], wp.tid())
wp.expect_eq(a[i][j], wp.tid())
a[i, j] = a[i, j] * 2
wp.atomic_add(a, i, j, 1)
wp.expect_eq(a[i, j], wp.tid() * 2 + 1)
def test_2d(test, device):
dim_x = 4
dim_y = 2
a = np.arange(0, dim_x * dim_y, dtype=np.int32)
a = a.reshape(dim_x, dim_y)
arr = wp.array(a, device=device)
test.assertEqual(arr.shape, a.shape)
test.assertEqual(arr.size, a.size)
test.assertEqual(arr.ndim, a.ndim)
with CheckOutput(test):
wp.launch(kernel_2d, dim=arr.size, inputs=[arr, dim_x, dim_y], device=device)
@wp.kernel
def kernel_3d(a: wp.array(dtype=int, ndim=3), m: int, n: int, o: int):
i = wp.tid() // (n * o)
j = wp.tid() % (n * o) // o
k = wp.tid() % o
wp.expect_eq(a[i, j, k], wp.tid())
wp.expect_eq(a[i][j][k], wp.tid())
a[i, j, k] = a[i, j, k] * 2
a[i][j][k] = a[i][j][k] * 2
wp.atomic_add(a, i, j, k, 1)
wp.expect_eq(a[i, j, k], wp.tid() * 4 + 1)
def test_3d(test, device):
dim_x = 8
dim_y = 4
dim_z = 2
a = np.arange(0, dim_x * dim_y * dim_z, dtype=np.int32)
a = a.reshape(dim_x, dim_y, dim_z)
arr = wp.array(a, device=device)
test.assertEqual(arr.shape, a.shape)
test.assertEqual(arr.size, a.size)
test.assertEqual(arr.ndim, a.ndim)
with CheckOutput(test):
wp.launch(kernel_3d, dim=arr.size, inputs=[arr, dim_x, dim_y, dim_z], device=device)
@wp.kernel
def kernel_4d(a: wp.array(dtype=int, ndim=4), m: int, n: int, o: int, p: int):
i = wp.tid() // (n * o * p)
j = wp.tid() % (n * o * p) // (o * p)
k = wp.tid() % (o * p) / p
l = wp.tid() % p
wp.expect_eq(a[i, j, k, l], wp.tid())
wp.expect_eq(a[i][j][k][l], wp.tid())
def test_4d(test, device):
dim_x = 16
dim_y = 8
dim_z = 4
dim_w = 2
a = np.arange(0, dim_x * dim_y * dim_z * dim_w, dtype=np.int32)
a = a.reshape(dim_x, dim_y, dim_z, dim_w)
arr = wp.array(a, device=device)
test.assertEqual(arr.shape, a.shape)
test.assertEqual(arr.size, a.size)
test.assertEqual(arr.ndim, a.ndim)
with CheckOutput(test):
wp.launch(kernel_4d, dim=arr.size, inputs=[arr, dim_x, dim_y, dim_z, dim_w], device=device)
@wp.kernel
def kernel_4d_transposed(a: wp.array(dtype=int, ndim=4), m: int, n: int, o: int, p: int):
i = wp.tid() // (n * o * p)
j = wp.tid() % (n * o * p) // (o * p)
k = wp.tid() % (o * p) / p
l = wp.tid() % p
wp.expect_eq(a[l, k, j, i], wp.tid())
wp.expect_eq(a[l][k][j][i], wp.tid())
def test_4d_transposed(test, device):
dim_x = 16
dim_y = 8
dim_z = 4
dim_w = 2
a = np.arange(0, dim_x * dim_y * dim_z * dim_w, dtype=np.int32)
a = a.reshape(dim_x, dim_y, dim_z, dim_w)
arr = wp.array(a, device=device)
# Transpose the array manually, as using the wp.array() constructor with arr.T would make it contiguous first
a_T = a.T
arr_T = wp.array(
dtype=arr.dtype,
shape=a_T.shape,
strides=a_T.__array_interface__["strides"],
capacity=arr.capacity,
ptr=arr.ptr,
owner=False,
requires_grad=arr.requires_grad,
device=device,
)
test.assertFalse(arr_T.is_contiguous)
test.assertEqual(arr_T.shape, a_T.shape)
test.assertEqual(arr_T.strides, a_T.__array_interface__["strides"])
test.assertEqual(arr_T.size, a_T.size)
test.assertEqual(arr_T.ndim, a_T.ndim)
with CheckOutput(test):
wp.launch(kernel_4d_transposed, dim=arr_T.size, inputs=[arr_T, dim_x, dim_y, dim_z, dim_w], device=device)
@wp.kernel
def lower_bound_kernel(values: wp.array(dtype=float), arr: wp.array(dtype=float), indices: wp.array(dtype=int)):
tid = wp.tid()
indices[tid] = wp.lower_bound(arr, values[tid])
def test_lower_bound(test, device):
arr = wp.array(np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0], dtype=float), dtype=float, device=device)
values = wp.array(np.array([-0.1, 0.0, 2.5, 4.0, 5.0, 5.5], dtype=float), dtype=float, device=device)
indices = wp.zeros(6, dtype=int, device=device)
wp.launch(kernel=lower_bound_kernel, dim=6, inputs=[values, arr, indices], device=device)
test.assertTrue((np.array([0, 0, 3, 4, 5, 5]) == indices.numpy()).all())
@wp.kernel
def f1(arr: wp.array(dtype=float)):
wp.expect_eq(arr.shape[0], 10)
@wp.kernel
def f2(arr: wp.array2d(dtype=float)):
wp.expect_eq(arr.shape[0], 10)
wp.expect_eq(arr.shape[1], 20)
slice = arr[0]
wp.expect_eq(slice.shape[0], 20)
@wp.kernel
def f3(arr: wp.array3d(dtype=float)):
wp.expect_eq(arr.shape[0], 10)
wp.expect_eq(arr.shape[1], 20)
wp.expect_eq(arr.shape[2], 30)
slice = arr[0, 0]
wp.expect_eq(slice.shape[0], 30)
@wp.kernel
def f4(arr: wp.array4d(dtype=float)):
wp.expect_eq(arr.shape[0], 10)
wp.expect_eq(arr.shape[1], 20)
wp.expect_eq(arr.shape[2], 30)
wp.expect_eq(arr.shape[3], 40)
slice = arr[0, 0, 0]
wp.expect_eq(slice.shape[0], 40)
def test_shape(test, device):
with CheckOutput(test):
a1 = wp.zeros(dtype=float, shape=10, device=device)
wp.launch(f1, dim=1, inputs=[a1], device=device)
a2 = wp.zeros(dtype=float, shape=(10, 20), device=device)
wp.launch(f2, dim=1, inputs=[a2], device=device)
a3 = wp.zeros(dtype=float, shape=(10, 20, 30), device=device)
wp.launch(f3, dim=1, inputs=[a3], device=device)
a4 = wp.zeros(dtype=float, shape=(10, 20, 30, 40), device=device)
wp.launch(f4, dim=1, inputs=[a4], device=device)
@wp.kernel
def sum_array(arr: wp.array(dtype=float), loss: wp.array(dtype=float)):
tid = wp.tid()
wp.atomic_add(loss, 0, arr[tid])
def test_flatten(test, device):
np_arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], dtype=float)
arr = wp.array(np_arr, dtype=float, shape=np_arr.shape, device=device, requires_grad=True)
arr_flat = arr.flatten()
arr_comp = wp.array(np_arr.flatten(), dtype=float, device=device)
assert_array_equal(arr_flat, arr_comp)
loss = wp.zeros(1, dtype=float, device=device, requires_grad=True)
tape = wp.Tape()
with tape:
wp.launch(kernel=sum_array, dim=len(arr_flat), inputs=[arr_flat, loss], device=device)
tape.backward(loss=loss)
grad = tape.gradients[arr_flat]
ones = wp.array(
np.ones(
(8,),
dtype=float,
),
dtype=float,
device=device,
)
assert_array_equal(grad, ones)
test.assertEqual(loss.numpy()[0], 36)
def test_reshape(test, device):
np_arr = np.arange(6, dtype=float)
arr = wp.array(np_arr, dtype=float, device=device, requires_grad=True)
arr_reshaped = arr.reshape((3, 2))
arr_comp = wp.array(np_arr.reshape((3, 2)), dtype=float, device=device)
assert_array_equal(arr_reshaped, arr_comp)
arr_reshaped = arr_reshaped.reshape(6)
assert_array_equal(arr_reshaped, arr)
loss = wp.zeros(1, dtype=float, device=device, requires_grad=True)
tape = wp.Tape()
with tape:
wp.launch(kernel=sum_array, dim=len(arr_reshaped), inputs=[arr_reshaped, loss], device=device)
tape.backward(loss=loss)
grad = tape.gradients[arr_reshaped]
ones = wp.array(
np.ones(
(6,),
dtype=float,
),
dtype=float,
device=device,
)
assert_array_equal(grad, ones)
test.assertEqual(loss.numpy()[0], 15)
np_arr = np.arange(6, dtype=float)
arr = wp.array(np_arr, dtype=float, device=device)
arr_infer = arr.reshape((-1, 3))
arr_comp = wp.array(np_arr.reshape((-1, 3)), dtype=float, device=device)
assert_array_equal(arr_infer, arr_comp)
@wp.kernel
def compare_stepped_window_a(x: wp.array2d(dtype=float)):
wp.expect_eq(x[0, 0], 1.0)
wp.expect_eq(x[0, 1], 2.0)
wp.expect_eq(x[1, 0], 9.0)
wp.expect_eq(x[1, 1], 10.0)
@wp.kernel
def compare_stepped_window_b(x: wp.array2d(dtype=float)):
wp.expect_eq(x[0, 0], 3.0)
wp.expect_eq(x[0, 1], 4.0)
wp.expect_eq(x[1, 0], 7.0)
wp.expect_eq(x[1, 1], 8.0)
wp.expect_eq(x[2, 0], 11.0)
wp.expect_eq(x[2, 1], 12.0)
def test_slicing(test, device):
np_arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=float)
arr = wp.array(np_arr, dtype=float, shape=np_arr.shape, device=device, requires_grad=True)
slice_a = arr[1, :, :] # test indexing
slice_b = arr[1:2, :, :] # test slicing
slice_c = arr[-1, :, :] # test negative indexing
slice_d = arr[-2:-1, :, :] # test negative slicing
slice_e = arr[-1:3, :, :] # test mixed slicing
slice_e2 = slice_e[0, 0, :] # test 2x slicing
slice_f = arr[0:3:2, 0, :] # test step
assert_array_equal(slice_a, wp.array(np_arr[1, :, :], dtype=float, device=device))
assert_array_equal(slice_b, wp.array(np_arr[1:2, :, :], dtype=float, device=device))
assert_array_equal(slice_c, wp.array(np_arr[-1, :, :], dtype=float, device=device))
assert_array_equal(slice_d, wp.array(np_arr[-2:-1, :, :], dtype=float, device=device))
assert_array_equal(slice_e, wp.array(np_arr[-1:3, :, :], dtype=float, device=device))
assert_array_equal(slice_e2, wp.array(np_arr[2, 0, :], dtype=float, device=device))
# wp does not support copying from/to non-contiguous arrays
# stepped windows must read on the device the original array was created on
wp.launch(kernel=compare_stepped_window_a, dim=1, inputs=[slice_f], device=device)
slice_flat = slice_b.flatten()
loss = wp.zeros(1, dtype=float, device=device, requires_grad=True)
tape = wp.Tape()
with tape:
wp.launch(kernel=sum_array, dim=len(slice_flat), inputs=[slice_flat, loss], device=device)
tape.backward(loss=loss)
grad = tape.gradients[slice_flat]
ones = wp.array(
np.ones(
(4,),
dtype=float,
),
dtype=float,
device=device,
)
assert_array_equal(grad, ones)
test.assertEqual(loss.numpy()[0], 26)
index_a = arr[1]
index_b = arr[2, 1]
index_c = arr[1, :]
index_d = arr[:, 1]
assert_array_equal(index_a, wp.array(np_arr[1], dtype=float, device=device))
assert_array_equal(index_b, wp.array(np_arr[2, 1], dtype=float, device=device))
assert_array_equal(index_c, wp.array(np_arr[1, :], dtype=float, device=device))
wp.launch(kernel=compare_stepped_window_b, dim=1, inputs=[index_d], device=device)
np_arr = np.zeros(10, dtype=int)
wp_arr = wp.array(np_arr, dtype=int, device=device)
assert_array_equal(wp_arr[:5], wp.array(np_arr[:5], dtype=int, device=device))
assert_array_equal(wp_arr[1:5], wp.array(np_arr[1:5], dtype=int, device=device))
assert_array_equal(wp_arr[-9:-5:1], wp.array(np_arr[-9:-5:1], dtype=int, device=device))
assert_array_equal(wp_arr[:5,], wp.array(np_arr[:5], dtype=int, device=device)) # noqa: E231
def test_view(test, device):
np_arr_a = np.arange(1, 10, 1, dtype=np.uint32)
np_arr_b = np.arange(1, 10, 1, dtype=np.float32)
np_arr_c = np.arange(1, 10, 1, dtype=np.uint16)
np_arr_d = np.arange(1, 10, 1, dtype=np.float16)
np_arr_e = np.ones((4, 4), dtype=np.float32)
wp_arr_a = wp.array(np_arr_a, dtype=wp.uint32, device=device)
wp_arr_b = wp.array(np_arr_b, dtype=wp.float32, device=device)
wp_arr_c = wp.array(np_arr_a, dtype=wp.uint16, device=device)
wp_arr_d = wp.array(np_arr_b, dtype=wp.float16, device=device)
wp_arr_e = wp.array(np_arr_e, dtype=wp.vec4, device=device)
wp_arr_f = wp.array(np_arr_e, dtype=wp.quat, device=device)
assert np.array_equal(np_arr_a.view(dtype=np.float32), wp_arr_a.view(dtype=wp.float32).numpy())
assert np.array_equal(np_arr_b.view(dtype=np.uint32), wp_arr_b.view(dtype=wp.uint32).numpy())
assert np.array_equal(np_arr_c.view(dtype=np.float16), wp_arr_c.view(dtype=wp.float16).numpy())
assert np.array_equal(np_arr_d.view(dtype=np.uint16), wp_arr_d.view(dtype=wp.uint16).numpy())
assert_array_equal(wp_arr_e.view(dtype=wp.quat), wp_arr_f)
@wp.kernel
def compare_2darrays(x: wp.array2d(dtype=float), y: wp.array2d(dtype=float), z: wp.array2d(dtype=int)):
i, j = wp.tid()
if x[i, j] == y[i, j]:
z[i, j] = 1
@wp.kernel
def compare_3darrays(x: wp.array3d(dtype=float), y: wp.array3d(dtype=float), z: wp.array3d(dtype=int)):
i, j, k = wp.tid()
if x[i, j, k] == y[i, j, k]:
z[i, j, k] = 1
def test_transpose(test, device):
# test default transpose in non-square 2d case
# wp does not support copying from/to non-contiguous arrays so check in kernel
np_arr = np.array([[1, 2], [3, 4], [5, 6]], dtype=float)
arr = wp.array(np_arr, dtype=float, device=device)
arr_transpose = arr.transpose()
arr_compare = wp.array(np_arr.transpose(), dtype=float, device=device)
check = wp.zeros(shape=(2, 3), dtype=int, device=device)
wp.launch(compare_2darrays, dim=(2, 3), inputs=[arr_transpose, arr_compare, check], device=device)
assert np.array_equal(check.numpy(), np.ones((2, 3), dtype=int))
# test transpose in square 3d case
# wp does not support copying from/to non-contiguous arrays so check in kernel
np_arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=float)
arr = wp.array3d(np_arr, dtype=float, shape=np_arr.shape, device=device, requires_grad=True)
arr_transpose = arr.transpose((0, 2, 1))
arr_compare = wp.array3d(np_arr.transpose((0, 2, 1)), dtype=float, device=device)
check = wp.zeros(shape=(3, 2, 2), dtype=int, device=device)
wp.launch(compare_3darrays, dim=(3, 2, 2), inputs=[arr_transpose, arr_compare, check], device=device)
assert np.array_equal(check.numpy(), np.ones((3, 2, 2), dtype=int))
# test transpose in square 3d case without axes supplied
arr_transpose = arr.transpose()
arr_compare = wp.array3d(np_arr.transpose(), dtype=float, device=device)
check = wp.zeros(shape=(2, 2, 3), dtype=int, device=device)
wp.launch(compare_3darrays, dim=(2, 2, 3), inputs=[arr_transpose, arr_compare, check], device=device)
assert np.array_equal(check.numpy(), np.ones((2, 2, 3), dtype=int))
# test transpose in 1d case (should be noop)
np_arr = np.array([1, 2, 3], dtype=float)
arr = wp.array(np_arr, dtype=float, device=device)
assert np.array_equal(np_arr.transpose(), arr.transpose().numpy())
def test_fill_scalar(test, device):
dim_x = 4
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
a1 = wp.zeros(dim_x, dtype=wptype, device=device)
a2 = wp.zeros((dim_x, dim_x), dtype=wptype, device=device)
a3 = wp.zeros((dim_x, dim_x, dim_x), dtype=wptype, device=device)
a4 = wp.zeros((dim_x, dim_x, dim_x, dim_x), dtype=wptype, device=device)
assert_np_equal(a1.numpy(), np.zeros(a1.shape, dtype=nptype))
assert_np_equal(a2.numpy(), np.zeros(a2.shape, dtype=nptype))
assert_np_equal(a3.numpy(), np.zeros(a3.shape, dtype=nptype))
assert_np_equal(a4.numpy(), np.zeros(a4.shape, dtype=nptype))
# fill with int value
fill_value = 42
a1.fill_(fill_value)
a2.fill_(fill_value)
a3.fill_(fill_value)
a4.fill_(fill_value)
assert_np_equal(a1.numpy(), np.full(a1.shape, fill_value, dtype=nptype))
assert_np_equal(a2.numpy(), np.full(a2.shape, fill_value, dtype=nptype))
assert_np_equal(a3.numpy(), np.full(a3.shape, fill_value, dtype=nptype))
assert_np_equal(a4.numpy(), np.full(a4.shape, fill_value, dtype=nptype))
a1.zero_()
a2.zero_()
a3.zero_()
a4.zero_()
assert_np_equal(a1.numpy(), np.zeros(a1.shape, dtype=nptype))
assert_np_equal(a2.numpy(), np.zeros(a2.shape, dtype=nptype))
assert_np_equal(a3.numpy(), np.zeros(a3.shape, dtype=nptype))
assert_np_equal(a4.numpy(), np.zeros(a4.shape, dtype=nptype))
if wptype in wp.types.float_types:
# fill with float value
fill_value = 13.37
a1.fill_(fill_value)
a2.fill_(fill_value)
a3.fill_(fill_value)
a4.fill_(fill_value)
assert_np_equal(a1.numpy(), np.full(a1.shape, fill_value, dtype=nptype))
assert_np_equal(a2.numpy(), np.full(a2.shape, fill_value, dtype=nptype))
assert_np_equal(a3.numpy(), np.full(a3.shape, fill_value, dtype=nptype))
assert_np_equal(a4.numpy(), np.full(a4.shape, fill_value, dtype=nptype))
# fill with Warp scalar value
fill_value = wptype(17)
a1.fill_(fill_value)
a2.fill_(fill_value)
a3.fill_(fill_value)
a4.fill_(fill_value)
assert_np_equal(a1.numpy(), np.full(a1.shape, fill_value.value, dtype=nptype))
assert_np_equal(a2.numpy(), np.full(a2.shape, fill_value.value, dtype=nptype))
assert_np_equal(a3.numpy(), np.full(a3.shape, fill_value.value, dtype=nptype))
assert_np_equal(a4.numpy(), np.full(a4.shape, fill_value.value, dtype=nptype))
def test_fill_vector(test, device):
# test filling a vector array with scalar or vector values (vec_type, list, or numpy array)
dim_x = 4
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
# vector types
vector_types = [
wp.types.vector(2, wptype),
wp.types.vector(3, wptype),
wp.types.vector(4, wptype),
wp.types.vector(5, wptype),
]
for vec_type in vector_types:
vec_len = vec_type._length_
a1 = wp.zeros(dim_x, dtype=vec_type, device=device)
a2 = wp.zeros((dim_x, dim_x), dtype=vec_type, device=device)
a3 = wp.zeros((dim_x, dim_x, dim_x), dtype=vec_type, device=device)
a4 = wp.zeros((dim_x, dim_x, dim_x, dim_x), dtype=vec_type, device=device)
assert_np_equal(a1.numpy(), np.zeros((*a1.shape, vec_len), dtype=nptype))
assert_np_equal(a2.numpy(), np.zeros((*a2.shape, vec_len), dtype=nptype))
assert_np_equal(a3.numpy(), np.zeros((*a3.shape, vec_len), dtype=nptype))
assert_np_equal(a4.numpy(), np.zeros((*a4.shape, vec_len), dtype=nptype))
# fill with int scalar
fill_value = 42
a1.fill_(fill_value)
a2.fill_(fill_value)
a3.fill_(fill_value)
a4.fill_(fill_value)
assert_np_equal(a1.numpy(), np.full((*a1.shape, vec_len), fill_value, dtype=nptype))
assert_np_equal(a2.numpy(), np.full((*a2.shape, vec_len), fill_value, dtype=nptype))
assert_np_equal(a3.numpy(), np.full((*a3.shape, vec_len), fill_value, dtype=nptype))
assert_np_equal(a4.numpy(), np.full((*a4.shape, vec_len), fill_value, dtype=nptype))
# test zeroing
a1.zero_()
a2.zero_()
a3.zero_()
a4.zero_()
assert_np_equal(a1.numpy(), np.zeros((*a1.shape, vec_len), dtype=nptype))
assert_np_equal(a2.numpy(), np.zeros((*a2.shape, vec_len), dtype=nptype))
assert_np_equal(a3.numpy(), np.zeros((*a3.shape, vec_len), dtype=nptype))
assert_np_equal(a4.numpy(), np.zeros((*a4.shape, vec_len), dtype=nptype))
# vector values can be passed as a list, numpy array, or Warp vector instance
fill_list = [17, 42, 99, 101, 127][:vec_len]
fill_arr = np.array(fill_list, dtype=nptype)
fill_vec = vec_type(fill_list)
expected1 = np.tile(fill_arr, a1.size).reshape((*a1.shape, vec_len))
expected2 = np.tile(fill_arr, a2.size).reshape((*a2.shape, vec_len))
expected3 = np.tile(fill_arr, a3.size).reshape((*a3.shape, vec_len))
expected4 = np.tile(fill_arr, a4.size).reshape((*a4.shape, vec_len))
# fill with list of vector length
a1.fill_(fill_list)
a2.fill_(fill_list)
a3.fill_(fill_list)
a4.fill_(fill_list)
assert_np_equal(a1.numpy(), expected1)
assert_np_equal(a2.numpy(), expected2)
assert_np_equal(a3.numpy(), expected3)
assert_np_equal(a4.numpy(), expected4)
# clear
a1.zero_()
a2.zero_()
a3.zero_()
a4.zero_()
# fill with numpy array of vector length
a1.fill_(fill_arr)
a2.fill_(fill_arr)
a3.fill_(fill_arr)
a4.fill_(fill_arr)
assert_np_equal(a1.numpy(), expected1)
assert_np_equal(a2.numpy(), expected2)
assert_np_equal(a3.numpy(), expected3)
assert_np_equal(a4.numpy(), expected4)
# clear
a1.zero_()
a2.zero_()
a3.zero_()
a4.zero_()
# fill with vec instance
a1.fill_(fill_vec)
a2.fill_(fill_vec)
a3.fill_(fill_vec)
a4.fill_(fill_vec)
assert_np_equal(a1.numpy(), expected1)
assert_np_equal(a2.numpy(), expected2)
assert_np_equal(a3.numpy(), expected3)
assert_np_equal(a4.numpy(), expected4)
if wptype in wp.types.float_types:
# fill with float scalar
fill_value = 13.37
a1.fill_(fill_value)
a2.fill_(fill_value)
a3.fill_(fill_value)
a4.fill_(fill_value)
assert_np_equal(a1.numpy(), np.full((*a1.shape, vec_len), fill_value, dtype=nptype))
assert_np_equal(a2.numpy(), np.full((*a2.shape, vec_len), fill_value, dtype=nptype))
assert_np_equal(a3.numpy(), np.full((*a3.shape, vec_len), fill_value, dtype=nptype))
assert_np_equal(a4.numpy(), np.full((*a4.shape, vec_len), fill_value, dtype=nptype))
# fill with float list of vector length
fill_list = [-2.5, -1.25, 1.25, 2.5, 5.0][:vec_len]
a1.fill_(fill_list)
a2.fill_(fill_list)
a3.fill_(fill_list)
a4.fill_(fill_list)
expected1 = np.tile(np.array(fill_list, dtype=nptype), a1.size).reshape((*a1.shape, vec_len))
expected2 = np.tile(np.array(fill_list, dtype=nptype), a2.size).reshape((*a2.shape, vec_len))
expected3 = np.tile(np.array(fill_list, dtype=nptype), a3.size).reshape((*a3.shape, vec_len))
expected4 = np.tile(np.array(fill_list, dtype=nptype), a4.size).reshape((*a4.shape, vec_len))
assert_np_equal(a1.numpy(), expected1)
assert_np_equal(a2.numpy(), expected2)
assert_np_equal(a3.numpy(), expected3)
assert_np_equal(a4.numpy(), expected4)
def test_fill_matrix(test, device):
# test filling a matrix array with scalar or matrix values (mat_type, nested list, or 2d numpy array)
dim_x = 4
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
# matrix types
matrix_types = [
# square matrices
wp.types.matrix((2, 2), wptype),
wp.types.matrix((3, 3), wptype),
wp.types.matrix((4, 4), wptype),
wp.types.matrix((5, 5), wptype),
# non-square matrices
wp.types.matrix((2, 3), wptype),
wp.types.matrix((3, 2), wptype),
wp.types.matrix((3, 4), wptype),
wp.types.matrix((4, 3), wptype),
]
for mat_type in matrix_types:
mat_len = mat_type._length_
mat_shape = mat_type._shape_
a1 = wp.zeros(dim_x, dtype=mat_type, device=device)
a2 = wp.zeros((dim_x, dim_x), dtype=mat_type, device=device)
a3 = wp.zeros((dim_x, dim_x, dim_x), dtype=mat_type, device=device)
a4 = wp.zeros((dim_x, dim_x, dim_x, dim_x), dtype=mat_type, device=device)
assert_np_equal(a1.numpy(), np.zeros((*a1.shape, *mat_shape), dtype=nptype))
assert_np_equal(a2.numpy(), np.zeros((*a2.shape, *mat_shape), dtype=nptype))
assert_np_equal(a3.numpy(), np.zeros((*a3.shape, *mat_shape), dtype=nptype))
assert_np_equal(a4.numpy(), np.zeros((*a4.shape, *mat_shape), dtype=nptype))
# fill with scalar
fill_value = 42
a1.fill_(fill_value)
a2.fill_(fill_value)
a3.fill_(fill_value)
a4.fill_(fill_value)
assert_np_equal(a1.numpy(), np.full((*a1.shape, *mat_shape), fill_value, dtype=nptype))
assert_np_equal(a2.numpy(), np.full((*a2.shape, *mat_shape), fill_value, dtype=nptype))
assert_np_equal(a3.numpy(), np.full((*a3.shape, *mat_shape), fill_value, dtype=nptype))
assert_np_equal(a4.numpy(), np.full((*a4.shape, *mat_shape), fill_value, dtype=nptype))
# test zeroing
a1.zero_()
a2.zero_()
a3.zero_()
a4.zero_()
assert_np_equal(a1.numpy(), np.zeros((*a1.shape, *mat_shape), dtype=nptype))
assert_np_equal(a2.numpy(), np.zeros((*a2.shape, *mat_shape), dtype=nptype))
assert_np_equal(a3.numpy(), np.zeros((*a3.shape, *mat_shape), dtype=nptype))
assert_np_equal(a4.numpy(), np.zeros((*a4.shape, *mat_shape), dtype=nptype))
# matrix values can be passed as a 1d numpy array, 2d numpy array, flat list, nested list, or Warp matrix instance
if wptype != wp.bool:
fill_arr1 = np.arange(mat_len, dtype=nptype)
else:
fill_arr1 = np.ones(mat_len, dtype=nptype)
fill_arr2 = fill_arr1.reshape(mat_shape)
fill_list1 = list(fill_arr1)
fill_list2 = [list(row) for row in fill_arr2]
fill_mat = mat_type(fill_arr1)
expected1 = np.tile(fill_arr1, a1.size).reshape((*a1.shape, *mat_shape))
expected2 = np.tile(fill_arr1, a2.size).reshape((*a2.shape, *mat_shape))
expected3 = np.tile(fill_arr1, a3.size).reshape((*a3.shape, *mat_shape))
expected4 = np.tile(fill_arr1, a4.size).reshape((*a4.shape, *mat_shape))
# fill with 1d numpy array
a1.fill_(fill_arr1)
a2.fill_(fill_arr1)
a3.fill_(fill_arr1)
a4.fill_(fill_arr1)
assert_np_equal(a1.numpy(), expected1)
assert_np_equal(a2.numpy(), expected2)
assert_np_equal(a3.numpy(), expected3)
assert_np_equal(a4.numpy(), expected4)
# clear
a1.zero_()
a2.zero_()
a3.zero_()
a4.zero_()
# fill with 2d numpy array
a1.fill_(fill_arr2)
a2.fill_(fill_arr2)
a3.fill_(fill_arr2)
a4.fill_(fill_arr2)
assert_np_equal(a1.numpy(), expected1)
assert_np_equal(a2.numpy(), expected2)
assert_np_equal(a3.numpy(), expected3)
assert_np_equal(a4.numpy(), expected4)
# clear
a1.zero_()
a2.zero_()
a3.zero_()
a4.zero_()
# fill with flat list
a1.fill_(fill_list1)
a2.fill_(fill_list1)
a3.fill_(fill_list1)
a4.fill_(fill_list1)
assert_np_equal(a1.numpy(), expected1)
assert_np_equal(a2.numpy(), expected2)
assert_np_equal(a3.numpy(), expected3)
assert_np_equal(a4.numpy(), expected4)
# clear
a1.zero_()
a2.zero_()
a3.zero_()
a4.zero_()
# fill with nested list
a1.fill_(fill_list2)
a2.fill_(fill_list2)
a3.fill_(fill_list2)
a4.fill_(fill_list2)
assert_np_equal(a1.numpy(), expected1)
assert_np_equal(a2.numpy(), expected2)
assert_np_equal(a3.numpy(), expected3)
assert_np_equal(a4.numpy(), expected4)
# clear
a1.zero_()
a2.zero_()
a3.zero_()
a4.zero_()
# fill with mat instance
a1.fill_(fill_mat)
a2.fill_(fill_mat)
a3.fill_(fill_mat)
a4.fill_(fill_mat)
assert_np_equal(a1.numpy(), expected1)
assert_np_equal(a2.numpy(), expected2)
assert_np_equal(a3.numpy(), expected3)
assert_np_equal(a4.numpy(), expected4)
@wp.struct
class FillStruct:
# scalar members (make sure to test float16)
i1: wp.int8
i2: wp.int16
i4: wp.int32
i8: wp.int64
f2: wp.float16
f4: wp.float32
f8: wp.float16
# vector members (make sure to test vectors of float16)
v2: wp.types.vector(2, wp.int64)
v3: wp.types.vector(3, wp.float32)
v4: wp.types.vector(4, wp.float16)
v5: wp.types.vector(5, wp.uint8)
# matrix members (make sure to test matrices of float16)
m2: wp.types.matrix((2, 2), wp.float64)
m3: wp.types.matrix((3, 3), wp.int32)
m4: wp.types.matrix((4, 4), wp.float16)
m5: wp.types.matrix((5, 5), wp.int8)
# arrays
a1: wp.array(dtype=float)
a2: wp.array2d(dtype=float)
a3: wp.array3d(dtype=float)
a4: wp.array4d(dtype=float)
def test_fill_struct(test, device):
dim_x = 4
nptype = FillStruct.numpy_dtype()
a1 = wp.zeros(dim_x, dtype=FillStruct, device=device)
a2 = wp.zeros((dim_x, dim_x), dtype=FillStruct, device=device)
a3 = wp.zeros((dim_x, dim_x, dim_x), dtype=FillStruct, device=device)
a4 = wp.zeros((dim_x, dim_x, dim_x, dim_x), dtype=FillStruct, device=device)
assert_np_equal(a1.numpy(), np.zeros(a1.shape, dtype=nptype))
assert_np_equal(a2.numpy(), np.zeros(a2.shape, dtype=nptype))
assert_np_equal(a3.numpy(), np.zeros(a3.shape, dtype=nptype))
assert_np_equal(a4.numpy(), np.zeros(a4.shape, dtype=nptype))
s = FillStruct()
# fill with default struct value (should be all zeros)
a1.fill_(s)
a2.fill_(s)
a3.fill_(s)
a4.fill_(s)
assert_np_equal(a1.numpy(), np.zeros(a1.shape, dtype=nptype))
assert_np_equal(a2.numpy(), np.zeros(a2.shape, dtype=nptype))
assert_np_equal(a3.numpy(), np.zeros(a3.shape, dtype=nptype))
assert_np_equal(a4.numpy(), np.zeros(a4.shape, dtype=nptype))
# scalars
s.i1 = -17
s.i2 = 42
s.i4 = 99
s.i8 = 101
s.f2 = -1.25
s.f4 = 13.37
s.f8 = 0.125
# vectors
s.v2 = [21, 22]
s.v3 = [31, 32, 33]
s.v4 = [41, 42, 43, 44]
s.v5 = [51, 52, 53, 54, 55]
# matrices
s.m2 = [[61, 62]] * 2
s.m3 = [[71, 72, 73]] * 3
s.m4 = [[81, 82, 83, 84]] * 4
s.m5 = [[91, 92, 93, 94, 95]] * 5
# arrays
s.a1 = wp.zeros((2,) * 1, dtype=float, device=device)
s.a2 = wp.zeros((2,) * 2, dtype=float, device=device)
s.a3 = wp.zeros((2,) * 3, dtype=float, device=device)
s.a4 = wp.zeros((2,) * 4, dtype=float, device=device)
# fill with custom struct value
a1.fill_(s)
a2.fill_(s)
a3.fill_(s)
a4.fill_(s)
ns = s.numpy_value()
expected1 = np.empty(a1.shape, dtype=nptype)
expected2 = np.empty(a2.shape, dtype=nptype)
expected3 = np.empty(a3.shape, dtype=nptype)
expected4 = np.empty(a4.shape, dtype=nptype)
expected1.fill(ns)
expected2.fill(ns)
expected3.fill(ns)
expected4.fill(ns)
assert_np_equal(a1.numpy(), expected1)
assert_np_equal(a2.numpy(), expected2)
assert_np_equal(a3.numpy(), expected3)
assert_np_equal(a4.numpy(), expected4)
# test clearing
a1.zero_()
a2.zero_()
a3.zero_()
a4.zero_()
assert_np_equal(a1.numpy(), np.zeros(a1.shape, dtype=nptype))
assert_np_equal(a2.numpy(), np.zeros(a2.shape, dtype=nptype))
assert_np_equal(a3.numpy(), np.zeros(a3.shape, dtype=nptype))
assert_np_equal(a4.numpy(), np.zeros(a4.shape, dtype=nptype))
def test_fill_slices(test, device):
# test fill_ and zero_ for non-contiguous arrays
# Note: we don't need to test the whole range of dtypes (vectors, matrices, structs) here
dim_x = 8
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
a1 = wp.zeros(dim_x, dtype=wptype, device=device)
a2 = wp.zeros((dim_x, dim_x), dtype=wptype, device=device)
a3 = wp.zeros((dim_x, dim_x, dim_x), dtype=wptype, device=device)
a4 = wp.zeros((dim_x, dim_x, dim_x, dim_x), dtype=wptype, device=device)
assert_np_equal(a1.numpy(), np.zeros(a1.shape, dtype=nptype))
assert_np_equal(a2.numpy(), np.zeros(a2.shape, dtype=nptype))
assert_np_equal(a3.numpy(), np.zeros(a3.shape, dtype=nptype))
assert_np_equal(a4.numpy(), np.zeros(a4.shape, dtype=nptype))
# partititon each array into even and odd slices
a1a = a1[::2]
a1b = a1[1::2]
a2a = a2[::2]
a2b = a2[1::2]
a3a = a3[::2]
a3b = a3[1::2]
a4a = a4[::2]
a4b = a4[1::2]
# fill even slices
fill_a = 17
a1a.fill_(fill_a)
a2a.fill_(fill_a)
a3a.fill_(fill_a)
a4a.fill_(fill_a)
# ensure filled slices are correct
assert_np_equal(a1a.numpy(), np.full(a1a.shape, fill_a, dtype=nptype))
assert_np_equal(a2a.numpy(), np.full(a2a.shape, fill_a, dtype=nptype))
assert_np_equal(a3a.numpy(), np.full(a3a.shape, fill_a, dtype=nptype))
assert_np_equal(a4a.numpy(), np.full(a4a.shape, fill_a, dtype=nptype))
# ensure unfilled slices are unaffected
assert_np_equal(a1b.numpy(), np.zeros(a1b.shape, dtype=nptype))
assert_np_equal(a2b.numpy(), np.zeros(a2b.shape, dtype=nptype))
assert_np_equal(a3b.numpy(), np.zeros(a3b.shape, dtype=nptype))
assert_np_equal(a4b.numpy(), np.zeros(a4b.shape, dtype=nptype))
# fill odd slices
fill_b = 42
a1b.fill_(fill_b)
a2b.fill_(fill_b)
a3b.fill_(fill_b)
a4b.fill_(fill_b)
# ensure filled slices are correct
assert_np_equal(a1b.numpy(), np.full(a1b.shape, fill_b, dtype=nptype))
assert_np_equal(a2b.numpy(), np.full(a2b.shape, fill_b, dtype=nptype))
assert_np_equal(a3b.numpy(), np.full(a3b.shape, fill_b, dtype=nptype))
assert_np_equal(a4b.numpy(), np.full(a4b.shape, fill_b, dtype=nptype))
# ensure unfilled slices are unaffected
assert_np_equal(a1a.numpy(), np.full(a1a.shape, fill_a, dtype=nptype))
assert_np_equal(a2a.numpy(), np.full(a2a.shape, fill_a, dtype=nptype))
assert_np_equal(a3a.numpy(), np.full(a3a.shape, fill_a, dtype=nptype))
assert_np_equal(a4a.numpy(), np.full(a4a.shape, fill_a, dtype=nptype))
# clear even slices
a1a.zero_()
a2a.zero_()
a3a.zero_()
a4a.zero_()
# ensure cleared slices are correct
assert_np_equal(a1a.numpy(), np.zeros(a1a.shape, dtype=nptype))
assert_np_equal(a2a.numpy(), np.zeros(a2a.shape, dtype=nptype))
assert_np_equal(a3a.numpy(), np.zeros(a3a.shape, dtype=nptype))
assert_np_equal(a4a.numpy(), np.zeros(a4a.shape, dtype=nptype))
# ensure uncleared slices are unaffected
assert_np_equal(a1b.numpy(), np.full(a1b.shape, fill_b, dtype=nptype))
assert_np_equal(a2b.numpy(), np.full(a2b.shape, fill_b, dtype=nptype))
assert_np_equal(a3b.numpy(), np.full(a3b.shape, fill_b, dtype=nptype))
assert_np_equal(a4b.numpy(), np.full(a4b.shape, fill_b, dtype=nptype))
# re-fill even slices
a1a.fill_(fill_a)
a2a.fill_(fill_a)
a3a.fill_(fill_a)
a4a.fill_(fill_a)
# clear odd slices
a1b.zero_()
a2b.zero_()
a3b.zero_()
a4b.zero_()
# ensure cleared slices are correct
assert_np_equal(a1b.numpy(), np.zeros(a1b.shape, dtype=nptype))
assert_np_equal(a2b.numpy(), np.zeros(a2b.shape, dtype=nptype))
assert_np_equal(a3b.numpy(), np.zeros(a3b.shape, dtype=nptype))
assert_np_equal(a4b.numpy(), np.zeros(a4b.shape, dtype=nptype))
# ensure uncleared slices are unaffected
assert_np_equal(a1a.numpy(), np.full(a1a.shape, fill_a, dtype=nptype))
assert_np_equal(a2a.numpy(), np.full(a2a.shape, fill_a, dtype=nptype))
assert_np_equal(a3a.numpy(), np.full(a3a.shape, fill_a, dtype=nptype))
assert_np_equal(a4a.numpy(), np.full(a4a.shape, fill_a, dtype=nptype))
def test_full_scalar(test, device):
dim = 4
for ndim in range(1, 5):
shape = (dim,) * ndim
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
# fill with int value and specific dtype
fill_value = 42
a = wp.full(shape, fill_value, dtype=wptype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, wptype)
test.assertEqual(na.shape, shape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, np.full(shape, fill_value, dtype=nptype))
if wptype in wp.types.float_types:
# fill with float value and specific dtype
fill_value = 13.37
a = wp.full(shape, fill_value, dtype=wptype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, wptype)
test.assertEqual(na.shape, shape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, np.full(shape, fill_value, dtype=nptype))
# fill with int value and automatically inferred dtype
fill_value = 42
a = wp.full(shape, fill_value, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, wp.int32)
test.assertEqual(na.shape, shape)
test.assertEqual(na.dtype, np.int32)
assert_np_equal(na, np.full(shape, fill_value, dtype=np.int32))
# fill with float value and automatically inferred dtype
fill_value = 13.37
a = wp.full(shape, fill_value, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, wp.float32)
test.assertEqual(na.shape, shape)
test.assertEqual(na.dtype, np.float32)
assert_np_equal(na, np.full(shape, fill_value, dtype=np.float32))
def test_full_vector(test, device):
dim = 4
for ndim in range(1, 5):
shape = (dim,) * ndim
# full from scalar
for veclen in [2, 3, 4, 5]:
npshape = (*shape, veclen)
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
vectype = wp.types.vector(veclen, wptype)
# fill with scalar int value and specific dtype
fill_value = 42
a = wp.full(shape, fill_value, dtype=vectype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, vectype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, np.full(a.size * veclen, fill_value, dtype=nptype).reshape(npshape))
if wptype in wp.types.float_types:
# fill with scalar float value and specific dtype
fill_value = 13.37
a = wp.full(shape, fill_value, dtype=vectype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, vectype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, np.full(a.size * veclen, fill_value, dtype=nptype).reshape(npshape))
# fill with vector value and specific dtype
fill_vec = vectype(42)
a = wp.full(shape, fill_vec, dtype=vectype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, vectype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, np.full(a.size * veclen, 42, dtype=nptype).reshape(npshape))
# fill with vector value and automatically inferred dtype
a = wp.full(shape, fill_vec, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, vectype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, np.full(a.size * veclen, 42, dtype=nptype).reshape(npshape))
fill_lists = [
[17, 42],
[17, 42, 99],
[17, 42, 99, 101],
[17, 42, 99, 101, 127],
]
# full from list and numpy array
for fill_list in fill_lists:
veclen = len(fill_list)
npshape = (*shape, veclen)
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
vectype = wp.types.vector(veclen, wptype)
# fill with list and specific dtype
a = wp.full(shape, fill_list, dtype=vectype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, vectype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
expected = np.tile(np.array(fill_list, dtype=nptype), a.size).reshape(npshape)
assert_np_equal(na, expected)
fill_arr = np.array(fill_list, dtype=nptype)
# fill with numpy array and specific dtype
a = wp.full(shape, fill_arr, dtype=vectype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, vectype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, expected)
# fill with numpy array and automatically infer dtype
a = wp.full(shape, fill_arr, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertTrue(wp.types.types_equal(a.dtype, vectype))
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, expected)
# fill with list and automatically infer dtype
a = wp.full(shape, fill_list, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
# check that the inferred dtype is a vector
# Note that we cannot guarantee the scalar type, because it depends on numpy and may vary by platform
# (e.g. int64 on Linux and int32 on Windows).
test.assertEqual(a.dtype._wp_generic_type_str_, "vec_t")
test.assertEqual(a.dtype._length_, veclen)
expected = np.tile(np.array(fill_list), a.size).reshape(npshape)
assert_np_equal(na, expected)
def test_full_matrix(test, device):
dim = 4
for ndim in range(1, 5):
shape = (dim,) * ndim
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
matrix_types = [
# square matrices
wp.types.matrix((2, 2), wptype),
wp.types.matrix((3, 3), wptype),
wp.types.matrix((4, 4), wptype),
wp.types.matrix((5, 5), wptype),
# non-square matrices
wp.types.matrix((2, 3), wptype),
wp.types.matrix((3, 2), wptype),
wp.types.matrix((3, 4), wptype),
wp.types.matrix((4, 3), wptype),
]
for mattype in matrix_types:
npshape = (*shape, *mattype._shape_)
# fill with scalar int value and specific dtype
fill_value = 42
a = wp.full(shape, fill_value, dtype=mattype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, mattype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, np.full(a.size * mattype._length_, fill_value, dtype=nptype).reshape(npshape))
if wptype in wp.types.float_types:
# fill with scalar float value and specific dtype
fill_value = 13.37
a = wp.full(shape, fill_value, dtype=mattype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, mattype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, np.full(a.size * mattype._length_, fill_value, dtype=nptype).reshape(npshape))
# fill with matrix value and specific dtype
fill_mat = mattype(42)
a = wp.full(shape, fill_mat, dtype=mattype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, mattype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, np.full(a.size * mattype._length_, 42, dtype=nptype).reshape(npshape))
# fill with matrix value and automatically inferred dtype
fill_mat = mattype(42)
a = wp.full(shape, fill_mat, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, mattype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, np.full(a.size * mattype._length_, 42, dtype=nptype).reshape(npshape))
# fill with 1d numpy array and specific dtype
if wptype != wp.bool:
fill_arr1d = np.arange(mattype._length_, dtype=nptype)
else:
fill_arr1d = np.ones(mattype._length_, dtype=nptype)
a = wp.full(shape, fill_arr1d, dtype=mattype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, mattype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
expected = np.tile(fill_arr1d, a.size).reshape(npshape)
assert_np_equal(na, expected)
# fill with 2d numpy array and specific dtype
fill_arr2d = fill_arr1d.reshape(mattype._shape_)
a = wp.full(shape, fill_arr2d, dtype=mattype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, mattype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, expected)
# fill with 2d numpy array and automatically infer dtype
a = wp.full(shape, fill_arr2d, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertTrue(wp.types.types_equal(a.dtype, mattype))
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, expected)
# fill with flat list and specific dtype
fill_list1d = list(fill_arr1d)
a = wp.full(shape, fill_list1d, dtype=mattype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, mattype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, expected)
# fill with nested list and specific dtype
fill_list2d = [list(row) for row in fill_arr2d]
a = wp.full(shape, fill_list2d, dtype=mattype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, mattype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, expected)
mat_lists = [
# square matrices
[[1, 2], [3, 4]],
[[1, 2, 3], [4, 5, 6], [7, 8, 9]],
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]],
# non-square matrices
[[1, 2, 3, 4], [5, 6, 7, 8]],
[[1, 2], [3, 4], [5, 6], [7, 8]],
]
# fill with nested lists and automatically infer dtype
for fill_list in mat_lists:
num_rows = len(fill_list)
num_cols = len(fill_list[0])
npshape = (*shape, num_rows, num_cols)
a = wp.full(shape, fill_list, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
# check that the inferred dtype is a correctly shaped matrix
# Note that we cannot guarantee the scalar type, because it depends on numpy and may vary by platform
# (e.g. int64 on Linux and int32 on Windows).
test.assertEqual(a.dtype._wp_generic_type_str_, "mat_t")
test.assertEqual(a.dtype._shape_, (num_rows, num_cols))
expected = np.tile(np.array(fill_list).flatten(), a.size).reshape(npshape)
assert_np_equal(na, expected)
def test_full_struct(test, device):
dim = 4
for ndim in range(1, 5):
shape = (dim,) * ndim
s = FillStruct()
# fill with default struct (should be zeros)
a = wp.full(shape, s, dtype=FillStruct, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, FillStruct)
test.assertEqual(na.shape, shape)
test.assertEqual(na.dtype, FillStruct.numpy_dtype())
assert_np_equal(na, np.zeros(a.size, dtype=FillStruct.numpy_dtype()))
# scalars
s.i1 = -17
s.i2 = 42
s.i4 = 99
s.i8 = 101
s.f2 = -1.25
s.f4 = 13.37
s.f8 = 0.125
# vectors
s.v2 = [21, 22]
s.v3 = [31, 32, 33]
s.v4 = [41, 42, 43, 44]
s.v5 = [51, 52, 53, 54, 55]
# matrices
s.m2 = [[61, 62]] * 2
s.m3 = [[71, 72, 73]] * 3
s.m4 = [[81, 82, 83, 84]] * 4
s.m5 = [[91, 92, 93, 94, 95]] * 5
# arrays
s.a1 = wp.zeros((2,) * 1, dtype=float, device=device)
s.a2 = wp.zeros((2,) * 2, dtype=float, device=device)
s.a3 = wp.zeros((2,) * 3, dtype=float, device=device)
s.a4 = wp.zeros((2,) * 4, dtype=float, device=device)
# fill with initialized struct and explicit dtype
a = wp.full(shape, s, dtype=FillStruct, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, FillStruct)
test.assertEqual(na.shape, shape)
test.assertEqual(na.dtype, FillStruct.numpy_dtype())
expected = np.empty(shape, dtype=FillStruct.numpy_dtype())
expected.fill(s.numpy_value())
assert_np_equal(na, expected)
# fill with initialized struct and automatically inferred dtype
a = wp.full(shape, s, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, FillStruct)
test.assertEqual(na.shape, shape)
test.assertEqual(na.dtype, FillStruct.numpy_dtype())
assert_np_equal(na, expected)
def test_round_trip(test, device):
dim_x = 4
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
a_np = np.random.randn(dim_x).astype(nptype)
a = wp.array(a_np, device=device)
test.assertEqual(a.dtype, wptype)
assert_np_equal(a.numpy(), a_np)
v_np = np.random.randn(dim_x, 3).astype(nptype)
v = wp.array(v_np, dtype=wp.types.vector(3, wptype), device=device)
assert_np_equal(v.numpy(), v_np)
def test_empty_array(test, device):
# Test whether common operations work with empty (zero-sized) arrays
# without throwing exceptions.
def test_empty_ops(ndim, nrows, ncols, wptype, nptype):
shape = (0,) * ndim
dtype_shape = ()
if wptype in wp.types.scalar_types:
# scalar, vector, or matrix
if ncols > 0:
if nrows > 0:
wptype = wp.types.matrix((nrows, ncols), wptype)
else:
wptype = wp.types.vector(ncols, wptype)
dtype_shape = wptype._shape_
fill_value = wptype(42)
else:
# struct
fill_value = wptype()
# create a zero-sized array
a = wp.empty(shape, dtype=wptype, device=device, requires_grad=True)
test.assertEqual(a.ptr, None)
test.assertEqual(a.size, 0)
test.assertEqual(a.shape, shape)
test.assertEqual(a.grad.ptr, None)
test.assertEqual(a.grad.size, 0)
test.assertEqual(a.grad.shape, shape)
# all of these methods should succeed with zero-sized arrays
a.zero_()
a.fill_(fill_value)
b = a.flatten()
b = a.reshape((0,))
b = a.transpose()
b = a.contiguous()
b = wp.empty_like(a)
b = wp.zeros_like(a)
b = wp.full_like(a, fill_value)
b = wp.clone(a)
wp.copy(a, b)
a.assign(b)
na = a.numpy()
test.assertEqual(na.size, 0)
test.assertEqual(na.shape, (*shape, *dtype_shape))
test.assertEqual(na.dtype, nptype)
test.assertEqual(a.list(), [])
for ndim in range(1, 5):
# test with scalars, vectors, and matrices
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
# scalars
test_empty_ops(ndim, 0, 0, wptype, nptype)
for ncols in [2, 3, 4, 5]:
# vectors
test_empty_ops(ndim, 0, ncols, wptype, nptype)
# square matrices
test_empty_ops(ndim, ncols, ncols, wptype, nptype)
# non-square matrices
test_empty_ops(ndim, 2, 3, wptype, nptype)
test_empty_ops(ndim, 3, 2, wptype, nptype)
test_empty_ops(ndim, 3, 4, wptype, nptype)
test_empty_ops(ndim, 4, 3, wptype, nptype)
# test with structs
test_empty_ops(ndim, 0, 0, FillStruct, FillStruct.numpy_dtype())
def test_empty_from_numpy(test, device):
# Test whether wrapping an empty (zero-sized) numpy array works correctly
def test_empty_from_data(ndim, nrows, ncols, wptype, nptype):
shape = (0,) * ndim
dtype_shape = ()
if ncols > 0:
if nrows > 0:
wptype = wp.types.matrix((nrows, ncols), wptype)
else:
wptype = wp.types.vector(ncols, wptype)
dtype_shape = wptype._shape_
npshape = (*shape, *dtype_shape)
na = np.empty(npshape, dtype=nptype)
a = wp.array(na, dtype=wptype, device=device)
test.assertEqual(a.size, 0)
test.assertEqual(a.shape, shape)
for ndim in range(1, 5):
# test with scalars, vectors, and matrices
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
# scalars
test_empty_from_data(ndim, 0, 0, wptype, nptype)
for ncols in [2, 3, 4, 5]:
# vectors
test_empty_from_data(ndim, 0, ncols, wptype, nptype)
# square matrices
test_empty_from_data(ndim, ncols, ncols, wptype, nptype)
# non-square matrices
test_empty_from_data(ndim, 2, 3, wptype, nptype)
test_empty_from_data(ndim, 3, 2, wptype, nptype)
test_empty_from_data(ndim, 3, 4, wptype, nptype)
test_empty_from_data(ndim, 4, 3, wptype, nptype)
def test_empty_from_list(test, device):
# Test whether creating an array from an empty Python list works correctly
def test_empty_from_data(nrows, ncols, wptype):
if ncols > 0:
if nrows > 0:
wptype = wp.types.matrix((nrows, ncols), wptype)
else:
wptype = wp.types.vector(ncols, wptype)
a = wp.array([], dtype=wptype, device=device)
test.assertEqual(a.size, 0)
test.assertEqual(a.shape, (0,))
# test with scalars, vectors, and matrices
for wptype in wp.types.scalar_types:
# scalars
test_empty_from_data(0, 0, wptype)
for ncols in [2, 3, 4, 5]:
# vectors
test_empty_from_data(0, ncols, wptype)
# square matrices
test_empty_from_data(ncols, ncols, wptype)
# non-square matrices
test_empty_from_data(2, 3, wptype)
test_empty_from_data(3, 2, wptype)
test_empty_from_data(3, 4, wptype)
test_empty_from_data(4, 3, wptype)
def test_to_list_scalar(test, device):
dim = 3
fill_value = 42
for ndim in range(1, 5):
shape = (dim,) * ndim
for wptype in wp.types.scalar_types:
a = wp.full(shape, fill_value, dtype=wptype, device=device)
l = a.list()
test.assertEqual(len(l), a.size)
test.assertTrue(all(x == fill_value for x in l))
def test_to_list_vector(test, device):
dim = 3
for ndim in range(1, 5):
shape = (dim,) * ndim
for veclen in [2, 3, 4, 5]:
for wptype in wp.types.scalar_types:
vectype = wp.types.vector(veclen, wptype)
fill_value = vectype(42)
a = wp.full(shape, fill_value, dtype=vectype, device=device)
l = a.list()
test.assertEqual(len(l), a.size)
test.assertTrue(all(x == fill_value for x in l))
def test_to_list_matrix(test, device):
dim = 3
for ndim in range(1, 5):
shape = (dim,) * ndim
for wptype in wp.types.scalar_types:
matrix_types = [
# square matrices
wp.types.matrix((2, 2), wptype),
wp.types.matrix((3, 3), wptype),
wp.types.matrix((4, 4), wptype),
wp.types.matrix((5, 5), wptype),
# non-square matrices
wp.types.matrix((2, 3), wptype),
wp.types.matrix((3, 2), wptype),
wp.types.matrix((3, 4), wptype),
wp.types.matrix((4, 3), wptype),
]
for mattype in matrix_types:
fill_value = mattype(42)
a = wp.full(shape, fill_value, dtype=mattype, device=device)
l = a.list()
test.assertEqual(len(l), a.size)
test.assertTrue(all(x == fill_value for x in l))
def test_to_list_struct(test, device):
@wp.struct
class Inner:
h: wp.float16
v: wp.vec3
@wp.struct
class ListStruct:
i: int
f: float
h: wp.float16
vi: wp.vec2i
vf: wp.vec3f
vh: wp.vec4h
mi: wp.types.matrix((2, 2), int)
mf: wp.types.matrix((3, 3), float)
mh: wp.types.matrix((4, 4), wp.float16)
inner: Inner
a1: wp.array(dtype=int)
a2: wp.array2d(dtype=float)
a3: wp.array3d(dtype=wp.float16)
bool: wp.bool
dim = 3
s = ListStruct()
s.i = 42
s.f = 2.5
s.h = -1.25
s.vi = wp.vec2i(1, 2)
s.vf = wp.vec3f(0.1, 0.2, 0.3)
s.vh = wp.vec4h(1.0, 2.0, 3.0, 4.0)
s.mi = [[1, 2], [3, 4]]
s.mf = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
s.mh = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
s.inner = Inner()
s.inner.h = 1.5
s.inner.v = [1, 2, 3]
s.a1 = wp.empty(1, dtype=int, device=device)
s.a2 = wp.empty((1, 1), dtype=float, device=device)
s.a3 = wp.empty((1, 1, 1), dtype=wp.float16, device=device)
s.bool = True
for ndim in range(1, 5):
shape = (dim,) * ndim
a = wp.full(shape, s, dtype=ListStruct, device=device)
l = a.list()
for i in range(a.size):
test.assertEqual(l[i].i, s.i)
test.assertEqual(l[i].f, s.f)
test.assertEqual(l[i].h, s.h)
test.assertEqual(l[i].vi, s.vi)
test.assertEqual(l[i].vf, s.vf)
test.assertEqual(l[i].vh, s.vh)
test.assertEqual(l[i].mi, s.mi)
test.assertEqual(l[i].mf, s.mf)
test.assertEqual(l[i].mh, s.mh)
test.assertEqual(l[i].bool, s.bool)
test.assertEqual(l[i].inner.h, s.inner.h)
test.assertEqual(l[i].inner.v, s.inner.v)
test.assertEqual(l[i].a1.dtype, s.a1.dtype)
test.assertEqual(l[i].a1.ndim, s.a1.ndim)
test.assertEqual(l[i].a2.dtype, s.a2.dtype)
test.assertEqual(l[i].a2.ndim, s.a2.ndim)
test.assertEqual(l[i].a3.dtype, s.a3.dtype)
test.assertEqual(l[i].a3.ndim, s.a3.ndim)
def test_large_arrays_slow(test, device):
# The goal of this test is to use arrays just large enough to know
# if there's a flaw in handling arrays with more than 2**31-1 elements
# Unfortunately, it takes a long time to run so it won't be run automatically
# without changes to support how frequently a test may be run
total_elements = 2**31 + 8
# 1-D to 4-D arrays: test zero_, fill_, then zero_ for scalar data types:
for total_dims in range(1, 5):
dim_x = math.ceil(total_elements ** (1 / total_dims))
shape_tuple = tuple([dim_x] * total_dims)
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
a1 = wp.zeros(shape_tuple, dtype=wptype, device=device)
assert_np_equal(a1.numpy(), np.zeros_like(a1.numpy()))
a1.fill_(127)
assert_np_equal(a1.numpy(), 127 * np.ones_like(a1.numpy()))
a1.zero_()
assert_np_equal(a1.numpy(), np.zeros_like(a1.numpy()))
def test_large_arrays_fast(test, device):
# A truncated version of test_large_arrays_slow meant to catch basic errors
total_elements = 2**31 + 8
nptype = np.dtype(np.int8)
wptype = wp.types.np_dtype_to_warp_type[nptype]
a1 = wp.zeros((total_elements,), dtype=wptype, device=device)
assert_np_equal(a1.numpy(), np.zeros_like(a1.numpy()))
a1.fill_(127)
assert_np_equal(a1.numpy(), 127 * np.ones_like(a1.numpy()))
a1.zero_()
assert_np_equal(a1.numpy(), np.zeros_like(a1.numpy()))
@wp.kernel
def kernel_array_to_bool(array_null: wp.array(dtype=float), array_valid: wp.array(dtype=float)):
if not array_null:
# always succeed
wp.expect_eq(0, 0)
else:
# force failure
wp.expect_eq(1, 2)
if array_valid:
# always succeed
wp.expect_eq(0, 0)
else:
# force failure
wp.expect_eq(1, 2)
def test_array_to_bool(test, device):
arr = wp.zeros(8, dtype=float, device=device)
wp.launch(kernel_array_to_bool, dim=1, inputs=[None, arr], device=device)
@wp.struct
class InputStruct:
param1: int
param2: float
param3: wp.vec3
param4: wp.array(dtype=float)
@wp.struct
class OutputStruct:
param1: int
param2: float
param3: wp.vec3
@wp.kernel
def struct_array_kernel(inputs: wp.array(dtype=InputStruct), outputs: wp.array(dtype=OutputStruct)):
tid = wp.tid()
wp.expect_eq(inputs[tid].param1, tid)
wp.expect_eq(inputs[tid].param2, float(tid * tid))
wp.expect_eq(inputs[tid].param3[0], 1.0)
wp.expect_eq(inputs[tid].param3[1], 2.0)
wp.expect_eq(inputs[tid].param3[2], 3.0)
wp.expect_eq(inputs[tid].param4[0], 1.0)
wp.expect_eq(inputs[tid].param4[1], 2.0)
wp.expect_eq(inputs[tid].param4[2], 3.0)
o = OutputStruct()
o.param1 = inputs[tid].param1
o.param2 = inputs[tid].param2
o.param3 = inputs[tid].param3
outputs[tid] = o
def test_array_of_structs(test, device):
num_items = 10
l = []
for i in range(num_items):
s = InputStruct()
s.param1 = i
s.param2 = float(i * i)
s.param3 = wp.vec3(1.0, 2.0, 3.0)
s.param4 = wp.array([1.0, 2.0, 3.0], dtype=float, device=device)
l.append(s)
# initialize array from list of structs
inputs = wp.array(l, dtype=InputStruct, device=device)
outputs = wp.zeros(num_items, dtype=OutputStruct, device=device)
# pass to our compute kernel
wp.launch(struct_array_kernel, dim=num_items, inputs=[inputs, outputs], device=device)
out_numpy = outputs.numpy()
out_list = outputs.list()
out_cptr = outputs.to("cpu").cptr()
for i in range(num_items):
test.assertEqual(out_numpy[i][0], l[i].param1)
test.assertEqual(out_numpy[i][1], l[i].param2)
assert_np_equal(out_numpy[i][2], np.array(l[i].param3))
# test named slices of numpy structured array
test.assertEqual(out_numpy["param1"][i], l[i].param1)
test.assertEqual(out_numpy["param2"][i], l[i].param2)
assert_np_equal(out_numpy["param3"][i], np.array(l[i].param3))
test.assertEqual(out_list[i].param1, l[i].param1)
test.assertEqual(out_list[i].param2, l[i].param2)
test.assertEqual(out_list[i].param3, l[i].param3)
test.assertEqual(out_cptr[i].param1, l[i].param1)
test.assertEqual(out_cptr[i].param2, l[i].param2)
test.assertEqual(out_cptr[i].param3, l[i].param3)
@wp.struct
class GradStruct:
param1: int
param2: float
param3: wp.vec3
@wp.kernel
def test_array_of_structs_grad_kernel(inputs: wp.array(dtype=GradStruct), loss: wp.array(dtype=float)):
tid = wp.tid()
wp.atomic_add(loss, 0, inputs[tid].param2 * 2.0)
def test_array_of_structs_grad(test, device):
num_items = 10
l = []
for i in range(num_items):
g = GradStruct()
g.param2 = float(i)
l.append(g)
a = wp.array(l, dtype=GradStruct, device=device, requires_grad=True)
loss = wp.zeros(1, dtype=float, device=device, requires_grad=True)
with wp.Tape() as tape:
wp.launch(test_array_of_structs_grad_kernel, dim=num_items, inputs=[a, loss], device=device)
tape.backward(loss)
grads = a.grad.numpy()
assert_np_equal(grads["param2"], np.full(num_items, 2.0, dtype=np.float32))
@wp.struct
class NumpyStruct:
x: int
v: wp.vec3
def test_array_of_structs_from_numpy(test, device):
num_items = 10
na = np.zeros(num_items, dtype=NumpyStruct.numpy_dtype())
na["x"] = 17
na["v"] = (1, 2, 3)
a = wp.array(data=na, dtype=NumpyStruct, device=device)
assert_np_equal(a.numpy(), na)
def test_array_of_structs_roundtrip(test, device):
num_items = 10
value = NumpyStruct()
value.x = 17
value.v = wp.vec3(1.0, 2.0, 3.0)
# create Warp structured array
a = wp.full(num_items, value, device=device)
# convert to NumPy structured array
na = a.numpy()
expected = np.zeros(num_items, dtype=NumpyStruct.numpy_dtype())
expected["x"] = value.x
expected["v"] = value.v
assert_np_equal(na, expected)
# modify a field
na["x"] = 42
# convert back to Warp array
a = wp.from_numpy(na, NumpyStruct, device=device)
expected["x"] = 42
assert_np_equal(a.numpy(), expected)
def test_array_from_numpy(test, device):
arr = np.array((1.0, 2.0, 3.0), dtype=float)
result = wp.from_numpy(arr)
expected = wp.array((1.0, 2.0, 3.0), dtype=wp.float32, shape=(3,))
assert_np_equal(result.numpy(), expected.numpy())
result = wp.from_numpy(arr, dtype=wp.vec3)
expected = wp.array(((1.0, 2.0, 3.0),), dtype=wp.vec3, shape=(1,))
assert_np_equal(result.numpy(), expected.numpy())
# --------------------------------------------------------------------------
arr = np.array(((1.0, 2.0, 3.0), (4.0, 5.0, 6.0)), dtype=float)
result = wp.from_numpy(arr)
expected = wp.array(((1.0, 2.0, 3.0), (4.0, 5.0, 6.0)), dtype=wp.vec3, shape=(2,))
assert_np_equal(result.numpy(), expected.numpy())
result = wp.from_numpy(arr, dtype=wp.float32)
expected = wp.array(((1.0, 2.0, 3.0), (4.0, 5.0, 6.0)), dtype=wp.float32, shape=(2, 3))
assert_np_equal(result.numpy(), expected.numpy())
result = wp.from_numpy(arr, dtype=wp.float32, shape=(6,))
expected = wp.array((1.0, 2.0, 3.0, 4.0, 5.0, 6.0), dtype=wp.float32, shape=(6,))
assert_np_equal(result.numpy(), expected.numpy())
# --------------------------------------------------------------------------
arr = np.array(
(
(
(1.0, 2.0, 3.0, 4.0),
(2.0, 3.0, 4.0, 5.0),
(3.0, 4.0, 5.0, 6.0),
(4.0, 5.0, 6.0, 7.0),
),
(
(2.0, 3.0, 4.0, 5.0),
(3.0, 4.0, 5.0, 6.0),
(4.0, 5.0, 6.0, 7.0),
(5.0, 6.0, 7.0, 8.0),
),
),
dtype=float,
)
result = wp.from_numpy(arr)
expected = wp.array(
(
(
(1.0, 2.0, 3.0, 4.0),
(2.0, 3.0, 4.0, 5.0),
(3.0, 4.0, 5.0, 6.0),
(4.0, 5.0, 6.0, 7.0),
),
(
(2.0, 3.0, 4.0, 5.0),
(3.0, 4.0, 5.0, 6.0),
(4.0, 5.0, 6.0, 7.0),
(5.0, 6.0, 7.0, 8.0),
),
),
dtype=wp.mat44,
shape=(2,),
)
assert_np_equal(result.numpy(), expected.numpy())
result = wp.from_numpy(arr, dtype=wp.float32)
expected = wp.array(
(
(
(1.0, 2.0, 3.0, 4.0),
(2.0, 3.0, 4.0, 5.0),
(3.0, 4.0, 5.0, 6.0),
(4.0, 5.0, 6.0, 7.0),
),
(
(2.0, 3.0, 4.0, 5.0),
(3.0, 4.0, 5.0, 6.0),
(4.0, 5.0, 6.0, 7.0),
(5.0, 6.0, 7.0, 8.0),
),
),
dtype=wp.float32,
shape=(2, 4, 4),
)
assert_np_equal(result.numpy(), expected.numpy())
result = wp.from_numpy(arr, dtype=wp.vec4)
expected = wp.array(
(
(1.0, 2.0, 3.0, 4.0),
(2.0, 3.0, 4.0, 5.0),
(3.0, 4.0, 5.0, 6.0),
(4.0, 5.0, 6.0, 7.0),
(2.0, 3.0, 4.0, 5.0),
(3.0, 4.0, 5.0, 6.0),
(4.0, 5.0, 6.0, 7.0),
(5.0, 6.0, 7.0, 8.0),
),
dtype=wp.vec4,
shape=(8,),
)
assert_np_equal(result.numpy(), expected.numpy())
result = wp.from_numpy(arr, dtype=wp.float32, shape=(32,))
expected = wp.array(
(
1.0, 2.0, 3.0, 4.0,
2.0, 3.0, 4.0, 5.0,
3.0, 4.0, 5.0, 6.0,
4.0, 5.0, 6.0, 7.0,
2.0, 3.0, 4.0, 5.0,
3.0, 4.0, 5.0, 6.0,
4.0, 5.0, 6.0, 7.0,
5.0, 6.0, 7.0, 8.0,
),
dtype=wp.float32,
shape=(32,),
)
assert_np_equal(result.numpy(), expected.numpy())
def register(parent):
devices = get_test_devices()
class TestArray(parent):
pass
add_function_test(TestArray, "test_shape", test_shape, devices=devices)
add_function_test(TestArray, "test_flatten", test_flatten, devices=devices)
add_function_test(TestArray, "test_reshape", test_reshape, devices=devices)
add_function_test(TestArray, "test_slicing", test_slicing, devices=devices)
add_function_test(TestArray, "test_transpose", test_transpose, devices=devices)
add_function_test(TestArray, "test_view", test_view, devices=devices)
add_function_test(TestArray, "test_1d_array", test_1d, devices=devices)
add_function_test(TestArray, "test_2d_array", test_2d, devices=devices)
add_function_test(TestArray, "test_3d_array", test_3d, devices=devices)
add_function_test(TestArray, "test_4d_array", test_4d, devices=devices)
add_function_test(TestArray, "test_4d_array_transposed", test_4d_transposed, devices=devices)
add_function_test(TestArray, "test_fill_scalar", test_fill_scalar, devices=devices)
add_function_test(TestArray, "test_fill_vector", test_fill_vector, devices=devices)
add_function_test(TestArray, "test_fill_matrix", test_fill_matrix, devices=devices)
add_function_test(TestArray, "test_fill_struct", test_fill_struct, devices=devices)
add_function_test(TestArray, "test_fill_slices", test_fill_slices, devices=devices)
add_function_test(TestArray, "test_full_scalar", test_full_scalar, devices=devices)
add_function_test(TestArray, "test_full_vector", test_full_vector, devices=devices)
add_function_test(TestArray, "test_full_matrix", test_full_matrix, devices=devices)
add_function_test(TestArray, "test_full_struct", test_full_struct, devices=devices)
add_function_test(TestArray, "test_empty_array", test_empty_array, devices=devices)
add_function_test(TestArray, "test_empty_from_numpy", test_empty_from_numpy, devices=devices)
add_function_test(TestArray, "test_empty_from_list", test_empty_from_list, devices=devices)
add_function_test(TestArray, "test_to_list_scalar", test_to_list_scalar, devices=devices)
add_function_test(TestArray, "test_to_list_vector", test_to_list_vector, devices=devices)
add_function_test(TestArray, "test_to_list_matrix", test_to_list_matrix, devices=devices)
add_function_test(TestArray, "test_to_list_struct", test_to_list_struct, devices=devices)
add_function_test(TestArray, "test_lower_bound", test_lower_bound, devices=devices)
add_function_test(TestArray, "test_round_trip", test_round_trip, devices=devices)
add_function_test(TestArray, "test_large_arrays_fast", test_large_arrays_fast, devices=devices)
add_function_test(TestArray, "test_array_to_bool", test_array_to_bool, devices=devices)
add_function_test(TestArray, "test_array_of_structs", test_array_of_structs, devices=devices)
add_function_test(TestArray, "test_array_of_structs_grad", test_array_of_structs_grad, devices=devices)
add_function_test(TestArray, "test_array_of_structs_from_numpy", test_array_of_structs_from_numpy, devices=devices)
add_function_test(TestArray, "test_array_of_structs_roundtrip", test_array_of_structs_roundtrip, devices=devices)
add_function_test(TestArray, "test_array_from_numpy", test_array_from_numpy, devices=devices)
return TestArray
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_array.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import unittest
# include parent path
import numpy as np
import warp as wp
from warp.tests.test_base import *
wp.init()
@wp.kernel
def op_kernel(x: wp.array(dtype=float), y: wp.array(dtype=float)):
tid = wp.tid()
y[tid] = 0.5 - x[tid] * 2.0
@wp.kernel
def inc(a: wp.array(dtype=float)):
tid = wp.tid()
a[tid] = a[tid] + 1.0
@wp.kernel
def arange(start: int, step: int, a: wp.array(dtype=int)):
tid = wp.tid()
a[tid] = start + step * tid
# copy elements between non-contiguous 1d arrays of float
@wp.kernel
def copy1d_float_kernel(dst: wp.array(dtype=float), src: wp.array(dtype=float)):
i = wp.tid()
dst[i] = src[i]
# copy elements between non-contiguous 2d arrays of float
@wp.kernel
def copy2d_float_kernel(dst: wp.array2d(dtype=float), src: wp.array2d(dtype=float)):
i, j = wp.tid()
dst[i, j] = src[i, j]
# copy elements between non-contiguous 3d arrays of float
@wp.kernel
def copy3d_float_kernel(dst: wp.array3d(dtype=float), src: wp.array3d(dtype=float)):
i, j, k = wp.tid()
dst[i, j, k] = src[i, j, k]
# copy elements between non-contiguous 2d arrays of vec3
@wp.kernel
def copy2d_vec3_kernel(dst: wp.array2d(dtype=wp.vec3), src: wp.array2d(dtype=wp.vec3)):
i, j = wp.tid()
dst[i, j] = src[i, j]
# copy elements between non-contiguous 2d arrays of mat22
@wp.kernel
def copy2d_mat22_kernel(dst: wp.array2d(dtype=wp.mat22), src: wp.array2d(dtype=wp.mat22)):
i, j = wp.tid()
dst[i, j] = src[i, j]
def test_torch_zerocopy(test, device):
import torch
a = wp.zeros(10, dtype=wp.float32, device=device)
t = wp.to_torch(a)
assert a.ptr == t.data_ptr()
torch_device = wp.device_to_torch(device)
t = torch.zeros(10, dtype=torch.float32, device=torch_device)
a = wp.from_torch(t)
assert a.ptr == t.data_ptr()
def test_from_torch(test, device):
import torch
torch_device = wp.device_to_torch(device)
# automatically determine warp dtype
def wrap_scalar_tensor_implicit(torch_dtype, expected_warp_dtype):
t = torch.zeros(10, dtype=torch_dtype, device=torch_device)
a = wp.from_torch(t)
assert a.dtype == expected_warp_dtype
assert a.shape == tuple(t.shape)
wrap_scalar_tensor_implicit(torch.float64, wp.float64)
wrap_scalar_tensor_implicit(torch.float32, wp.float32)
wrap_scalar_tensor_implicit(torch.float16, wp.float16)
wrap_scalar_tensor_implicit(torch.int64, wp.int64)
wrap_scalar_tensor_implicit(torch.int32, wp.int32)
wrap_scalar_tensor_implicit(torch.int16, wp.int16)
wrap_scalar_tensor_implicit(torch.int8, wp.int8)
wrap_scalar_tensor_implicit(torch.uint8, wp.uint8)
wrap_scalar_tensor_implicit(torch.bool, wp.bool)
# explicitly specify warp dtype
def wrap_scalar_tensor_explicit(torch_dtype, expected_warp_dtype):
t = torch.zeros(10, dtype=torch_dtype, device=torch_device)
a = wp.from_torch(t, expected_warp_dtype)
assert a.dtype == expected_warp_dtype
assert a.shape == tuple(t.shape)
wrap_scalar_tensor_explicit(torch.float64, wp.float64)
wrap_scalar_tensor_explicit(torch.float32, wp.float32)
wrap_scalar_tensor_explicit(torch.float16, wp.float16)
wrap_scalar_tensor_explicit(torch.int64, wp.int64)
wrap_scalar_tensor_explicit(torch.int64, wp.uint64)
wrap_scalar_tensor_explicit(torch.int32, wp.int32)
wrap_scalar_tensor_explicit(torch.int32, wp.uint32)
wrap_scalar_tensor_explicit(torch.int16, wp.int16)
wrap_scalar_tensor_explicit(torch.int16, wp.uint16)
wrap_scalar_tensor_explicit(torch.int8, wp.int8)
wrap_scalar_tensor_explicit(torch.int8, wp.uint8)
wrap_scalar_tensor_explicit(torch.uint8, wp.uint8)
wrap_scalar_tensor_explicit(torch.uint8, wp.int8)
wrap_scalar_tensor_explicit(torch.bool, wp.uint8)
wrap_scalar_tensor_explicit(torch.bool, wp.int8)
wrap_scalar_tensor_explicit(torch.bool, wp.bool)
def wrap_vec_tensor(n, desired_warp_dtype):
t = torch.zeros((10, n), dtype=torch.float32, device=torch_device)
a = wp.from_torch(t, desired_warp_dtype)
assert a.dtype == desired_warp_dtype
assert a.shape == (10,)
wrap_vec_tensor(2, wp.vec2)
wrap_vec_tensor(3, wp.vec3)
wrap_vec_tensor(4, wp.vec4)
wrap_vec_tensor(6, wp.spatial_vector)
wrap_vec_tensor(7, wp.transform)
def wrap_mat_tensor(n, m, desired_warp_dtype):
t = torch.zeros((10, n, m), dtype=torch.float32, device=torch_device)
a = wp.from_torch(t, desired_warp_dtype)
assert a.dtype == desired_warp_dtype
assert a.shape == (10,)
wrap_mat_tensor(2, 2, wp.mat22)
wrap_mat_tensor(3, 3, wp.mat33)
wrap_mat_tensor(4, 4, wp.mat44)
wrap_mat_tensor(6, 6, wp.spatial_matrix)
def wrap_vec_tensor_with_grad(n, desired_warp_dtype):
t = torch.zeros((10, n), dtype=torch.float32, device=torch_device)
a = wp.from_torch(t, desired_warp_dtype, requires_grad=True)
assert a.dtype == desired_warp_dtype
assert a.shape == (10,)
wrap_vec_tensor_with_grad(2, wp.vec2)
wrap_vec_tensor_with_grad(3, wp.vec3)
wrap_vec_tensor_with_grad(4, wp.vec4)
wrap_vec_tensor_with_grad(6, wp.spatial_vector)
wrap_vec_tensor_with_grad(7, wp.transform)
def wrap_mat_tensor_with_grad(n, m, desired_warp_dtype):
t = torch.zeros((10, n, m), dtype=torch.float32, device=torch_device)
a = wp.from_torch(t, desired_warp_dtype, requires_grad=True)
assert a.dtype == desired_warp_dtype
assert a.shape == (10,)
wrap_mat_tensor_with_grad(2, 2, wp.mat22)
wrap_mat_tensor_with_grad(3, 3, wp.mat33)
wrap_mat_tensor_with_grad(4, 4, wp.mat44)
wrap_mat_tensor_with_grad(6, 6, wp.spatial_matrix)
def test_to_torch(test, device):
import torch
def wrap_scalar_array(warp_dtype, expected_torch_dtype):
a = wp.zeros(10, dtype=warp_dtype, device=device)
t = wp.to_torch(a)
assert t.dtype == expected_torch_dtype
assert tuple(t.shape) == a.shape
wrap_scalar_array(wp.float64, torch.float64)
wrap_scalar_array(wp.float32, torch.float32)
wrap_scalar_array(wp.float16, torch.float16)
wrap_scalar_array(wp.int64, torch.int64)
wrap_scalar_array(wp.int32, torch.int32)
wrap_scalar_array(wp.int16, torch.int16)
wrap_scalar_array(wp.int8, torch.int8)
wrap_scalar_array(wp.uint8, torch.uint8)
wrap_scalar_array(wp.bool, torch.bool)
# not supported by torch
# wrap_scalar_array(wp.uint64, torch.int64)
# wrap_scalar_array(wp.uint32, torch.int32)
# wrap_scalar_array(wp.uint16, torch.int16)
def wrap_vec_array(n, warp_dtype):
a = wp.zeros(10, dtype=warp_dtype, device=device)
t = wp.to_torch(a)
assert t.dtype == torch.float32
assert tuple(t.shape) == (10, n)
wrap_vec_array(2, wp.vec2)
wrap_vec_array(3, wp.vec3)
wrap_vec_array(4, wp.vec4)
wrap_vec_array(6, wp.spatial_vector)
wrap_vec_array(7, wp.transform)
def wrap_mat_array(n, m, warp_dtype):
a = wp.zeros(10, dtype=warp_dtype, device=device)
t = wp.to_torch(a)
assert t.dtype == torch.float32
assert tuple(t.shape) == (10, n, m)
wrap_mat_array(2, 2, wp.mat22)
wrap_mat_array(3, 3, wp.mat33)
wrap_mat_array(4, 4, wp.mat44)
wrap_mat_array(6, 6, wp.spatial_matrix)
def test_from_torch_slices(test, device):
import torch
torch_device = wp.device_to_torch(device)
# 1D slice, contiguous
t_base = torch.arange(10, dtype=torch.float32, device=torch_device)
t = t_base[2:9]
a = wp.from_torch(t)
assert a.ptr == t.data_ptr()
assert a.is_contiguous
assert a.shape == tuple(t.shape)
assert_np_equal(a.numpy(), t.cpu().numpy())
# 1D slice with non-contiguous stride
t_base = torch.arange(10, dtype=torch.float32, device=torch_device)
t = t_base[2:9:2]
a = wp.from_torch(t)
assert a.ptr == t.data_ptr()
assert not a.is_contiguous
assert a.shape == tuple(t.shape)
# copy contents to contiguous array
a_contiguous = wp.empty_like(a)
wp.launch(copy1d_float_kernel, dim=a.shape, inputs=[a_contiguous, a], device=device)
assert_np_equal(a_contiguous.numpy(), t.cpu().numpy())
# 2D slices (non-contiguous)
t_base = torch.arange(24, dtype=torch.float32, device=torch_device).reshape((4, 6))
t = t_base[1:3, 2:5]
a = wp.from_torch(t)
assert a.ptr == t.data_ptr()
assert not a.is_contiguous
assert a.shape == tuple(t.shape)
# copy contents to contiguous array
a_contiguous = wp.empty_like(a)
wp.launch(copy2d_float_kernel, dim=a.shape, inputs=[a_contiguous, a], device=device)
assert_np_equal(a_contiguous.numpy(), t.cpu().numpy())
# 3D slices (non-contiguous)
t_base = torch.arange(36, dtype=torch.float32, device=torch_device).reshape((4, 3, 3))
t = t_base[::2, 0:1, 1:2]
a = wp.from_torch(t)
assert a.ptr == t.data_ptr()
assert not a.is_contiguous
assert a.shape == tuple(t.shape)
# copy contents to contiguous array
a_contiguous = wp.empty_like(a)
wp.launch(copy3d_float_kernel, dim=a.shape, inputs=[a_contiguous, a], device=device)
assert_np_equal(a_contiguous.numpy(), t.cpu().numpy())
# 2D slices of vec3 (inner contiguous, outer non-contiguous)
t_base = torch.arange(150, dtype=torch.float32, device=torch_device).reshape((10, 5, 3))
t = t_base[1:7:2, 2:5]
a = wp.from_torch(t, dtype=wp.vec3)
assert a.ptr == t.data_ptr()
assert not a.is_contiguous
assert a.shape == tuple(t.shape[:-1])
# copy contents to contiguous array
a_contiguous = wp.empty_like(a)
wp.launch(copy2d_vec3_kernel, dim=a.shape, inputs=[a_contiguous, a], device=device)
assert_np_equal(a_contiguous.numpy(), t.cpu().numpy())
# 2D slices of mat22 (inner contiguous, outer non-contiguous)
t_base = torch.arange(200, dtype=torch.float32, device=torch_device).reshape((10, 5, 2, 2))
t = t_base[1:7:2, 2:5]
a = wp.from_torch(t, dtype=wp.mat22)
assert a.ptr == t.data_ptr()
assert not a.is_contiguous
assert a.shape == tuple(t.shape[:-2])
# copy contents to contiguous array
a_contiguous = wp.empty_like(a)
wp.launch(copy2d_mat22_kernel, dim=a.shape, inputs=[a_contiguous, a], device=device)
assert_np_equal(a_contiguous.numpy(), t.cpu().numpy())
def test_from_torch_zero_strides(test, device):
import torch
torch_device = wp.device_to_torch(device)
t_base = torch.arange(9, dtype=torch.float32, device=torch_device).reshape((3, 3))
# expand outermost dimension
t = t_base.unsqueeze(0).expand(3, -1, -1)
a = wp.from_torch(t)
assert a.ptr == t.data_ptr()
assert not a.is_contiguous
assert a.shape == tuple(t.shape)
a_contiguous = wp.empty_like(a)
wp.launch(copy3d_float_kernel, dim=a.shape, inputs=[a_contiguous, a], device=device)
assert_np_equal(a_contiguous.numpy(), t.cpu().numpy())
# expand middle dimension
t = t_base.unsqueeze(1).expand(-1, 3, -1)
a = wp.from_torch(t)
assert a.ptr == t.data_ptr()
assert not a.is_contiguous
assert a.shape == tuple(t.shape)
a_contiguous = wp.empty_like(a)
wp.launch(copy3d_float_kernel, dim=a.shape, inputs=[a_contiguous, a], device=device)
assert_np_equal(a_contiguous.numpy(), t.cpu().numpy())
# expand innermost dimension
t = t_base.unsqueeze(2).expand(-1, -1, 3)
a = wp.from_torch(t)
assert a.ptr == t.data_ptr()
assert not a.is_contiguous
assert a.shape == tuple(t.shape)
a_contiguous = wp.empty_like(a)
wp.launch(copy3d_float_kernel, dim=a.shape, inputs=[a_contiguous, a], device=device)
assert_np_equal(a_contiguous.numpy(), t.cpu().numpy())
def test_torch_mgpu_from_torch(test, device):
import torch
n = 32
t0 = torch.arange(0, n, 1, dtype=torch.int32, device="cuda:0")
t1 = torch.arange(0, n * 2, 2, dtype=torch.int32, device="cuda:1")
a0 = wp.from_torch(t0, dtype=wp.int32)
a1 = wp.from_torch(t1, dtype=wp.int32)
assert a0.device == "cuda:0"
assert a1.device == "cuda:1"
expected0 = np.arange(0, n, 1)
expected1 = np.arange(0, n * 2, 2)
assert_np_equal(a0.numpy(), expected0)
assert_np_equal(a1.numpy(), expected1)
def test_torch_mgpu_to_torch(test, device):
n = 32
with wp.ScopedDevice("cuda:0"):
a0 = wp.empty(n, dtype=wp.int32)
wp.launch(arange, dim=a0.size, inputs=[0, 1, a0])
with wp.ScopedDevice("cuda:1"):
a1 = wp.empty(n, dtype=wp.int32)
wp.launch(arange, dim=a1.size, inputs=[0, 2, a1])
t0 = wp.to_torch(a0)
t1 = wp.to_torch(a1)
assert str(t0.device) == "cuda:0"
assert str(t1.device) == "cuda:1"
expected0 = np.arange(0, n, 1, dtype=np.int32)
expected1 = np.arange(0, n * 2, 2, dtype=np.int32)
assert_np_equal(t0.cpu().numpy(), expected0)
assert_np_equal(t1.cpu().numpy(), expected1)
def test_torch_mgpu_interop(test, device):
import torch
n = 1024 * 1024
with torch.cuda.device(0):
t0 = torch.arange(n, dtype=torch.float32, device="cuda")
a0 = wp.from_torch(t0)
wp.launch(inc, dim=a0.size, inputs=[a0], stream=wp.stream_from_torch())
with torch.cuda.device(1):
t1 = torch.arange(n, dtype=torch.float32, device="cuda")
a1 = wp.from_torch(t1)
wp.launch(inc, dim=a1.size, inputs=[a1], stream=wp.stream_from_torch())
assert a0.device == "cuda:0"
assert a1.device == "cuda:1"
expected = np.arange(n, dtype=int) + 1
# ensure the torch tensors were modified by warp
assert_np_equal(t0.cpu().numpy(), expected)
assert_np_equal(t1.cpu().numpy(), expected)
def test_torch_autograd(test, device):
"""Test torch autograd with a custom Warp op"""
import torch
# custom autograd op
class TestFunc(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
# allocate output array
y = torch.empty_like(x)
ctx.x = x
ctx.y = y
wp.launch(kernel=op_kernel, dim=len(x), inputs=[wp.from_torch(x)], outputs=[wp.from_torch(y)])
return y
@staticmethod
def backward(ctx, adj_y):
# adjoints should be allocated as zero initialized
adj_x = torch.zeros_like(ctx.x).contiguous()
adj_y = adj_y.contiguous()
wp_x = wp.from_torch(ctx.x, grad=adj_x)
wp_y = wp.from_torch(ctx.y, grad=adj_y)
wp.launch(
kernel=op_kernel,
dim=len(ctx.x),
# fwd inputs
inputs=[wp_x],
outputs=[wp_y],
# adj inputs (already stored in input/output arrays, passing null pointers)
adj_inputs=[None],
adj_outputs=[None],
adjoint=True,
)
return adj_x
# run autograd on given device
with wp.ScopedDevice(device):
torch_device = wp.device_to_torch(device)
# input data
x = torch.ones(16, dtype=torch.float32, device=torch_device, requires_grad=True)
# execute op
y = TestFunc.apply(x)
# compute grads
l = y.sum()
l.backward()
passed = (x.grad == -2.0).all()
assert passed.item()
def test_torch_graph_torch_stream(test, device):
"""Capture Torch graph on Torch stream"""
import torch
torch_device = wp.device_to_torch(device)
n = 1024 * 1024
t = torch.zeros(n, dtype=torch.float32, device=torch_device)
a = wp.from_torch(t)
g = torch.cuda.CUDAGraph()
# create a device-specific torch stream to use for capture
# (otherwise torch.cuda.graph reuses its capture stream, which can be problematic if it's from a different device)
torch_stream = torch.cuda.Stream(device=torch_device)
# make warp use the same stream
warp_stream = wp.stream_from_torch(torch_stream)
# capture graph
with wp.ScopedStream(warp_stream), torch.cuda.graph(g, stream=torch_stream):
t += 1.0
wp.launch(inc, dim=n, inputs=[a])
t += 1.0
wp.launch(inc, dim=n, inputs=[a])
# replay graph
num_iters = 10
for i in range(num_iters):
g.replay()
passed = (t == num_iters * 4.0).all()
assert passed.item()
def test_torch_graph_warp_stream(test, device):
"""Capture Torch graph on Warp stream"""
import torch
torch_device = wp.device_to_torch(device)
n = 1024 * 1024
t = torch.zeros(n, dtype=torch.float32, device=torch_device)
a = wp.from_torch(t)
g = torch.cuda.CUDAGraph()
# make torch use the warp stream from the given device
torch_stream = wp.stream_to_torch(device)
# capture graph
with wp.ScopedDevice(device), torch.cuda.graph(g, stream=torch_stream):
t += 1.0
wp.launch(inc, dim=n, inputs=[a])
t += 1.0
wp.launch(inc, dim=n, inputs=[a])
# replay graph
num_iters = 10
for i in range(num_iters):
g.replay()
passed = (t == num_iters * 4.0).all()
assert passed.item()
def test_warp_graph_warp_stream(test, device):
"""Capture Warp graph on Warp stream"""
import torch
torch_device = wp.device_to_torch(device)
n = 1024 * 1024
t = torch.zeros(n, dtype=torch.float32, device=torch_device)
a = wp.from_torch(t)
# make torch use the warp stream from the given device
torch_stream = wp.stream_to_torch(device)
# capture graph
with wp.ScopedDevice(device), torch.cuda.stream(torch_stream):
wp.capture_begin()
t += 1.0
wp.launch(inc, dim=n, inputs=[a])
t += 1.0
wp.launch(inc, dim=n, inputs=[a])
g = wp.capture_end()
# replay graph
num_iters = 10
for i in range(num_iters):
wp.capture_launch(g)
passed = (t == num_iters * 4.0).all()
assert passed.item()
def test_warp_graph_torch_stream(test, device):
"""Capture Warp graph on Torch stream"""
import torch
torch_device = wp.device_to_torch(device)
n = 1024 * 1024
t = torch.zeros(n, dtype=torch.float32, device=torch_device)
a = wp.from_torch(t)
# create a device-specific torch stream to use for capture
# (the default torch stream is not suitable for graph capture)
torch_stream = torch.cuda.Stream(device=torch_device)
# make warp use the same stream
warp_stream = wp.stream_from_torch(torch_stream)
# capture graph
with wp.ScopedStream(warp_stream), torch.cuda.stream(torch_stream):
wp.capture_begin()
t += 1.0
wp.launch(inc, dim=n, inputs=[a])
t += 1.0
wp.launch(inc, dim=n, inputs=[a])
g = wp.capture_end()
# replay graph
num_iters = 10
for i in range(num_iters):
wp.capture_launch(g)
passed = (t == num_iters * 4.0).all()
assert passed.item()
def register(parent):
class TestTorch(parent):
pass
try:
import torch
# check which Warp devices work with Torch
# CUDA devices may fail if Torch was not compiled with CUDA support
test_devices = get_test_devices()
torch_compatible_devices = []
torch_compatible_cuda_devices = []
for d in test_devices:
try:
t = torch.arange(10, device=wp.device_to_torch(d))
t += 1
torch_compatible_devices.append(d)
if d.is_cuda:
torch_compatible_cuda_devices.append(d)
except Exception as e:
print(f"Skipping Torch tests on device '{d}' due to exception: {e}")
if torch_compatible_devices:
add_function_test(TestTorch, "test_from_torch", test_from_torch, devices=torch_compatible_devices)
add_function_test(
TestTorch, "test_from_torch_slices", test_from_torch_slices, devices=torch_compatible_devices
)
add_function_test(
TestTorch,
"test_from_torch_zero_strides",
test_from_torch_zero_strides,
devices=torch_compatible_devices,
)
add_function_test(TestTorch, "test_to_torch", test_to_torch, devices=torch_compatible_devices)
add_function_test(TestTorch, "test_torch_zerocopy", test_torch_zerocopy, devices=torch_compatible_devices)
add_function_test(TestTorch, "test_torch_autograd", test_torch_autograd, devices=torch_compatible_devices)
if torch_compatible_cuda_devices:
add_function_test(
TestTorch,
"test_torch_graph_torch_stream",
test_torch_graph_torch_stream,
devices=torch_compatible_cuda_devices,
)
add_function_test(
TestTorch,
"test_torch_graph_warp_stream",
test_torch_graph_warp_stream,
devices=torch_compatible_cuda_devices,
)
add_function_test(
TestTorch,
"test_warp_graph_warp_stream",
test_warp_graph_warp_stream,
devices=torch_compatible_cuda_devices,
)
add_function_test(
TestTorch,
"test_warp_graph_torch_stream",
test_warp_graph_torch_stream,
devices=torch_compatible_cuda_devices,
)
# multi-GPU tests
if len(torch_compatible_cuda_devices) > 1:
add_function_test(TestTorch, "test_torch_mgpu_from_torch", test_torch_mgpu_from_torch)
add_function_test(TestTorch, "test_torch_mgpu_to_torch", test_torch_mgpu_to_torch)
add_function_test(TestTorch, "test_torch_mgpu_interop", test_torch_mgpu_interop)
except Exception as e:
print(f"Skipping Torch tests due to exception: {e}")
return TestTorch
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_torch.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import numpy as np
import warp as wp
from warp.tests.test_base import *
wp.init()
np_signed_int_types = [
np.int8,
np.int16,
np.int32,
np.int64,
np.byte,
]
np_unsigned_int_types = [
np.uint8,
np.uint16,
np.uint32,
np.uint64,
np.ubyte,
]
np_int_types = np_signed_int_types + np_unsigned_int_types
np_float_types = [np.float16, np.float32, np.float64]
np_scalar_types = np_int_types + np_float_types
def randvals(shape, dtype):
if dtype in np_float_types:
return np.random.randn(*shape).astype(dtype)
elif dtype in [np.int8, np.uint8, np.byte, np.ubyte]:
return np.random.randint(1, 3, size=shape, dtype=dtype)
return np.random.randint(1, 5, size=shape, dtype=dtype)
kernel_cache = dict()
def getkernel(func, suffix=""):
module = wp.get_module(func.__module__)
key = func.__name__ + "_" + suffix
if key not in kernel_cache:
kernel_cache[key] = wp.Kernel(func=func, key=key, module=module)
return kernel_cache[key]
def get_select_kernel(dtype):
def output_select_kernel_fn(
input: wp.array(dtype=dtype),
index: int,
out: wp.array(dtype=dtype),
):
out[0] = input[index]
return getkernel(output_select_kernel_fn, suffix=dtype.__name__)
def get_select_kernel2(dtype):
def output_select_kernel2_fn(
input: wp.array(dtype=dtype, ndim=2),
index0: int,
index1: int,
out: wp.array(dtype=dtype),
):
out[0] = input[index0, index1]
return getkernel(output_select_kernel2_fn, suffix=dtype.__name__)
def test_arrays(test, device, dtype):
np.random.seed(123)
tol = {
np.float16: 1.0e-3,
np.float32: 1.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
vec2 = wp.types.vector(length=2, dtype=wptype)
vec3 = wp.types.vector(length=3, dtype=wptype)
vec4 = wp.types.vector(length=4, dtype=wptype)
vec5 = wp.types.vector(length=5, dtype=wptype)
v2_np = randvals((10, 2), dtype)
v3_np = randvals((10, 3), dtype)
v4_np = randvals((10, 4), dtype)
v5_np = randvals((10, 5), dtype)
v2 = wp.array(v2_np, dtype=vec2, requires_grad=True, device=device)
v3 = wp.array(v3_np, dtype=vec3, requires_grad=True, device=device)
v4 = wp.array(v4_np, dtype=vec4, requires_grad=True, device=device)
v5 = wp.array(v5_np, dtype=vec5, requires_grad=True, device=device)
assert_np_equal(v2.numpy(), v2_np, tol=1.0e-6)
assert_np_equal(v3.numpy(), v3_np, tol=1.0e-6)
assert_np_equal(v4.numpy(), v4_np, tol=1.0e-6)
assert_np_equal(v5.numpy(), v5_np, tol=1.0e-6)
vec2 = wp.types.vector(length=2, dtype=wptype)
vec3 = wp.types.vector(length=3, dtype=wptype)
vec4 = wp.types.vector(length=4, dtype=wptype)
v2 = wp.array(v2_np, dtype=vec2, requires_grad=True, device=device)
v3 = wp.array(v3_np, dtype=vec3, requires_grad=True, device=device)
v4 = wp.array(v4_np, dtype=vec4, requires_grad=True, device=device)
assert_np_equal(v2.numpy(), v2_np, tol=1.0e-6)
assert_np_equal(v3.numpy(), v3_np, tol=1.0e-6)
assert_np_equal(v4.numpy(), v4_np, tol=1.0e-6)
def test_components(test, device, dtype):
# test accessing vector components from Python - this is especially important
# for float16, which requires special handling internally
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
vec3 = wp.types.vector(length=3, dtype=wptype)
v = vec3(1, 2, 3)
# test __getitem__ for individual components
test.assertEqual(v[0], 1)
test.assertEqual(v[1], 2)
test.assertEqual(v[2], 3)
# test __getitem__ for slices
s = v[:]
test.assertEqual(s[0], 1)
test.assertEqual(s[1], 2)
test.assertEqual(s[2], 3)
s = v[1:]
test.assertEqual(s[0], 2)
test.assertEqual(s[1], 3)
s = v[:2]
test.assertEqual(s[0], 1)
test.assertEqual(s[1], 2)
s = v[::2]
test.assertEqual(s[0], 1)
test.assertEqual(s[1], 3)
# test __setitem__ for individual components
v[0] = 4
v[1] = 5
v[2] = 6
test.assertEqual(v[0], 4)
test.assertEqual(v[1], 5)
test.assertEqual(v[2], 6)
# test __setitem__ for slices
v[:] = [7, 8, 9]
test.assertEqual(v[0], 7)
test.assertEqual(v[1], 8)
test.assertEqual(v[2], 9)
v[1:] = [10, 11]
test.assertEqual(v[0], 7)
test.assertEqual(v[1], 10)
test.assertEqual(v[2], 11)
v[:2] = [12, 13]
test.assertEqual(v[0], 12)
test.assertEqual(v[1], 13)
test.assertEqual(v[2], 11)
v[::2] = [14, 15]
test.assertEqual(v[0], 14)
test.assertEqual(v[1], 13)
test.assertEqual(v[2], 15)
def test_anon_type_instance(test, device, dtype, register_kernels=False):
np.random.seed(123)
tol = {
np.float16: 5.0e-3,
np.float32: 1.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
def check_scalar_init(
input: wp.array(dtype=wptype),
output: wp.array(dtype=wptype),
):
v2result = wp.vector(input[0], length=2)
v3result = wp.vector(input[1], length=3)
v4result = wp.vector(input[2], length=4)
v5result = wp.vector(input[3], length=5)
idx = 0
for i in range(2):
output[idx] = wptype(2) * v2result[i]
idx = idx + 1
for i in range(3):
output[idx] = wptype(2) * v3result[i]
idx = idx + 1
for i in range(4):
output[idx] = wptype(2) * v4result[i]
idx = idx + 1
for i in range(5):
output[idx] = wptype(2) * v5result[i]
idx = idx + 1
def check_component_init(
input: wp.array(dtype=wptype),
output: wp.array(dtype=wptype),
):
v2result = wp.vector(input[0], input[1])
v3result = wp.vector(input[2], input[3], input[4])
v4result = wp.vector(input[5], input[6], input[7], input[8])
v5result = wp.vector(input[9], input[10], input[11], input[12], input[13])
idx = 0
for i in range(2):
output[idx] = wptype(2) * v2result[i]
idx = idx + 1
for i in range(3):
output[idx] = wptype(2) * v3result[i]
idx = idx + 1
for i in range(4):
output[idx] = wptype(2) * v4result[i]
idx = idx + 1
for i in range(5):
output[idx] = wptype(2) * v5result[i]
idx = idx + 1
scalar_kernel = getkernel(check_scalar_init, suffix=dtype.__name__)
component_kernel = getkernel(check_component_init, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
if register_kernels:
return
input = wp.array(randvals([4], dtype), requires_grad=True, device=device)
output = wp.zeros(2 + 3 + 4 + 5, dtype=wptype, requires_grad=True, device=device)
wp.launch(scalar_kernel, dim=1, inputs=[input], outputs=[output], device=device)
assert_np_equal(output.numpy()[:2], 2 * np.array([input.numpy()[0]] * 2), tol=1.0e-6)
assert_np_equal(output.numpy()[2:5], 2 * np.array([input.numpy()[1]] * 3), tol=1.0e-6)
assert_np_equal(output.numpy()[5:9], 2 * np.array([input.numpy()[2]] * 4), tol=1.0e-6)
assert_np_equal(output.numpy()[9:], 2 * np.array([input.numpy()[3]] * 5), tol=1.0e-6)
if dtype in np_float_types:
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for i in range(len(output)):
tape = wp.Tape()
with tape:
wp.launch(scalar_kernel, dim=1, inputs=[input], outputs=[output], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[output, i], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(input.numpy())
if i < 2:
expected[0] = 2
elif i < 5:
expected[1] = 2
elif i < 9:
expected[2] = 2
else:
expected[3] = 2
assert_np_equal(tape.gradients[input].numpy(), expected, tol=tol)
tape.reset()
tape.zero()
input = wp.array(randvals([2 + 3 + 4 + 5], dtype), requires_grad=True, device=device)
output = wp.zeros(2 + 3 + 4 + 5, dtype=wptype, requires_grad=True, device=device)
wp.launch(component_kernel, dim=1, inputs=[input], outputs=[output], device=device)
assert_np_equal(output.numpy(), 2 * input.numpy(), tol=1.0e-6)
if dtype in np_float_types:
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for i in range(len(output)):
tape = wp.Tape()
with tape:
wp.launch(component_kernel, dim=1, inputs=[input], outputs=[output], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[output, i], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(input.numpy())
expected[i] = 2
assert_np_equal(tape.gradients[input].numpy(), expected, tol=tol)
tape.reset()
tape.zero()
def test_constants(test, device, dtype, register_kernels=False):
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
vec2 = wp.types.vector(length=2, dtype=wptype)
vec3 = wp.types.vector(length=3, dtype=wptype)
vec4 = wp.types.vector(length=4, dtype=wptype)
vec5 = wp.types.vector(length=5, dtype=wptype)
cv2 = wp.constant(vec2(1, 2))
cv3 = wp.constant(vec3(1, 2, 3))
cv4 = wp.constant(vec4(1, 2, 3, 4))
cv5 = wp.constant(vec5(1, 2, 3, 4, 5))
def check_vector_constants():
wp.expect_eq(cv2, vec2(wptype(1), wptype(2)))
wp.expect_eq(cv3, vec3(wptype(1), wptype(2), wptype(3)))
wp.expect_eq(cv4, vec4(wptype(1), wptype(2), wptype(3), wptype(4)))
wp.expect_eq(cv5, vec5(wptype(1), wptype(2), wptype(3), wptype(4), wptype(5)))
kernel = getkernel(check_vector_constants, suffix=dtype.__name__)
if register_kernels:
return
wp.launch(kernel, dim=1, inputs=[])
def test_constructors(test, device, dtype, register_kernels=False):
np.random.seed(123)
tol = {
np.float16: 5.0e-3,
np.float32: 1.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
vec2 = wp.types.vector(length=2, dtype=wptype)
vec3 = wp.types.vector(length=3, dtype=wptype)
vec4 = wp.types.vector(length=4, dtype=wptype)
vec5 = wp.types.vector(length=5, dtype=wptype)
def check_scalar_constructor(
input: wp.array(dtype=wptype),
v2: wp.array(dtype=vec2),
v3: wp.array(dtype=vec3),
v4: wp.array(dtype=vec4),
v5: wp.array(dtype=vec5),
v20: wp.array(dtype=wptype),
v21: wp.array(dtype=wptype),
v30: wp.array(dtype=wptype),
v31: wp.array(dtype=wptype),
v32: wp.array(dtype=wptype),
v40: wp.array(dtype=wptype),
v41: wp.array(dtype=wptype),
v42: wp.array(dtype=wptype),
v43: wp.array(dtype=wptype),
v50: wp.array(dtype=wptype),
v51: wp.array(dtype=wptype),
v52: wp.array(dtype=wptype),
v53: wp.array(dtype=wptype),
v54: wp.array(dtype=wptype),
):
v2result = vec2(input[0])
v3result = vec3(input[0])
v4result = vec4(input[0])
v5result = vec5(input[0])
v2[0] = v2result
v3[0] = v3result
v4[0] = v4result
v5[0] = v5result
# multiply outputs by 2 so we've got something to backpropagate
v20[0] = wptype(2) * v2result[0]
v21[0] = wptype(2) * v2result[1]
v30[0] = wptype(2) * v3result[0]
v31[0] = wptype(2) * v3result[1]
v32[0] = wptype(2) * v3result[2]
v40[0] = wptype(2) * v4result[0]
v41[0] = wptype(2) * v4result[1]
v42[0] = wptype(2) * v4result[2]
v43[0] = wptype(2) * v4result[3]
v50[0] = wptype(2) * v5result[0]
v51[0] = wptype(2) * v5result[1]
v52[0] = wptype(2) * v5result[2]
v53[0] = wptype(2) * v5result[3]
v54[0] = wptype(2) * v5result[4]
def check_vector_constructors(
input: wp.array(dtype=wptype),
v2: wp.array(dtype=vec2),
v3: wp.array(dtype=vec3),
v4: wp.array(dtype=vec4),
v5: wp.array(dtype=vec5),
v20: wp.array(dtype=wptype),
v21: wp.array(dtype=wptype),
v30: wp.array(dtype=wptype),
v31: wp.array(dtype=wptype),
v32: wp.array(dtype=wptype),
v40: wp.array(dtype=wptype),
v41: wp.array(dtype=wptype),
v42: wp.array(dtype=wptype),
v43: wp.array(dtype=wptype),
v50: wp.array(dtype=wptype),
v51: wp.array(dtype=wptype),
v52: wp.array(dtype=wptype),
v53: wp.array(dtype=wptype),
v54: wp.array(dtype=wptype),
):
v2result = vec2(input[0], input[1])
v3result = vec3(input[2], input[3], input[4])
v4result = vec4(input[5], input[6], input[7], input[8])
v5result = vec5(input[9], input[10], input[11], input[12], input[13])
v2[0] = v2result
v3[0] = v3result
v4[0] = v4result
v5[0] = v5result
# multiply the output by 2 so we've got something to backpropagate:
v20[0] = wptype(2) * v2result[0]
v21[0] = wptype(2) * v2result[1]
v30[0] = wptype(2) * v3result[0]
v31[0] = wptype(2) * v3result[1]
v32[0] = wptype(2) * v3result[2]
v40[0] = wptype(2) * v4result[0]
v41[0] = wptype(2) * v4result[1]
v42[0] = wptype(2) * v4result[2]
v43[0] = wptype(2) * v4result[3]
v50[0] = wptype(2) * v5result[0]
v51[0] = wptype(2) * v5result[1]
v52[0] = wptype(2) * v5result[2]
v53[0] = wptype(2) * v5result[3]
v54[0] = wptype(2) * v5result[4]
vec_kernel = getkernel(check_vector_constructors, suffix=dtype.__name__)
kernel = getkernel(check_scalar_constructor, suffix=dtype.__name__)
if register_kernels:
return
input = wp.array(randvals([1], dtype), requires_grad=True, device=device)
v2 = wp.zeros(1, dtype=vec2, device=device)
v3 = wp.zeros(1, dtype=vec3, device=device)
v4 = wp.zeros(1, dtype=vec4, device=device)
v5 = wp.zeros(1, dtype=vec5, device=device)
v20 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v21 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v30 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v31 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v32 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v40 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v41 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v42 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v43 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v50 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v51 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v52 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v53 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v54 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[input],
outputs=[v2, v3, v4, v5, v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54],
device=device,
)
if dtype in np_float_types:
for l in [v20, v21]:
tape.backward(loss=l)
test.assertEqual(tape.gradients[input].numpy()[0], 2.0)
tape.zero()
for l in [v30, v31, v32]:
tape.backward(loss=l)
test.assertEqual(tape.gradients[input].numpy()[0], 2.0)
tape.zero()
for l in [v40, v41, v42, v43]:
tape.backward(loss=l)
test.assertEqual(tape.gradients[input].numpy()[0], 2.0)
tape.zero()
for l in [v50, v51, v52, v53, v54]:
tape.backward(loss=l)
test.assertEqual(tape.gradients[input].numpy()[0], 2.0)
tape.zero()
val = input.numpy()[0]
assert_np_equal(v2.numpy()[0], np.array([val, val]), tol=1.0e-6)
assert_np_equal(v3.numpy()[0], np.array([val, val, val]), tol=1.0e-6)
assert_np_equal(v4.numpy()[0], np.array([val, val, val, val]), tol=1.0e-6)
assert_np_equal(v5.numpy()[0], np.array([val, val, val, val, val]), tol=1.0e-6)
assert_np_equal(v20.numpy()[0], 2 * val, tol=1.0e-6)
assert_np_equal(v21.numpy()[0], 2 * val, tol=1.0e-6)
assert_np_equal(v30.numpy()[0], 2 * val, tol=1.0e-6)
assert_np_equal(v31.numpy()[0], 2 * val, tol=1.0e-6)
assert_np_equal(v32.numpy()[0], 2 * val, tol=1.0e-6)
assert_np_equal(v40.numpy()[0], 2 * val, tol=1.0e-6)
assert_np_equal(v41.numpy()[0], 2 * val, tol=1.0e-6)
assert_np_equal(v42.numpy()[0], 2 * val, tol=1.0e-6)
assert_np_equal(v43.numpy()[0], 2 * val, tol=1.0e-6)
assert_np_equal(v50.numpy()[0], 2 * val, tol=1.0e-6)
assert_np_equal(v51.numpy()[0], 2 * val, tol=1.0e-6)
assert_np_equal(v52.numpy()[0], 2 * val, tol=1.0e-6)
assert_np_equal(v53.numpy()[0], 2 * val, tol=1.0e-6)
assert_np_equal(v54.numpy()[0], 2 * val, tol=1.0e-6)
input = wp.array(randvals([14], dtype), requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
vec_kernel,
dim=1,
inputs=[input],
outputs=[v2, v3, v4, v5, v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54],
device=device,
)
if dtype in np_float_types:
for i, l in enumerate([v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54]):
tape.backward(loss=l)
grad = tape.gradients[input].numpy()
expected_grad = np.zeros_like(grad)
expected_grad[i] = 2
assert_np_equal(grad, expected_grad, tol=tol)
tape.zero()
assert_np_equal(v2.numpy()[0, 0], input.numpy()[0], tol=tol)
assert_np_equal(v2.numpy()[0, 1], input.numpy()[1], tol=tol)
assert_np_equal(v3.numpy()[0, 0], input.numpy()[2], tol=tol)
assert_np_equal(v3.numpy()[0, 1], input.numpy()[3], tol=tol)
assert_np_equal(v3.numpy()[0, 2], input.numpy()[4], tol=tol)
assert_np_equal(v4.numpy()[0, 0], input.numpy()[5], tol=tol)
assert_np_equal(v4.numpy()[0, 1], input.numpy()[6], tol=tol)
assert_np_equal(v4.numpy()[0, 2], input.numpy()[7], tol=tol)
assert_np_equal(v4.numpy()[0, 3], input.numpy()[8], tol=tol)
assert_np_equal(v5.numpy()[0, 0], input.numpy()[9], tol=tol)
assert_np_equal(v5.numpy()[0, 1], input.numpy()[10], tol=tol)
assert_np_equal(v5.numpy()[0, 2], input.numpy()[11], tol=tol)
assert_np_equal(v5.numpy()[0, 3], input.numpy()[12], tol=tol)
assert_np_equal(v5.numpy()[0, 4], input.numpy()[13], tol=tol)
assert_np_equal(v20.numpy()[0], 2 * input.numpy()[0], tol=tol)
assert_np_equal(v21.numpy()[0], 2 * input.numpy()[1], tol=tol)
assert_np_equal(v30.numpy()[0], 2 * input.numpy()[2], tol=tol)
assert_np_equal(v31.numpy()[0], 2 * input.numpy()[3], tol=tol)
assert_np_equal(v32.numpy()[0], 2 * input.numpy()[4], tol=tol)
assert_np_equal(v40.numpy()[0], 2 * input.numpy()[5], tol=tol)
assert_np_equal(v41.numpy()[0], 2 * input.numpy()[6], tol=tol)
assert_np_equal(v42.numpy()[0], 2 * input.numpy()[7], tol=tol)
assert_np_equal(v43.numpy()[0], 2 * input.numpy()[8], tol=tol)
assert_np_equal(v50.numpy()[0], 2 * input.numpy()[9], tol=tol)
assert_np_equal(v51.numpy()[0], 2 * input.numpy()[10], tol=tol)
assert_np_equal(v52.numpy()[0], 2 * input.numpy()[11], tol=tol)
assert_np_equal(v53.numpy()[0], 2 * input.numpy()[12], tol=tol)
assert_np_equal(v54.numpy()[0], 2 * input.numpy()[13], tol=tol)
def test_indexing(test, device, dtype, register_kernels=False):
np.random.seed(123)
tol = {
np.float16: 5.0e-3,
np.float32: 1.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
vec2 = wp.types.vector(length=2, dtype=wptype)
vec3 = wp.types.vector(length=3, dtype=wptype)
vec4 = wp.types.vector(length=4, dtype=wptype)
vec5 = wp.types.vector(length=5, dtype=wptype)
def check_indexing(
v2: wp.array(dtype=vec2),
v3: wp.array(dtype=vec3),
v4: wp.array(dtype=vec4),
v5: wp.array(dtype=vec5),
v20: wp.array(dtype=wptype),
v21: wp.array(dtype=wptype),
v30: wp.array(dtype=wptype),
v31: wp.array(dtype=wptype),
v32: wp.array(dtype=wptype),
v40: wp.array(dtype=wptype),
v41: wp.array(dtype=wptype),
v42: wp.array(dtype=wptype),
v43: wp.array(dtype=wptype),
v50: wp.array(dtype=wptype),
v51: wp.array(dtype=wptype),
v52: wp.array(dtype=wptype),
v53: wp.array(dtype=wptype),
v54: wp.array(dtype=wptype),
):
# multiply outputs by 2 so we've got something to backpropagate:
v20[0] = wptype(2) * v2[0][0]
v21[0] = wptype(2) * v2[0][1]
v30[0] = wptype(2) * v3[0][0]
v31[0] = wptype(2) * v3[0][1]
v32[0] = wptype(2) * v3[0][2]
v40[0] = wptype(2) * v4[0][0]
v41[0] = wptype(2) * v4[0][1]
v42[0] = wptype(2) * v4[0][2]
v43[0] = wptype(2) * v4[0][3]
v50[0] = wptype(2) * v5[0][0]
v51[0] = wptype(2) * v5[0][1]
v52[0] = wptype(2) * v5[0][2]
v53[0] = wptype(2) * v5[0][3]
v54[0] = wptype(2) * v5[0][4]
kernel = getkernel(check_indexing, suffix=dtype.__name__)
if register_kernels:
return
v2 = wp.array(randvals((1, 2), dtype), dtype=vec2, requires_grad=True, device=device)
v3 = wp.array(randvals((1, 3), dtype), dtype=vec3, requires_grad=True, device=device)
v4 = wp.array(randvals((1, 4), dtype), dtype=vec4, requires_grad=True, device=device)
v5 = wp.array(randvals((1, 5), dtype), dtype=vec5, requires_grad=True, device=device)
v20 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v21 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v30 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v31 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v32 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v40 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v41 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v42 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v43 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v50 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v51 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v52 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v53 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v54 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[v2, v3, v4, v5],
outputs=[v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54],
device=device,
)
if dtype in np_float_types:
for i, l in enumerate([v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54]):
tape.backward(loss=l)
allgrads = np.concatenate([tape.gradients[v].numpy()[0] for v in [v2, v3, v4, v5]])
expected_grads = np.zeros_like(allgrads)
expected_grads[i] = 2
assert_np_equal(allgrads, expected_grads, tol=tol)
tape.zero()
assert_np_equal(v20.numpy()[0], 2.0 * v2.numpy()[0, 0], tol=tol)
assert_np_equal(v21.numpy()[0], 2.0 * v2.numpy()[0, 1], tol=tol)
assert_np_equal(v30.numpy()[0], 2.0 * v3.numpy()[0, 0], tol=tol)
assert_np_equal(v31.numpy()[0], 2.0 * v3.numpy()[0, 1], tol=tol)
assert_np_equal(v32.numpy()[0], 2.0 * v3.numpy()[0, 2], tol=tol)
assert_np_equal(v40.numpy()[0], 2.0 * v4.numpy()[0, 0], tol=tol)
assert_np_equal(v41.numpy()[0], 2.0 * v4.numpy()[0, 1], tol=tol)
assert_np_equal(v42.numpy()[0], 2.0 * v4.numpy()[0, 2], tol=tol)
assert_np_equal(v43.numpy()[0], 2.0 * v4.numpy()[0, 3], tol=tol)
assert_np_equal(v50.numpy()[0], 2.0 * v5.numpy()[0, 0], tol=tol)
assert_np_equal(v51.numpy()[0], 2.0 * v5.numpy()[0, 1], tol=tol)
assert_np_equal(v52.numpy()[0], 2.0 * v5.numpy()[0, 2], tol=tol)
assert_np_equal(v53.numpy()[0], 2.0 * v5.numpy()[0, 3], tol=tol)
assert_np_equal(v54.numpy()[0], 2.0 * v5.numpy()[0, 4], tol=tol)
def test_equality(test, device, dtype, register_kernels=False):
np.random.seed(123)
tol = {
np.float16: 1.0e-3,
np.float32: 1.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
vec2 = wp.types.vector(length=2, dtype=wptype)
vec3 = wp.types.vector(length=3, dtype=wptype)
vec4 = wp.types.vector(length=4, dtype=wptype)
vec5 = wp.types.vector(length=5, dtype=wptype)
def check_equality(
v20: wp.array(dtype=vec2),
v21: wp.array(dtype=vec2),
v22: wp.array(dtype=vec2),
v30: wp.array(dtype=vec3),
v31: wp.array(dtype=vec3),
v32: wp.array(dtype=vec3),
v33: wp.array(dtype=vec3),
v40: wp.array(dtype=vec4),
v41: wp.array(dtype=vec4),
v42: wp.array(dtype=vec4),
v43: wp.array(dtype=vec4),
v44: wp.array(dtype=vec4),
v50: wp.array(dtype=vec5),
v51: wp.array(dtype=vec5),
v52: wp.array(dtype=vec5),
v53: wp.array(dtype=vec5),
v54: wp.array(dtype=vec5),
v55: wp.array(dtype=vec5),
):
wp.expect_eq(v20[0], v20[0])
wp.expect_neq(v21[0], v20[0])
wp.expect_neq(v22[0], v20[0])
wp.expect_eq(v30[0], v30[0])
wp.expect_neq(v31[0], v30[0])
wp.expect_neq(v32[0], v30[0])
wp.expect_neq(v33[0], v30[0])
wp.expect_eq(v40[0], v40[0])
wp.expect_neq(v41[0], v40[0])
wp.expect_neq(v42[0], v40[0])
wp.expect_neq(v43[0], v40[0])
wp.expect_neq(v44[0], v40[0])
wp.expect_eq(v50[0], v50[0])
wp.expect_neq(v51[0], v50[0])
wp.expect_neq(v52[0], v50[0])
wp.expect_neq(v53[0], v50[0])
wp.expect_neq(v54[0], v50[0])
wp.expect_neq(v55[0], v50[0])
kernel = getkernel(check_equality, suffix=dtype.__name__)
if register_kernels:
return
v20 = wp.array([1.0, 2.0], dtype=vec2, requires_grad=True, device=device)
v21 = wp.array([1.0, 3.0], dtype=vec2, requires_grad=True, device=device)
v22 = wp.array([3.0, 2.0], dtype=vec2, requires_grad=True, device=device)
v30 = wp.array([1.0, 2.0, 3.0], dtype=vec3, requires_grad=True, device=device)
v31 = wp.array([-1.0, 2.0, 3.0], dtype=vec3, requires_grad=True, device=device)
v32 = wp.array([1.0, -2.0, 3.0], dtype=vec3, requires_grad=True, device=device)
v33 = wp.array([1.0, 2.0, -3.0], dtype=vec3, requires_grad=True, device=device)
v40 = wp.array([1.0, 2.0, 3.0, 4.0], dtype=vec4, requires_grad=True, device=device)
v41 = wp.array([-1.0, 2.0, 3.0, 4.0], dtype=vec4, requires_grad=True, device=device)
v42 = wp.array([1.0, -2.0, 3.0, 4.0], dtype=vec4, requires_grad=True, device=device)
v43 = wp.array([1.0, 2.0, -3.0, 4.0], dtype=vec4, requires_grad=True, device=device)
v44 = wp.array([1.0, 2.0, 3.0, -4.0], dtype=vec4, requires_grad=True, device=device)
v50 = wp.array([1.0, 2.0, 3.0, 4.0, 5.0], dtype=vec5, requires_grad=True, device=device)
v51 = wp.array([-1.0, 2.0, 3.0, 4.0, 5.0], dtype=vec5, requires_grad=True, device=device)
v52 = wp.array([1.0, -2.0, 3.0, 4.0, 5.0], dtype=vec5, requires_grad=True, device=device)
v53 = wp.array([1.0, 2.0, -3.0, 4.0, 5.0], dtype=vec5, requires_grad=True, device=device)
v54 = wp.array([1.0, 2.0, 3.0, -4.0, 5.0], dtype=vec5, requires_grad=True, device=device)
v55 = wp.array([1.0, 2.0, 3.0, 4.0, -5.0], dtype=vec5, requires_grad=True, device=device)
wp.launch(
kernel,
dim=1,
inputs=[
v20,
v21,
v22,
v30,
v31,
v32,
v33,
v40,
v41,
v42,
v43,
v44,
v50,
v51,
v52,
v53,
v54,
v55,
],
outputs=[],
device=device,
)
def test_negation(test, device, dtype, register_kernels=False):
np.random.seed(123)
tol = {
np.float16: 5.0e-3,
np.float32: 1.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
vec2 = wp.types.vector(length=2, dtype=wptype)
vec3 = wp.types.vector(length=3, dtype=wptype)
vec4 = wp.types.vector(length=4, dtype=wptype)
vec5 = wp.types.vector(length=5, dtype=wptype)
def check_negation(
v2: wp.array(dtype=vec2),
v3: wp.array(dtype=vec3),
v4: wp.array(dtype=vec4),
v5: wp.array(dtype=vec5),
v2out: wp.array(dtype=vec2),
v3out: wp.array(dtype=vec3),
v4out: wp.array(dtype=vec4),
v5out: wp.array(dtype=vec5),
v20: wp.array(dtype=wptype),
v21: wp.array(dtype=wptype),
v30: wp.array(dtype=wptype),
v31: wp.array(dtype=wptype),
v32: wp.array(dtype=wptype),
v40: wp.array(dtype=wptype),
v41: wp.array(dtype=wptype),
v42: wp.array(dtype=wptype),
v43: wp.array(dtype=wptype),
v50: wp.array(dtype=wptype),
v51: wp.array(dtype=wptype),
v52: wp.array(dtype=wptype),
v53: wp.array(dtype=wptype),
v54: wp.array(dtype=wptype),
):
v2result = -v2[0]
v3result = -v3[0]
v4result = -v4[0]
v5result = -v5[0]
v2out[0] = v2result
v3out[0] = v3result
v4out[0] = v4result
v5out[0] = v5result
# multiply these outputs by 2 so we've got something to backpropagate:
v20[0] = wptype(2) * v2result[0]
v21[0] = wptype(2) * v2result[1]
v30[0] = wptype(2) * v3result[0]
v31[0] = wptype(2) * v3result[1]
v32[0] = wptype(2) * v3result[2]
v40[0] = wptype(2) * v4result[0]
v41[0] = wptype(2) * v4result[1]
v42[0] = wptype(2) * v4result[2]
v43[0] = wptype(2) * v4result[3]
v50[0] = wptype(2) * v5result[0]
v51[0] = wptype(2) * v5result[1]
v52[0] = wptype(2) * v5result[2]
v53[0] = wptype(2) * v5result[3]
v54[0] = wptype(2) * v5result[4]
kernel = getkernel(check_negation, suffix=dtype.__name__)
if register_kernels:
return
v2 = wp.array(randvals((1, 2), dtype), dtype=vec2, requires_grad=True, device=device)
v3 = wp.array(randvals((1, 3), dtype), dtype=vec3, requires_grad=True, device=device)
v4 = wp.array(randvals((1, 4), dtype), dtype=vec4, requires_grad=True, device=device)
v5_np = randvals((1, 5), dtype)
v5 = wp.array(v5_np, dtype=vec5, requires_grad=True, device=device)
v2out = wp.zeros(1, dtype=vec2, device=device)
v3out = wp.zeros(1, dtype=vec3, device=device)
v4out = wp.zeros(1, dtype=vec4, device=device)
v5out = wp.zeros(1, dtype=vec5, device=device)
v20 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v21 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v30 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v31 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v32 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v40 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v41 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v42 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v43 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v50 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v51 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v52 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v53 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v54 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[v2, v3, v4, v5],
outputs=[v2out, v3out, v4out, v5out, v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54],
device=device,
)
if dtype in np_float_types:
for i, l in enumerate([v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54]):
tape.backward(loss=l)
allgrads = np.concatenate([tape.gradients[v].numpy()[0] for v in [v2, v3, v4, v5]])
expected_grads = np.zeros_like(allgrads)
expected_grads[i] = -2
assert_np_equal(allgrads, expected_grads, tol=tol)
tape.zero()
assert_np_equal(v2out.numpy()[0], -v2.numpy()[0], tol=tol)
assert_np_equal(v3out.numpy()[0], -v3.numpy()[0], tol=tol)
assert_np_equal(v4out.numpy()[0], -v4.numpy()[0], tol=tol)
assert_np_equal(v5out.numpy()[0], -v5.numpy()[0], tol=tol)
def test_scalar_multiplication(test, device, dtype, register_kernels=False):
np.random.seed(123)
tol = {
np.float16: 5.0e-3,
np.float32: 1.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
vec2 = wp.types.vector(length=2, dtype=wptype)
vec3 = wp.types.vector(length=3, dtype=wptype)
vec4 = wp.types.vector(length=4, dtype=wptype)
vec5 = wp.types.vector(length=5, dtype=wptype)
def check_mul(
s: wp.array(dtype=wptype),
v2: wp.array(dtype=vec2),
v3: wp.array(dtype=vec3),
v4: wp.array(dtype=vec4),
v5: wp.array(dtype=vec5),
v20: wp.array(dtype=wptype),
v21: wp.array(dtype=wptype),
v30: wp.array(dtype=wptype),
v31: wp.array(dtype=wptype),
v32: wp.array(dtype=wptype),
v40: wp.array(dtype=wptype),
v41: wp.array(dtype=wptype),
v42: wp.array(dtype=wptype),
v43: wp.array(dtype=wptype),
v50: wp.array(dtype=wptype),
v51: wp.array(dtype=wptype),
v52: wp.array(dtype=wptype),
v53: wp.array(dtype=wptype),
v54: wp.array(dtype=wptype),
):
v2result = s[0] * v2[0]
v3result = s[0] * v3[0]
v4result = s[0] * v4[0]
v5result = s[0] * v5[0]
# multiply outputs by 2 so we've got something to backpropagate:
v20[0] = wptype(2) * v2result[0]
v21[0] = wptype(2) * v2result[1]
v30[0] = wptype(2) * v3result[0]
v31[0] = wptype(2) * v3result[1]
v32[0] = wptype(2) * v3result[2]
v40[0] = wptype(2) * v4result[0]
v41[0] = wptype(2) * v4result[1]
v42[0] = wptype(2) * v4result[2]
v43[0] = wptype(2) * v4result[3]
v50[0] = wptype(2) * v5result[0]
v51[0] = wptype(2) * v5result[1]
v52[0] = wptype(2) * v5result[2]
v53[0] = wptype(2) * v5result[3]
v54[0] = wptype(2) * v5result[4]
kernel = getkernel(check_mul, suffix=dtype.__name__)
if register_kernels:
return
s = wp.array(randvals([1], dtype), requires_grad=True, device=device)
v2 = wp.array(randvals((1, 2), dtype), dtype=vec2, requires_grad=True, device=device)
v3 = wp.array(randvals((1, 3), dtype), dtype=vec3, requires_grad=True, device=device)
v4 = wp.array(randvals((1, 4), dtype), dtype=vec4, requires_grad=True, device=device)
v5 = wp.array(randvals((1, 5), dtype), dtype=vec5, requires_grad=True, device=device)
v20 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v21 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v30 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v31 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v32 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v40 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v41 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v42 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v43 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v50 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v51 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v52 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v53 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v54 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
s,
v2,
v3,
v4,
v5,
],
outputs=[v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54],
device=device,
)
assert_np_equal(v20.numpy()[0], 2 * s.numpy()[0] * v2.numpy()[0, 0], tol=tol)
assert_np_equal(v21.numpy()[0], 2 * s.numpy()[0] * v2.numpy()[0, 1], tol=tol)
assert_np_equal(v30.numpy()[0], 2 * s.numpy()[0] * v3.numpy()[0, 0], tol=10 * tol)
assert_np_equal(v31.numpy()[0], 2 * s.numpy()[0] * v3.numpy()[0, 1], tol=10 * tol)
assert_np_equal(v32.numpy()[0], 2 * s.numpy()[0] * v3.numpy()[0, 2], tol=10 * tol)
assert_np_equal(v40.numpy()[0], 2 * s.numpy()[0] * v4.numpy()[0, 0], tol=10 * tol)
assert_np_equal(v41.numpy()[0], 2 * s.numpy()[0] * v4.numpy()[0, 1], tol=10 * tol)
assert_np_equal(v42.numpy()[0], 2 * s.numpy()[0] * v4.numpy()[0, 2], tol=10 * tol)
assert_np_equal(v43.numpy()[0], 2 * s.numpy()[0] * v4.numpy()[0, 3], tol=10 * tol)
assert_np_equal(v50.numpy()[0], 2 * s.numpy()[0] * v5.numpy()[0, 0], tol=10 * tol)
assert_np_equal(v51.numpy()[0], 2 * s.numpy()[0] * v5.numpy()[0, 1], tol=10 * tol)
assert_np_equal(v52.numpy()[0], 2 * s.numpy()[0] * v5.numpy()[0, 2], tol=10 * tol)
assert_np_equal(v53.numpy()[0], 2 * s.numpy()[0] * v5.numpy()[0, 3], tol=10 * tol)
assert_np_equal(v54.numpy()[0], 2 * s.numpy()[0] * v5.numpy()[0, 4], tol=10 * tol)
incmps = np.concatenate([v.numpy()[0] for v in [v2, v3, v4, v5]])
if dtype in np_float_types:
for i, l in enumerate([v20, v21, v30, v31, v32, v40, v41, v42, v43]):
tape.backward(loss=l)
sgrad = tape.gradients[s].numpy()[0]
assert_np_equal(sgrad, 2 * incmps[i], tol=10 * tol)
allgrads = np.concatenate([tape.gradients[v].numpy()[0] for v in [v2, v3, v4]])
expected_grads = np.zeros_like(allgrads)
expected_grads[i] = s.numpy()[0] * 2
assert_np_equal(allgrads, expected_grads, tol=10 * tol)
tape.zero()
def test_scalar_multiplication_rightmul(test, device, dtype, register_kernels=False):
np.random.seed(123)
tol = {
np.float16: 5.0e-3,
np.float32: 1.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
vec2 = wp.types.vector(length=2, dtype=wptype)
vec3 = wp.types.vector(length=3, dtype=wptype)
vec4 = wp.types.vector(length=4, dtype=wptype)
vec5 = wp.types.vector(length=5, dtype=wptype)
def check_rightmul(
s: wp.array(dtype=wptype),
v2: wp.array(dtype=vec2),
v3: wp.array(dtype=vec3),
v4: wp.array(dtype=vec4),
v5: wp.array(dtype=vec5),
v20: wp.array(dtype=wptype),
v21: wp.array(dtype=wptype),
v30: wp.array(dtype=wptype),
v31: wp.array(dtype=wptype),
v32: wp.array(dtype=wptype),
v40: wp.array(dtype=wptype),
v41: wp.array(dtype=wptype),
v42: wp.array(dtype=wptype),
v43: wp.array(dtype=wptype),
v50: wp.array(dtype=wptype),
v51: wp.array(dtype=wptype),
v52: wp.array(dtype=wptype),
v53: wp.array(dtype=wptype),
v54: wp.array(dtype=wptype),
):
v2result = v2[0] * s[0]
v3result = v3[0] * s[0]
v4result = v4[0] * s[0]
v5result = v5[0] * s[0]
# multiply outputs by 2 so we've got something to backpropagate:
v20[0] = wptype(2) * v2result[0]
v21[0] = wptype(2) * v2result[1]
v30[0] = wptype(2) * v3result[0]
v31[0] = wptype(2) * v3result[1]
v32[0] = wptype(2) * v3result[2]
v40[0] = wptype(2) * v4result[0]
v41[0] = wptype(2) * v4result[1]
v42[0] = wptype(2) * v4result[2]
v43[0] = wptype(2) * v4result[3]
v50[0] = wptype(2) * v5result[0]
v51[0] = wptype(2) * v5result[1]
v52[0] = wptype(2) * v5result[2]
v53[0] = wptype(2) * v5result[3]
v54[0] = wptype(2) * v5result[4]
kernel = getkernel(check_rightmul, suffix=dtype.__name__)
if register_kernels:
return
s = wp.array(randvals([1], dtype), requires_grad=True, device=device)
v2 = wp.array(randvals((1, 2), dtype), dtype=vec2, requires_grad=True, device=device)
v3 = wp.array(randvals((1, 3), dtype), dtype=vec3, requires_grad=True, device=device)
v4 = wp.array(randvals((1, 4), dtype), dtype=vec4, requires_grad=True, device=device)
v5 = wp.array(randvals((1, 5), dtype), dtype=vec5, requires_grad=True, device=device)
v20 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v21 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v30 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v31 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v32 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v40 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v41 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v42 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v43 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v50 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v51 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v52 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v53 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v54 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
s,
v2,
v3,
v4,
v5,
],
outputs=[v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54],
device=device,
)
assert_np_equal(v20.numpy()[0], 2 * s.numpy()[0] * v2.numpy()[0, 0], tol=tol)
assert_np_equal(v21.numpy()[0], 2 * s.numpy()[0] * v2.numpy()[0, 1], tol=tol)
assert_np_equal(v30.numpy()[0], 2 * s.numpy()[0] * v3.numpy()[0, 0], tol=10 * tol)
assert_np_equal(v31.numpy()[0], 2 * s.numpy()[0] * v3.numpy()[0, 1], tol=10 * tol)
assert_np_equal(v32.numpy()[0], 2 * s.numpy()[0] * v3.numpy()[0, 2], tol=10 * tol)
assert_np_equal(v40.numpy()[0], 2 * s.numpy()[0] * v4.numpy()[0, 0], tol=10 * tol)
assert_np_equal(v41.numpy()[0], 2 * s.numpy()[0] * v4.numpy()[0, 1], tol=10 * tol)
assert_np_equal(v42.numpy()[0], 2 * s.numpy()[0] * v4.numpy()[0, 2], tol=10 * tol)
assert_np_equal(v43.numpy()[0], 2 * s.numpy()[0] * v4.numpy()[0, 3], tol=10 * tol)
assert_np_equal(v50.numpy()[0], 2 * s.numpy()[0] * v5.numpy()[0, 0], tol=10 * tol)
assert_np_equal(v51.numpy()[0], 2 * s.numpy()[0] * v5.numpy()[0, 1], tol=10 * tol)
assert_np_equal(v52.numpy()[0], 2 * s.numpy()[0] * v5.numpy()[0, 2], tol=10 * tol)
assert_np_equal(v53.numpy()[0], 2 * s.numpy()[0] * v5.numpy()[0, 3], tol=10 * tol)
assert_np_equal(v54.numpy()[0], 2 * s.numpy()[0] * v5.numpy()[0, 4], tol=10 * tol)
incmps = np.concatenate([v.numpy()[0] for v in [v2, v3, v4, v5]])
if dtype in np_float_types:
for i, l in enumerate([v20, v21, v30, v31, v32, v40, v41, v42, v43]):
tape.backward(loss=l)
sgrad = tape.gradients[s].numpy()[0]
assert_np_equal(sgrad, 2 * incmps[i], tol=10 * tol)
allgrads = np.concatenate([tape.gradients[v].numpy()[0] for v in [v2, v3, v4]])
expected_grads = np.zeros_like(allgrads)
expected_grads[i] = s.numpy()[0] * 2
assert_np_equal(allgrads, expected_grads, tol=10 * tol)
tape.zero()
def test_cw_multiplication(test, device, dtype, register_kernels=False):
np.random.seed(123)
tol = {
np.float16: 5.0e-3,
np.float32: 1.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
vec2 = wp.types.vector(length=2, dtype=wptype)
vec3 = wp.types.vector(length=3, dtype=wptype)
vec4 = wp.types.vector(length=4, dtype=wptype)
vec5 = wp.types.vector(length=5, dtype=wptype)
def check_cw_mul(
s2: wp.array(dtype=vec2),
s3: wp.array(dtype=vec3),
s4: wp.array(dtype=vec4),
s5: wp.array(dtype=vec5),
v2: wp.array(dtype=vec2),
v3: wp.array(dtype=vec3),
v4: wp.array(dtype=vec4),
v5: wp.array(dtype=vec5),
v20: wp.array(dtype=wptype),
v21: wp.array(dtype=wptype),
v30: wp.array(dtype=wptype),
v31: wp.array(dtype=wptype),
v32: wp.array(dtype=wptype),
v40: wp.array(dtype=wptype),
v41: wp.array(dtype=wptype),
v42: wp.array(dtype=wptype),
v43: wp.array(dtype=wptype),
v50: wp.array(dtype=wptype),
v51: wp.array(dtype=wptype),
v52: wp.array(dtype=wptype),
v53: wp.array(dtype=wptype),
v54: wp.array(dtype=wptype),
):
v2result = wp.cw_mul(s2[0], v2[0])
v3result = wp.cw_mul(s3[0], v3[0])
v4result = wp.cw_mul(s4[0], v4[0])
v5result = wp.cw_mul(s5[0], v5[0])
v20[0] = wptype(2) * v2result[0]
v21[0] = wptype(2) * v2result[1]
v30[0] = wptype(2) * v3result[0]
v31[0] = wptype(2) * v3result[1]
v32[0] = wptype(2) * v3result[2]
v40[0] = wptype(2) * v4result[0]
v41[0] = wptype(2) * v4result[1]
v42[0] = wptype(2) * v4result[2]
v43[0] = wptype(2) * v4result[3]
v50[0] = wptype(2) * v5result[0]
v51[0] = wptype(2) * v5result[1]
v52[0] = wptype(2) * v5result[2]
v53[0] = wptype(2) * v5result[3]
v54[0] = wptype(2) * v5result[4]
kernel = getkernel(check_cw_mul, suffix=dtype.__name__)
if register_kernels:
return
s2 = wp.array(randvals((1, 2), dtype), dtype=vec2, requires_grad=True, device=device)
s3 = wp.array(randvals((1, 3), dtype), dtype=vec3, requires_grad=True, device=device)
s4 = wp.array(randvals((1, 4), dtype), dtype=vec4, requires_grad=True, device=device)
s5 = wp.array(randvals((1, 5), dtype), dtype=vec5, requires_grad=True, device=device)
v2 = wp.array(randvals((1, 2), dtype), dtype=vec2, requires_grad=True, device=device)
v3 = wp.array(randvals((1, 3), dtype), dtype=vec3, requires_grad=True, device=device)
v4 = wp.array(randvals((1, 4), dtype), dtype=vec4, requires_grad=True, device=device)
v5 = wp.array(randvals((1, 5), dtype), dtype=vec5, requires_grad=True, device=device)
v20 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v21 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v30 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v31 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v32 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v40 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v41 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v42 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v43 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v50 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v51 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v52 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v53 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v54 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
s2,
s3,
s4,
s5,
v2,
v3,
v4,
v5,
],
outputs=[v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54],
device=device,
)
assert_np_equal(v20.numpy()[0], 2 * s2.numpy()[0, 0] * v2.numpy()[0, 0], tol=10 * tol)
assert_np_equal(v21.numpy()[0], 2 * s2.numpy()[0, 1] * v2.numpy()[0, 1], tol=10 * tol)
assert_np_equal(v30.numpy()[0], 2 * s3.numpy()[0, 0] * v3.numpy()[0, 0], tol=10 * tol)
assert_np_equal(v31.numpy()[0], 2 * s3.numpy()[0, 1] * v3.numpy()[0, 1], tol=10 * tol)
assert_np_equal(v32.numpy()[0], 2 * s3.numpy()[0, 2] * v3.numpy()[0, 2], tol=10 * tol)
assert_np_equal(v40.numpy()[0], 2 * s4.numpy()[0, 0] * v4.numpy()[0, 0], tol=10 * tol)
assert_np_equal(v41.numpy()[0], 2 * s4.numpy()[0, 1] * v4.numpy()[0, 1], tol=10 * tol)
assert_np_equal(v42.numpy()[0], 2 * s4.numpy()[0, 2] * v4.numpy()[0, 2], tol=10 * tol)
assert_np_equal(v43.numpy()[0], 2 * s4.numpy()[0, 3] * v4.numpy()[0, 3], tol=10 * tol)
assert_np_equal(v50.numpy()[0], 2 * s5.numpy()[0, 0] * v5.numpy()[0, 0], tol=10 * tol)
assert_np_equal(v51.numpy()[0], 2 * s5.numpy()[0, 1] * v5.numpy()[0, 1], tol=10 * tol)
assert_np_equal(v52.numpy()[0], 2 * s5.numpy()[0, 2] * v5.numpy()[0, 2], tol=10 * tol)
assert_np_equal(v53.numpy()[0], 2 * s5.numpy()[0, 3] * v5.numpy()[0, 3], tol=10 * tol)
assert_np_equal(v54.numpy()[0], 2 * s5.numpy()[0, 4] * v5.numpy()[0, 4], tol=10 * tol)
incmps = np.concatenate([v.numpy()[0] for v in [v2, v3, v4, v5]])
scmps = np.concatenate([v.numpy()[0] for v in [s2, s3, s4, s5]])
if dtype in np_float_types:
for i, l in enumerate([v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54]):
tape.backward(loss=l)
sgrads = np.concatenate([tape.gradients[v].numpy()[0] for v in [s2, s3, s4, s5]])
expected_grads = np.zeros_like(sgrads)
expected_grads[i] = incmps[i] * 2
assert_np_equal(sgrads, expected_grads, tol=10 * tol)
allgrads = np.concatenate([tape.gradients[v].numpy()[0] for v in [v2, v3, v4, v5]])
expected_grads = np.zeros_like(allgrads)
expected_grads[i] = scmps[i] * 2
assert_np_equal(allgrads, expected_grads, tol=10 * tol)
tape.zero()
def test_scalar_division(test, device, dtype, register_kernels=False):
np.random.seed(123)
tol = {
np.float16: 5.0e-3,
np.float32: 1.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
vec2 = wp.types.vector(length=2, dtype=wptype)
vec3 = wp.types.vector(length=3, dtype=wptype)
vec4 = wp.types.vector(length=4, dtype=wptype)
vec5 = wp.types.vector(length=5, dtype=wptype)
def check_div(
s: wp.array(dtype=wptype),
v2: wp.array(dtype=vec2),
v3: wp.array(dtype=vec3),
v4: wp.array(dtype=vec4),
v5: wp.array(dtype=vec5),
v20: wp.array(dtype=wptype),
v21: wp.array(dtype=wptype),
v30: wp.array(dtype=wptype),
v31: wp.array(dtype=wptype),
v32: wp.array(dtype=wptype),
v40: wp.array(dtype=wptype),
v41: wp.array(dtype=wptype),
v42: wp.array(dtype=wptype),
v43: wp.array(dtype=wptype),
v50: wp.array(dtype=wptype),
v51: wp.array(dtype=wptype),
v52: wp.array(dtype=wptype),
v53: wp.array(dtype=wptype),
v54: wp.array(dtype=wptype),
):
v2result = v2[0] / s[0]
v3result = v3[0] / s[0]
v4result = v4[0] / s[0]
v5result = v5[0] / s[0]
v20[0] = wptype(2) * v2result[0]
v21[0] = wptype(2) * v2result[1]
v30[0] = wptype(2) * v3result[0]
v31[0] = wptype(2) * v3result[1]
v32[0] = wptype(2) * v3result[2]
v40[0] = wptype(2) * v4result[0]
v41[0] = wptype(2) * v4result[1]
v42[0] = wptype(2) * v4result[2]
v43[0] = wptype(2) * v4result[3]
v50[0] = wptype(2) * v5result[0]
v51[0] = wptype(2) * v5result[1]
v52[0] = wptype(2) * v5result[2]
v53[0] = wptype(2) * v5result[3]
v54[0] = wptype(2) * v5result[4]
kernel = getkernel(check_div, suffix=dtype.__name__)
if register_kernels:
return
s = wp.array(randvals([1], dtype), requires_grad=True, device=device)
v2 = wp.array(randvals((1, 2), dtype), dtype=vec2, requires_grad=True, device=device)
v3 = wp.array(randvals((1, 3), dtype), dtype=vec3, requires_grad=True, device=device)
v4 = wp.array(randvals((1, 4), dtype), dtype=vec4, requires_grad=True, device=device)
v5 = wp.array(randvals((1, 5), dtype), dtype=vec5, requires_grad=True, device=device)
v20 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v21 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v30 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v31 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v32 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v40 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v41 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v42 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v43 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v50 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v51 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v52 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v53 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v54 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
s,
v2,
v3,
v4,
v5,
],
outputs=[v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54],
device=device,
)
if dtype in np_int_types:
assert_np_equal(v20.numpy()[0], 2 * (v2.numpy()[0, 0] // (s.numpy()[0])), tol=tol)
assert_np_equal(v21.numpy()[0], 2 * (v2.numpy()[0, 1] // (s.numpy()[0])), tol=tol)
assert_np_equal(v30.numpy()[0], 2 * (v3.numpy()[0, 0] // (s.numpy()[0])), tol=10 * tol)
assert_np_equal(v31.numpy()[0], 2 * (v3.numpy()[0, 1] // (s.numpy()[0])), tol=10 * tol)
assert_np_equal(v32.numpy()[0], 2 * (v3.numpy()[0, 2] // (s.numpy()[0])), tol=10 * tol)
assert_np_equal(v40.numpy()[0], 2 * (v4.numpy()[0, 0] // (s.numpy()[0])), tol=10 * tol)
assert_np_equal(v41.numpy()[0], 2 * (v4.numpy()[0, 1] // (s.numpy()[0])), tol=10 * tol)
assert_np_equal(v42.numpy()[0], 2 * (v4.numpy()[0, 2] // (s.numpy()[0])), tol=10 * tol)
assert_np_equal(v43.numpy()[0], 2 * (v4.numpy()[0, 3] // (s.numpy()[0])), tol=10 * tol)
assert_np_equal(v50.numpy()[0], 2 * (v5.numpy()[0, 0] // (s.numpy()[0])), tol=10 * tol)
assert_np_equal(v51.numpy()[0], 2 * (v5.numpy()[0, 1] // (s.numpy()[0])), tol=10 * tol)
assert_np_equal(v52.numpy()[0], 2 * (v5.numpy()[0, 2] // (s.numpy()[0])), tol=10 * tol)
assert_np_equal(v53.numpy()[0], 2 * (v5.numpy()[0, 3] // (s.numpy()[0])), tol=10 * tol)
assert_np_equal(v54.numpy()[0], 2 * (v5.numpy()[0, 4] // (s.numpy()[0])), tol=10 * tol)
else:
assert_np_equal(v20.numpy()[0], 2 * v2.numpy()[0, 0] / (s.numpy()[0]), tol=tol)
assert_np_equal(v21.numpy()[0], 2 * v2.numpy()[0, 1] / (s.numpy()[0]), tol=tol)
assert_np_equal(v30.numpy()[0], 2 * v3.numpy()[0, 0] / (s.numpy()[0]), tol=10 * tol)
assert_np_equal(v31.numpy()[0], 2 * v3.numpy()[0, 1] / (s.numpy()[0]), tol=10 * tol)
assert_np_equal(v32.numpy()[0], 2 * v3.numpy()[0, 2] / (s.numpy()[0]), tol=10 * tol)
assert_np_equal(v40.numpy()[0], 2 * v4.numpy()[0, 0] / (s.numpy()[0]), tol=10 * tol)
assert_np_equal(v41.numpy()[0], 2 * v4.numpy()[0, 1] / (s.numpy()[0]), tol=10 * tol)
assert_np_equal(v42.numpy()[0], 2 * v4.numpy()[0, 2] / (s.numpy()[0]), tol=10 * tol)
assert_np_equal(v43.numpy()[0], 2 * v4.numpy()[0, 3] / (s.numpy()[0]), tol=10 * tol)
assert_np_equal(v50.numpy()[0], 2 * v5.numpy()[0, 0] / (s.numpy()[0]), tol=10 * tol)
assert_np_equal(v51.numpy()[0], 2 * v5.numpy()[0, 1] / (s.numpy()[0]), tol=10 * tol)
assert_np_equal(v52.numpy()[0], 2 * v5.numpy()[0, 2] / (s.numpy()[0]), tol=10 * tol)
assert_np_equal(v53.numpy()[0], 2 * v5.numpy()[0, 3] / (s.numpy()[0]), tol=10 * tol)
assert_np_equal(v54.numpy()[0], 2 * v5.numpy()[0, 4] / (s.numpy()[0]), tol=10 * tol)
incmps = np.concatenate([v.numpy()[0] for v in [v2, v3, v4, v5]])
if dtype in np_float_types:
for i, l in enumerate([v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54]):
tape.backward(loss=l)
sgrad = tape.gradients[s].numpy()[0]
# d/ds v/s = -v/s^2
assert_np_equal(sgrad, -2 * incmps[i] / (s.numpy()[0] * s.numpy()[0]), tol=10 * tol)
allgrads = np.concatenate([tape.gradients[v].numpy()[0] for v in [v2, v3, v4, v5]])
expected_grads = np.zeros_like(allgrads)
expected_grads[i] = 2 / s.numpy()[0]
# d/dv v/s = 1/s
assert_np_equal(allgrads, expected_grads, tol=tol)
tape.zero()
def test_cw_division(test, device, dtype, register_kernels=False):
np.random.seed(123)
tol = {
np.float16: 1.0e-2,
np.float32: 1.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
vec2 = wp.types.vector(length=2, dtype=wptype)
vec3 = wp.types.vector(length=3, dtype=wptype)
vec4 = wp.types.vector(length=4, dtype=wptype)
vec5 = wp.types.vector(length=5, dtype=wptype)
def check_cw_div(
s2: wp.array(dtype=vec2),
s3: wp.array(dtype=vec3),
s4: wp.array(dtype=vec4),
s5: wp.array(dtype=vec5),
v2: wp.array(dtype=vec2),
v3: wp.array(dtype=vec3),
v4: wp.array(dtype=vec4),
v5: wp.array(dtype=vec5),
v20: wp.array(dtype=wptype),
v21: wp.array(dtype=wptype),
v30: wp.array(dtype=wptype),
v31: wp.array(dtype=wptype),
v32: wp.array(dtype=wptype),
v40: wp.array(dtype=wptype),
v41: wp.array(dtype=wptype),
v42: wp.array(dtype=wptype),
v43: wp.array(dtype=wptype),
v50: wp.array(dtype=wptype),
v51: wp.array(dtype=wptype),
v52: wp.array(dtype=wptype),
v53: wp.array(dtype=wptype),
v54: wp.array(dtype=wptype),
):
v2result = wp.cw_div(v2[0], s2[0])
v3result = wp.cw_div(v3[0], s3[0])
v4result = wp.cw_div(v4[0], s4[0])
v5result = wp.cw_div(v5[0], s5[0])
v20[0] = wptype(2) * v2result[0]
v21[0] = wptype(2) * v2result[1]
v30[0] = wptype(2) * v3result[0]
v31[0] = wptype(2) * v3result[1]
v32[0] = wptype(2) * v3result[2]
v40[0] = wptype(2) * v4result[0]
v41[0] = wptype(2) * v4result[1]
v42[0] = wptype(2) * v4result[2]
v43[0] = wptype(2) * v4result[3]
v50[0] = wptype(2) * v5result[0]
v51[0] = wptype(2) * v5result[1]
v52[0] = wptype(2) * v5result[2]
v53[0] = wptype(2) * v5result[3]
v54[0] = wptype(2) * v5result[4]
kernel = getkernel(check_cw_div, suffix=dtype.__name__)
if register_kernels:
return
s2 = wp.array(randvals((1, 2), dtype), dtype=vec2, requires_grad=True, device=device)
s3 = wp.array(randvals((1, 3), dtype), dtype=vec3, requires_grad=True, device=device)
s4 = wp.array(randvals((1, 4), dtype), dtype=vec4, requires_grad=True, device=device)
s5 = wp.array(randvals((1, 5), dtype), dtype=vec5, requires_grad=True, device=device)
v2 = wp.array(randvals((1, 2), dtype), dtype=vec2, requires_grad=True, device=device)
v3 = wp.array(randvals((1, 3), dtype), dtype=vec3, requires_grad=True, device=device)
v4 = wp.array(randvals((1, 4), dtype), dtype=vec4, requires_grad=True, device=device)
v5 = wp.array(randvals((1, 5), dtype), dtype=vec5, requires_grad=True, device=device)
v20 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v21 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v30 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v31 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v32 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v40 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v41 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v42 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v43 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v50 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v51 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v52 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v53 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v54 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
s2,
s3,
s4,
s5,
v2,
v3,
v4,
v5,
],
outputs=[v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54],
device=device,
)
if dtype in np_int_types:
assert_np_equal(v20.numpy()[0], 2 * (v2.numpy()[0, 0] // s2.numpy()[0, 0]), tol=tol)
assert_np_equal(v21.numpy()[0], 2 * (v2.numpy()[0, 1] // s2.numpy()[0, 1]), tol=tol)
assert_np_equal(v30.numpy()[0], 2 * (v3.numpy()[0, 0] // s3.numpy()[0, 0]), tol=tol)
assert_np_equal(v31.numpy()[0], 2 * (v3.numpy()[0, 1] // s3.numpy()[0, 1]), tol=tol)
assert_np_equal(v32.numpy()[0], 2 * (v3.numpy()[0, 2] // s3.numpy()[0, 2]), tol=tol)
assert_np_equal(v40.numpy()[0], 2 * (v4.numpy()[0, 0] // s4.numpy()[0, 0]), tol=tol)
assert_np_equal(v41.numpy()[0], 2 * (v4.numpy()[0, 1] // s4.numpy()[0, 1]), tol=tol)
assert_np_equal(v42.numpy()[0], 2 * (v4.numpy()[0, 2] // s4.numpy()[0, 2]), tol=tol)
assert_np_equal(v43.numpy()[0], 2 * (v4.numpy()[0, 3] // s4.numpy()[0, 3]), tol=tol)
assert_np_equal(v50.numpy()[0], 2 * (v5.numpy()[0, 0] // s5.numpy()[0, 0]), tol=tol)
assert_np_equal(v51.numpy()[0], 2 * (v5.numpy()[0, 1] // s5.numpy()[0, 1]), tol=tol)
assert_np_equal(v52.numpy()[0], 2 * (v5.numpy()[0, 2] // s5.numpy()[0, 2]), tol=tol)
assert_np_equal(v53.numpy()[0], 2 * (v5.numpy()[0, 3] // s5.numpy()[0, 3]), tol=tol)
assert_np_equal(v54.numpy()[0], 2 * (v5.numpy()[0, 4] // s5.numpy()[0, 4]), tol=tol)
else:
assert_np_equal(v20.numpy()[0], 2 * v2.numpy()[0, 0] / s2.numpy()[0, 0], tol=tol)
assert_np_equal(v21.numpy()[0], 2 * v2.numpy()[0, 1] / s2.numpy()[0, 1], tol=tol)
assert_np_equal(v30.numpy()[0], 2 * v3.numpy()[0, 0] / s3.numpy()[0, 0], tol=tol)
assert_np_equal(v31.numpy()[0], 2 * v3.numpy()[0, 1] / s3.numpy()[0, 1], tol=tol)
assert_np_equal(v32.numpy()[0], 2 * v3.numpy()[0, 2] / s3.numpy()[0, 2], tol=tol)
assert_np_equal(v40.numpy()[0], 2 * v4.numpy()[0, 0] / s4.numpy()[0, 0], tol=tol)
assert_np_equal(v41.numpy()[0], 2 * v4.numpy()[0, 1] / s4.numpy()[0, 1], tol=tol)
assert_np_equal(v42.numpy()[0], 2 * v4.numpy()[0, 2] / s4.numpy()[0, 2], tol=tol)
assert_np_equal(v43.numpy()[0], 2 * v4.numpy()[0, 3] / s4.numpy()[0, 3], tol=tol)
assert_np_equal(v50.numpy()[0], 2 * v5.numpy()[0, 0] / s5.numpy()[0, 0], tol=tol)
assert_np_equal(v51.numpy()[0], 2 * v5.numpy()[0, 1] / s5.numpy()[0, 1], tol=tol)
assert_np_equal(v52.numpy()[0], 2 * v5.numpy()[0, 2] / s5.numpy()[0, 2], tol=tol)
assert_np_equal(v53.numpy()[0], 2 * v5.numpy()[0, 3] / s5.numpy()[0, 3], tol=tol)
assert_np_equal(v54.numpy()[0], 2 * v5.numpy()[0, 4] / s5.numpy()[0, 4], tol=tol)
if dtype in np_float_types:
incmps = np.concatenate([v.numpy()[0] for v in [v2, v3, v4, v5]])
scmps = np.concatenate([v.numpy()[0] for v in [s2, s3, s4, s5]])
for i, l in enumerate([v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54]):
tape.backward(loss=l)
sgrads = np.concatenate([tape.gradients[v].numpy()[0] for v in [s2, s3, s4, s5]])
expected_grads = np.zeros_like(sgrads)
# d/ds v/s = -v/s^2
expected_grads[i] = -incmps[i] * 2 / (scmps[i] * scmps[i])
assert_np_equal(sgrads, expected_grads, tol=20 * tol)
allgrads = np.concatenate([tape.gradients[v].numpy()[0] for v in [v2, v3, v4, v5]])
expected_grads = np.zeros_like(allgrads)
# d/dv v/s = 1/s
expected_grads[i] = 2 / scmps[i]
assert_np_equal(allgrads, expected_grads, tol=tol)
tape.zero()
def test_addition(test, device, dtype, register_kernels=False):
np.random.seed(123)
tol = {
np.float16: 5.0e-3,
np.float32: 1.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
vec2 = wp.types.vector(length=2, dtype=wptype)
vec3 = wp.types.vector(length=3, dtype=wptype)
vec4 = wp.types.vector(length=4, dtype=wptype)
vec5 = wp.types.vector(length=5, dtype=wptype)
def check_add(
s2: wp.array(dtype=vec2),
s3: wp.array(dtype=vec3),
s4: wp.array(dtype=vec4),
s5: wp.array(dtype=vec5),
v2: wp.array(dtype=vec2),
v3: wp.array(dtype=vec3),
v4: wp.array(dtype=vec4),
v5: wp.array(dtype=vec5),
v20: wp.array(dtype=wptype),
v21: wp.array(dtype=wptype),
v30: wp.array(dtype=wptype),
v31: wp.array(dtype=wptype),
v32: wp.array(dtype=wptype),
v40: wp.array(dtype=wptype),
v41: wp.array(dtype=wptype),
v42: wp.array(dtype=wptype),
v43: wp.array(dtype=wptype),
v50: wp.array(dtype=wptype),
v51: wp.array(dtype=wptype),
v52: wp.array(dtype=wptype),
v53: wp.array(dtype=wptype),
v54: wp.array(dtype=wptype),
):
v2result = v2[0] + s2[0]
v3result = v3[0] + s3[0]
v4result = v4[0] + s4[0]
v5result = v5[0] + s5[0]
v20[0] = wptype(2) * v2result[0]
v21[0] = wptype(2) * v2result[1]
v30[0] = wptype(2) * v3result[0]
v31[0] = wptype(2) * v3result[1]
v32[0] = wptype(2) * v3result[2]
v40[0] = wptype(2) * v4result[0]
v41[0] = wptype(2) * v4result[1]
v42[0] = wptype(2) * v4result[2]
v43[0] = wptype(2) * v4result[3]
v50[0] = wptype(2) * v5result[0]
v51[0] = wptype(2) * v5result[1]
v52[0] = wptype(2) * v5result[2]
v53[0] = wptype(2) * v5result[3]
v54[0] = wptype(2) * v5result[4]
kernel = getkernel(check_add, suffix=dtype.__name__)
if register_kernels:
return
s2 = wp.array(randvals((1, 2), dtype), dtype=vec2, requires_grad=True, device=device)
s3 = wp.array(randvals((1, 3), dtype), dtype=vec3, requires_grad=True, device=device)
s4 = wp.array(randvals((1, 4), dtype), dtype=vec4, requires_grad=True, device=device)
s5 = wp.array(randvals((1, 5), dtype), dtype=vec5, requires_grad=True, device=device)
v2 = wp.array(randvals((1, 2), dtype), dtype=vec2, requires_grad=True, device=device)
v3 = wp.array(randvals((1, 3), dtype), dtype=vec3, requires_grad=True, device=device)
v4 = wp.array(randvals((1, 4), dtype), dtype=vec4, requires_grad=True, device=device)
v5 = wp.array(randvals((1, 5), dtype), dtype=vec5, requires_grad=True, device=device)
v20 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v21 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v30 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v31 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v32 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v40 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v41 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v42 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v43 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v50 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v51 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v52 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v53 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v54 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
s2,
s3,
s4,
s5,
v2,
v3,
v4,
v5,
],
outputs=[v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54],
device=device,
)
assert_np_equal(v20.numpy()[0], 2 * (v2.numpy()[0, 0] + s2.numpy()[0, 0]), tol=tol)
assert_np_equal(v21.numpy()[0], 2 * (v2.numpy()[0, 1] + s2.numpy()[0, 1]), tol=tol)
assert_np_equal(v30.numpy()[0], 2 * (v3.numpy()[0, 0] + s3.numpy()[0, 0]), tol=tol)
assert_np_equal(v31.numpy()[0], 2 * (v3.numpy()[0, 1] + s3.numpy()[0, 1]), tol=tol)
assert_np_equal(v32.numpy()[0], 2 * (v3.numpy()[0, 2] + s3.numpy()[0, 2]), tol=tol)
assert_np_equal(v40.numpy()[0], 2 * (v4.numpy()[0, 0] + s4.numpy()[0, 0]), tol=tol)
assert_np_equal(v41.numpy()[0], 2 * (v4.numpy()[0, 1] + s4.numpy()[0, 1]), tol=tol)
assert_np_equal(v42.numpy()[0], 2 * (v4.numpy()[0, 2] + s4.numpy()[0, 2]), tol=tol)
assert_np_equal(v43.numpy()[0], 2 * (v4.numpy()[0, 3] + s4.numpy()[0, 3]), tol=tol)
assert_np_equal(v50.numpy()[0], 2 * (v5.numpy()[0, 0] + s5.numpy()[0, 0]), tol=tol)
assert_np_equal(v51.numpy()[0], 2 * (v5.numpy()[0, 1] + s5.numpy()[0, 1]), tol=tol)
assert_np_equal(v52.numpy()[0], 2 * (v5.numpy()[0, 2] + s5.numpy()[0, 2]), tol=tol)
assert_np_equal(v53.numpy()[0], 2 * (v5.numpy()[0, 3] + s5.numpy()[0, 3]), tol=tol)
assert_np_equal(v54.numpy()[0], 2 * (v5.numpy()[0, 4] + s5.numpy()[0, 4]), tol=2 * tol)
if dtype in np_float_types:
for i, l in enumerate([v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54]):
tape.backward(loss=l)
sgrads = np.concatenate([tape.gradients[v].numpy()[0] for v in [s2, s3, s4, s5]])
expected_grads = np.zeros_like(sgrads)
expected_grads[i] = 2
assert_np_equal(sgrads, expected_grads, tol=10 * tol)
allgrads = np.concatenate([tape.gradients[v].numpy()[0] for v in [v2, v3, v4, v5]])
assert_np_equal(allgrads, expected_grads, tol=tol)
tape.zero()
def test_subtraction_unsigned(test, device, dtype, register_kernels=False):
np.random.seed(123)
tol = {
np.float16: 1.0e-3,
np.float32: 1.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
vec2 = wp.types.vector(length=2, dtype=wptype)
vec3 = wp.types.vector(length=3, dtype=wptype)
vec4 = wp.types.vector(length=4, dtype=wptype)
vec5 = wp.types.vector(length=5, dtype=wptype)
def check_subtraction_unsigned():
wp.expect_eq(vec2(wptype(3), wptype(4)) - vec2(wptype(1), wptype(2)), vec2(wptype(2), wptype(2)))
wp.expect_eq(
vec3(
wptype(3),
wptype(4),
wptype(4),
)
- vec3(wptype(1), wptype(2), wptype(3)),
vec3(wptype(2), wptype(2), wptype(1)),
)
wp.expect_eq(
vec4(
wptype(3),
wptype(4),
wptype(4),
wptype(5),
)
- vec4(wptype(1), wptype(2), wptype(3), wptype(4)),
vec4(wptype(2), wptype(2), wptype(1), wptype(1)),
)
wp.expect_eq(
vec5(
wptype(3),
wptype(4),
wptype(4),
wptype(5),
wptype(4),
)
- vec5(wptype(1), wptype(2), wptype(3), wptype(4), wptype(4)),
vec5(wptype(2), wptype(2), wptype(1), wptype(1), wptype(0)),
)
kernel = getkernel(check_subtraction_unsigned, suffix=dtype.__name__)
if register_kernels:
return
wp.launch(kernel, dim=1, inputs=[], outputs=[], device=device)
def test_subtraction(test, device, dtype, register_kernels=False):
np.random.seed(123)
tol = {
np.float16: 5.0e-3,
np.float32: 1.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
vec2 = wp.types.vector(length=2, dtype=wptype)
vec3 = wp.types.vector(length=3, dtype=wptype)
vec4 = wp.types.vector(length=4, dtype=wptype)
vec5 = wp.types.vector(length=5, dtype=wptype)
def check_subtraction(
s2: wp.array(dtype=vec2),
s3: wp.array(dtype=vec3),
s4: wp.array(dtype=vec4),
s5: wp.array(dtype=vec5),
v2: wp.array(dtype=vec2),
v3: wp.array(dtype=vec3),
v4: wp.array(dtype=vec4),
v5: wp.array(dtype=vec5),
v20: wp.array(dtype=wptype),
v21: wp.array(dtype=wptype),
v30: wp.array(dtype=wptype),
v31: wp.array(dtype=wptype),
v32: wp.array(dtype=wptype),
v40: wp.array(dtype=wptype),
v41: wp.array(dtype=wptype),
v42: wp.array(dtype=wptype),
v43: wp.array(dtype=wptype),
v50: wp.array(dtype=wptype),
v51: wp.array(dtype=wptype),
v52: wp.array(dtype=wptype),
v53: wp.array(dtype=wptype),
v54: wp.array(dtype=wptype),
):
v2result = v2[0] - s2[0]
v3result = v3[0] - s3[0]
v4result = v4[0] - s4[0]
v5result = v5[0] - s5[0]
# multiply outputs by 2 so there's something to backpropagate:
v20[0] = wptype(2) * v2result[0]
v21[0] = wptype(2) * v2result[1]
v30[0] = wptype(2) * v3result[0]
v31[0] = wptype(2) * v3result[1]
v32[0] = wptype(2) * v3result[2]
v40[0] = wptype(2) * v4result[0]
v41[0] = wptype(2) * v4result[1]
v42[0] = wptype(2) * v4result[2]
v43[0] = wptype(2) * v4result[3]
v50[0] = wptype(2) * v5result[0]
v51[0] = wptype(2) * v5result[1]
v52[0] = wptype(2) * v5result[2]
v53[0] = wptype(2) * v5result[3]
v54[0] = wptype(2) * v5result[4]
kernel = getkernel(check_subtraction, suffix=dtype.__name__)
if register_kernels:
return
s2 = wp.array(randvals((1, 2), dtype), dtype=vec2, requires_grad=True, device=device)
s3 = wp.array(randvals((1, 3), dtype), dtype=vec3, requires_grad=True, device=device)
s4 = wp.array(randvals((1, 4), dtype), dtype=vec4, requires_grad=True, device=device)
s5 = wp.array(randvals((1, 5), dtype), dtype=vec5, requires_grad=True, device=device)
v2 = wp.array(randvals((1, 2), dtype), dtype=vec2, requires_grad=True, device=device)
v3 = wp.array(randvals((1, 3), dtype), dtype=vec3, requires_grad=True, device=device)
v4 = wp.array(randvals((1, 4), dtype), dtype=vec4, requires_grad=True, device=device)
v5 = wp.array(randvals((1, 5), dtype), dtype=vec5, requires_grad=True, device=device)
v20 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v21 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v30 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v31 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v32 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v40 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v41 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v42 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v43 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v50 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v51 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v52 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v53 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
v54 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
s2,
s3,
s4,
s5,
v2,
v3,
v4,
v5,
],
outputs=[v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54],
device=device,
)
assert_np_equal(v20.numpy()[0], 2 * (v2.numpy()[0, 0] - s2.numpy()[0, 0]), tol=tol)
assert_np_equal(v21.numpy()[0], 2 * (v2.numpy()[0, 1] - s2.numpy()[0, 1]), tol=tol)
assert_np_equal(v30.numpy()[0], 2 * (v3.numpy()[0, 0] - s3.numpy()[0, 0]), tol=tol)
assert_np_equal(v31.numpy()[0], 2 * (v3.numpy()[0, 1] - s3.numpy()[0, 1]), tol=tol)
assert_np_equal(v32.numpy()[0], 2 * (v3.numpy()[0, 2] - s3.numpy()[0, 2]), tol=tol)
assert_np_equal(v40.numpy()[0], 2 * (v4.numpy()[0, 0] - s4.numpy()[0, 0]), tol=2 * tol)
assert_np_equal(v41.numpy()[0], 2 * (v4.numpy()[0, 1] - s4.numpy()[0, 1]), tol=2 * tol)
assert_np_equal(v42.numpy()[0], 2 * (v4.numpy()[0, 2] - s4.numpy()[0, 2]), tol=2 * tol)
assert_np_equal(v43.numpy()[0], 2 * (v4.numpy()[0, 3] - s4.numpy()[0, 3]), tol=2 * tol)
assert_np_equal(v50.numpy()[0], 2 * (v5.numpy()[0, 0] - s5.numpy()[0, 0]), tol=tol)
assert_np_equal(v51.numpy()[0], 2 * (v5.numpy()[0, 1] - s5.numpy()[0, 1]), tol=tol)
assert_np_equal(v52.numpy()[0], 2 * (v5.numpy()[0, 2] - s5.numpy()[0, 2]), tol=tol)
assert_np_equal(v53.numpy()[0], 2 * (v5.numpy()[0, 3] - s5.numpy()[0, 3]), tol=tol)
assert_np_equal(v54.numpy()[0], 2 * (v5.numpy()[0, 4] - s5.numpy()[0, 4]), tol=tol)
if dtype in np_float_types:
for i, l in enumerate([v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54]):
tape.backward(loss=l)
sgrads = np.concatenate([tape.gradients[v].numpy()[0] for v in [s2, s3, s4, s5]])
expected_grads = np.zeros_like(sgrads)
expected_grads[i] = -2
assert_np_equal(sgrads, expected_grads, tol=10 * tol)
allgrads = np.concatenate([tape.gradients[v].numpy()[0] for v in [v2, v3, v4, v5]])
expected_grads = np.zeros_like(allgrads)
# d/dv v/s = 1/s
expected_grads[i] = 2
assert_np_equal(allgrads, expected_grads, tol=tol)
tape.zero()
def test_dotproduct(test, device, dtype, register_kernels=False):
np.random.seed(123)
tol = {
np.float16: 1.0e-2,
np.float32: 1.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
vec2 = wp.types.vector(length=2, dtype=wptype)
vec3 = wp.types.vector(length=3, dtype=wptype)
vec4 = wp.types.vector(length=4, dtype=wptype)
vec5 = wp.types.vector(length=5, dtype=wptype)
def check_dot(
s2: wp.array(dtype=vec2),
s3: wp.array(dtype=vec3),
s4: wp.array(dtype=vec4),
s5: wp.array(dtype=vec5),
v2: wp.array(dtype=vec2),
v3: wp.array(dtype=vec3),
v4: wp.array(dtype=vec4),
v5: wp.array(dtype=vec5),
dot2: wp.array(dtype=wptype),
dot3: wp.array(dtype=wptype),
dot4: wp.array(dtype=wptype),
dot5: wp.array(dtype=wptype),
):
dot2[0] = wptype(2) * wp.dot(v2[0], s2[0])
dot3[0] = wptype(2) * wp.dot(v3[0], s3[0])
dot4[0] = wptype(2) * wp.dot(v4[0], s4[0])
dot5[0] = wptype(2) * wp.dot(v5[0], s5[0])
kernel = getkernel(check_dot, suffix=dtype.__name__)
if register_kernels:
return
s2 = wp.array(randvals((1, 2), dtype), dtype=vec2, requires_grad=True, device=device)
s3 = wp.array(randvals((1, 3), dtype), dtype=vec3, requires_grad=True, device=device)
s4 = wp.array(randvals((1, 4), dtype), dtype=vec4, requires_grad=True, device=device)
s5 = wp.array(randvals((1, 5), dtype), dtype=vec5, requires_grad=True, device=device)
v2 = wp.array(randvals((1, 2), dtype), dtype=vec2, requires_grad=True, device=device)
v3 = wp.array(randvals((1, 3), dtype), dtype=vec3, requires_grad=True, device=device)
v4 = wp.array(randvals((1, 4), dtype), dtype=vec4, requires_grad=True, device=device)
v5 = wp.array(randvals((1, 5), dtype), dtype=vec5, requires_grad=True, device=device)
dot2 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
dot3 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
dot4 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
dot5 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
s2,
s3,
s4,
s5,
v2,
v3,
v4,
v5,
],
outputs=[dot2, dot3, dot4, dot5],
device=device,
)
assert_np_equal(dot2.numpy()[0], 2.0 * (v2.numpy() * s2.numpy()).sum(), tol=10 * tol)
assert_np_equal(dot3.numpy()[0], 2.0 * (v3.numpy() * s3.numpy()).sum(), tol=10 * tol)
assert_np_equal(dot4.numpy()[0], 2.0 * (v4.numpy() * s4.numpy()).sum(), tol=10 * tol)
assert_np_equal(dot5.numpy()[0], 2.0 * (v5.numpy() * s5.numpy()).sum(), tol=10 * tol)
if dtype in np_float_types:
tape.backward(loss=dot2)
sgrads = tape.gradients[s2].numpy()[0]
expected_grads = 2.0 * v2.numpy()[0]
assert_np_equal(sgrads, expected_grads, tol=10 * tol)
vgrads = tape.gradients[v2].numpy()[0]
expected_grads = 2.0 * s2.numpy()[0]
assert_np_equal(vgrads, expected_grads, tol=tol)
tape.zero()
tape.backward(loss=dot3)
sgrads = tape.gradients[s3].numpy()[0]
expected_grads = 2.0 * v3.numpy()[0]
assert_np_equal(sgrads, expected_grads, tol=10 * tol)
vgrads = tape.gradients[v3].numpy()[0]
expected_grads = 2.0 * s3.numpy()[0]
assert_np_equal(vgrads, expected_grads, tol=tol)
tape.zero()
tape.backward(loss=dot4)
sgrads = tape.gradients[s4].numpy()[0]
expected_grads = 2.0 * v4.numpy()[0]
assert_np_equal(sgrads, expected_grads, tol=10 * tol)
vgrads = tape.gradients[v4].numpy()[0]
expected_grads = 2.0 * s4.numpy()[0]
assert_np_equal(vgrads, expected_grads, tol=tol)
tape.zero()
tape.backward(loss=dot5)
sgrads = tape.gradients[s5].numpy()[0]
expected_grads = 2.0 * v5.numpy()[0]
assert_np_equal(sgrads, expected_grads, tol=10 * tol)
vgrads = tape.gradients[v5].numpy()[0]
expected_grads = 2.0 * s5.numpy()[0]
assert_np_equal(vgrads, expected_grads, tol=10 * tol)
tape.zero()
def test_length(test, device, dtype, register_kernels=False):
np.random.seed(123)
tol = {
np.float16: 5.0e-3,
np.float32: 1.0e-6,
np.float64: 1.0e-7,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
vec2 = wp.types.vector(length=2, dtype=wptype)
vec3 = wp.types.vector(length=3, dtype=wptype)
vec4 = wp.types.vector(length=4, dtype=wptype)
vec5 = wp.types.vector(length=5, dtype=wptype)
def check_length(
v2: wp.array(dtype=vec2),
v3: wp.array(dtype=vec3),
v4: wp.array(dtype=vec4),
v5: wp.array(dtype=vec5),
l2: wp.array(dtype=wptype),
l3: wp.array(dtype=wptype),
l4: wp.array(dtype=wptype),
l5: wp.array(dtype=wptype),
l22: wp.array(dtype=wptype),
l23: wp.array(dtype=wptype),
l24: wp.array(dtype=wptype),
l25: wp.array(dtype=wptype),
):
l2[0] = wptype(2) * wp.length(v2[0])
l3[0] = wptype(2) * wp.length(v3[0])
l4[0] = wptype(2) * wp.length(v4[0])
l5[0] = wptype(2) * wp.length(v5[0])
l22[0] = wptype(2) * wp.length_sq(v2[0])
l23[0] = wptype(2) * wp.length_sq(v3[0])
l24[0] = wptype(2) * wp.length_sq(v4[0])
l25[0] = wptype(2) * wp.length_sq(v5[0])
kernel = getkernel(check_length, suffix=dtype.__name__)
if register_kernels:
return
v2 = wp.array(randvals((1, 2), dtype), dtype=vec2, requires_grad=True, device=device)
v3 = wp.array(randvals((1, 3), dtype), dtype=vec3, requires_grad=True, device=device)
v4 = wp.array(randvals((1, 4), dtype), dtype=vec4, requires_grad=True, device=device)
v5 = wp.array(randvals((1, 5), dtype), dtype=vec5, requires_grad=True, device=device)
l2 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
l3 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
l4 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
l5 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
l22 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
l23 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
l24 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
l25 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
v2,
v3,
v4,
v5,
],
outputs=[l2, l3, l4, l5, l22, l23, l24, l25],
device=device,
)
assert_np_equal(l2.numpy()[0], 2 * np.linalg.norm(v2.numpy()), tol=10 * tol)
assert_np_equal(l3.numpy()[0], 2 * np.linalg.norm(v3.numpy()), tol=10 * tol)
assert_np_equal(l4.numpy()[0], 2 * np.linalg.norm(v4.numpy()), tol=10 * tol)
assert_np_equal(l5.numpy()[0], 2 * np.linalg.norm(v5.numpy()), tol=10 * tol)
assert_np_equal(l22.numpy()[0], 2 * np.linalg.norm(v2.numpy()) ** 2, tol=10 * tol)
assert_np_equal(l23.numpy()[0], 2 * np.linalg.norm(v3.numpy()) ** 2, tol=10 * tol)
assert_np_equal(l24.numpy()[0], 2 * np.linalg.norm(v4.numpy()) ** 2, tol=10 * tol)
assert_np_equal(l25.numpy()[0], 2 * np.linalg.norm(v5.numpy()) ** 2, tol=10 * tol)
tape.backward(loss=l2)
grad = tape.gradients[v2].numpy()[0]
expected_grad = 2 * v2.numpy()[0] / np.linalg.norm(v2.numpy())
assert_np_equal(grad, expected_grad, tol=10 * tol)
tape.zero()
tape.backward(loss=l3)
grad = tape.gradients[v3].numpy()[0]
expected_grad = 2 * v3.numpy()[0] / np.linalg.norm(v3.numpy())
assert_np_equal(grad, expected_grad, tol=10 * tol)
tape.zero()
tape.backward(loss=l4)
grad = tape.gradients[v4].numpy()[0]
expected_grad = 2 * v4.numpy()[0] / np.linalg.norm(v4.numpy())
assert_np_equal(grad, expected_grad, tol=10 * tol)
tape.zero()
tape.backward(loss=l5)
grad = tape.gradients[v5].numpy()[0]
expected_grad = 2 * v5.numpy()[0] / np.linalg.norm(v5.numpy())
assert_np_equal(grad, expected_grad, tol=10 * tol)
tape.zero()
tape.backward(loss=l22)
grad = tape.gradients[v2].numpy()[0]
expected_grad = 4 * v2.numpy()[0]
assert_np_equal(grad, expected_grad, tol=10 * tol)
tape.zero()
tape.backward(loss=l23)
grad = tape.gradients[v3].numpy()[0]
expected_grad = 4 * v3.numpy()[0]
assert_np_equal(grad, expected_grad, tol=10 * tol)
tape.zero()
tape.backward(loss=l24)
grad = tape.gradients[v4].numpy()[0]
expected_grad = 4 * v4.numpy()[0]
assert_np_equal(grad, expected_grad, tol=10 * tol)
tape.zero()
tape.backward(loss=l25)
grad = tape.gradients[v5].numpy()[0]
expected_grad = 4 * v5.numpy()[0]
assert_np_equal(grad, expected_grad, tol=10 * tol)
tape.zero()
def test_normalize(test, device, dtype, register_kernels=False):
np.random.seed(123)
tol = {
np.float16: 5.0e-3,
np.float32: 1.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
vec2 = wp.types.vector(length=2, dtype=wptype)
vec3 = wp.types.vector(length=3, dtype=wptype)
vec4 = wp.types.vector(length=4, dtype=wptype)
vec5 = wp.types.vector(length=5, dtype=wptype)
def check_normalize(
v2: wp.array(dtype=vec2),
v3: wp.array(dtype=vec3),
v4: wp.array(dtype=vec4),
v5: wp.array(dtype=vec5),
n20: wp.array(dtype=wptype),
n21: wp.array(dtype=wptype),
n30: wp.array(dtype=wptype),
n31: wp.array(dtype=wptype),
n32: wp.array(dtype=wptype),
n40: wp.array(dtype=wptype),
n41: wp.array(dtype=wptype),
n42: wp.array(dtype=wptype),
n43: wp.array(dtype=wptype),
n50: wp.array(dtype=wptype),
n51: wp.array(dtype=wptype),
n52: wp.array(dtype=wptype),
n53: wp.array(dtype=wptype),
n54: wp.array(dtype=wptype),
):
n2 = wptype(2) * wp.normalize(v2[0])
n3 = wptype(2) * wp.normalize(v3[0])
n4 = wptype(2) * wp.normalize(v4[0])
n5 = wptype(2) * wp.normalize(v5[0])
n20[0] = n2[0]
n21[0] = n2[1]
n30[0] = n3[0]
n31[0] = n3[1]
n32[0] = n3[2]
n40[0] = n4[0]
n41[0] = n4[1]
n42[0] = n4[2]
n43[0] = n4[3]
n50[0] = n5[0]
n51[0] = n5[1]
n52[0] = n5[2]
n53[0] = n5[3]
n54[0] = n5[4]
def check_normalize_alt(
v2: wp.array(dtype=vec2),
v3: wp.array(dtype=vec3),
v4: wp.array(dtype=vec4),
v5: wp.array(dtype=vec5),
n20: wp.array(dtype=wptype),
n21: wp.array(dtype=wptype),
n30: wp.array(dtype=wptype),
n31: wp.array(dtype=wptype),
n32: wp.array(dtype=wptype),
n40: wp.array(dtype=wptype),
n41: wp.array(dtype=wptype),
n42: wp.array(dtype=wptype),
n43: wp.array(dtype=wptype),
n50: wp.array(dtype=wptype),
n51: wp.array(dtype=wptype),
n52: wp.array(dtype=wptype),
n53: wp.array(dtype=wptype),
n54: wp.array(dtype=wptype),
):
n2 = wptype(2) * v2[0] / wp.length(v2[0])
n3 = wptype(2) * v3[0] / wp.length(v3[0])
n4 = wptype(2) * v4[0] / wp.length(v4[0])
n5 = wptype(2) * v5[0] / wp.length(v5[0])
n20[0] = n2[0]
n21[0] = n2[1]
n30[0] = n3[0]
n31[0] = n3[1]
n32[0] = n3[2]
n40[0] = n4[0]
n41[0] = n4[1]
n42[0] = n4[2]
n43[0] = n4[3]
n50[0] = n5[0]
n51[0] = n5[1]
n52[0] = n5[2]
n53[0] = n5[3]
n54[0] = n5[4]
normalize_kernel = getkernel(check_normalize, suffix=dtype.__name__)
normalize_alt_kernel = getkernel(check_normalize_alt, suffix=dtype.__name__)
if register_kernels:
return
# I've already tested the things I'm using in check_normalize_alt, so I'll just
# make sure the two are giving the same results/gradients
v2 = wp.array(randvals((1, 2), dtype), dtype=vec2, requires_grad=True, device=device)
v3 = wp.array(randvals((1, 3), dtype), dtype=vec3, requires_grad=True, device=device)
v4 = wp.array(randvals((1, 4), dtype), dtype=vec4, requires_grad=True, device=device)
v5 = wp.array(randvals((1, 5), dtype), dtype=vec5, requires_grad=True, device=device)
n20 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n21 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n30 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n31 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n32 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n40 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n41 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n42 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n43 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n50 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n51 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n52 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n53 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n54 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n20_alt = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n21_alt = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n30_alt = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n31_alt = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n32_alt = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n40_alt = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n41_alt = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n42_alt = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n43_alt = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n50_alt = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n51_alt = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n52_alt = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n53_alt = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n54_alt = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
outputs0 = [
n20,
n21,
n30,
n31,
n32,
n40,
n41,
n42,
n43,
n50,
n51,
n52,
n53,
n54,
]
tape0 = wp.Tape()
with tape0:
wp.launch(
normalize_kernel,
dim=1,
inputs=[
v2,
v3,
v4,
v5,
],
outputs=outputs0,
device=device,
)
outputs1 = [
n20_alt,
n21_alt,
n30_alt,
n31_alt,
n32_alt,
n40_alt,
n41_alt,
n42_alt,
n43_alt,
n50_alt,
n51_alt,
n52_alt,
n53_alt,
n54_alt,
]
tape1 = wp.Tape()
with tape1:
wp.launch(
normalize_alt_kernel,
dim=1,
inputs=[
v2,
v3,
v4,
v5,
],
outputs=outputs1,
device=device,
)
for ncmp, ncmpalt in zip(outputs0, outputs1):
assert_np_equal(ncmp.numpy()[0], ncmpalt.numpy()[0], tol=10 * tol)
invecs = [
v2,
v2,
v3,
v3,
v3,
v4,
v4,
v4,
v4,
v5,
v5,
v5,
v5,
v5,
]
for ncmp, ncmpalt, v in zip(outputs0, outputs1, invecs):
tape0.backward(loss=ncmp)
tape1.backward(loss=ncmpalt)
assert_np_equal(tape0.gradients[v].numpy()[0], tape1.gradients[v].numpy()[0], tol=10 * tol)
tape0.zero()
tape1.zero()
def test_crossproduct(test, device, dtype, register_kernels=False):
np.random.seed(123)
tol = {
np.float16: 5.0e-3,
np.float32: 1.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
vec3 = wp.types.vector(length=3, dtype=wptype)
def check_cross(
s3: wp.array(dtype=vec3),
v3: wp.array(dtype=vec3),
c0: wp.array(dtype=wptype),
c1: wp.array(dtype=wptype),
c2: wp.array(dtype=wptype),
):
c = wp.cross(s3[0], v3[0])
# multiply outputs by 2 so we've got something to backpropagate:
c0[0] = wptype(2) * c[0]
c1[0] = wptype(2) * c[1]
c2[0] = wptype(2) * c[2]
kernel = getkernel(check_cross, suffix=dtype.__name__)
if register_kernels:
return
s3 = wp.array(randvals((1, 3), dtype), dtype=vec3, requires_grad=True, device=device)
v3 = wp.array(randvals((1, 3), dtype), dtype=vec3, requires_grad=True, device=device)
c0 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
c1 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
c2 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
s3,
v3,
],
outputs=[c0, c1, c2],
device=device,
)
result = 2 * np.cross(s3.numpy(), v3.numpy())[0]
assert_np_equal(c0.numpy()[0], result[0], tol=10 * tol)
assert_np_equal(c1.numpy()[0], result[1], tol=10 * tol)
assert_np_equal(c2.numpy()[0], result[2], tol=10 * tol)
if dtype in np_float_types:
# c.x = sy vz - sz vy
# c.y = sz vx - sx vz
# c.z = sx vy - sy vx
# ( d/dsx d/dsy d/dsz )c.x = ( 0 vz -vy )
# ( d/dsx d/dsy d/dsz )c.y = ( -vz 0 vx )
# ( d/dsx d/dsy d/dsz )c.z = ( vy -vx 0 )
# ( d/dvx d/dvy d/dvz )c.x = (0 -sz sy)
# ( d/dvx d/dvy d/dvz )c.y = (sz 0 -sx)
# ( d/dvx d/dvy d/dvz )c.z = (-sy sx 0)
tape.backward(loss=c0)
assert_np_equal(
tape.gradients[s3].numpy(), 2.0 * np.array([0, v3.numpy()[0, 2], -v3.numpy()[0, 1]]), tol=10 * tol
)
assert_np_equal(
tape.gradients[v3].numpy(), 2.0 * np.array([0, -s3.numpy()[0, 2], s3.numpy()[0, 1]]), tol=10 * tol
)
tape.zero()
tape.backward(loss=c1)
assert_np_equal(
tape.gradients[s3].numpy(), 2.0 * np.array([-v3.numpy()[0, 2], 0, v3.numpy()[0, 0]]), tol=10 * tol
)
assert_np_equal(
tape.gradients[v3].numpy(), 2.0 * np.array([s3.numpy()[0, 2], 0, -s3.numpy()[0, 0]]), tol=10 * tol
)
tape.zero()
tape.backward(loss=c2)
assert_np_equal(
tape.gradients[s3].numpy(), 2.0 * np.array([v3.numpy()[0, 1], -v3.numpy()[0, 0], 0]), tol=10 * tol
)
assert_np_equal(
tape.gradients[v3].numpy(), 2.0 * np.array([-s3.numpy()[0, 1], s3.numpy()[0, 0], 0]), tol=10 * tol
)
tape.zero()
def test_minmax(test, device, dtype, register_kernels=False):
np.random.seed(123)
# \TODO: not quite sure why, but the numbers are off for 16 bit float
# on the cpu (but not cuda). This is probably just the sketchy float16
# arithmetic I implemented to get all this stuff working, so
# hopefully that can be fixed when we do that correctly.
tol = {
np.float16: 1.0e-2,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
vec2 = wp.types.vector(length=2, dtype=wptype)
vec3 = wp.types.vector(length=3, dtype=wptype)
vec4 = wp.types.vector(length=4, dtype=wptype)
vec5 = wp.types.vector(length=5, dtype=wptype)
# \TODO: Also not quite sure why: this kernel compiles incredibly
# slowly though...
def check_vec_min_max(
a: wp.array(dtype=wptype, ndim=2),
b: wp.array(dtype=wptype, ndim=2),
mins: wp.array(dtype=wptype, ndim=2),
maxs: wp.array(dtype=wptype, ndim=2),
):
for i in range(10):
# multiplying by 2 so we've got something to backpropagate:
a2read = vec2(a[i, 0], a[i, 1])
b2read = vec2(b[i, 0], b[i, 1])
c2 = wptype(2) * wp.min(a2read, b2read)
d2 = wptype(2) * wp.max(a2read, b2read)
a3read = vec3(a[i, 2], a[i, 3], a[i, 4])
b3read = vec3(b[i, 2], b[i, 3], b[i, 4])
c3 = wptype(2) * wp.min(a3read, b3read)
d3 = wptype(2) * wp.max(a3read, b3read)
a4read = vec4(a[i, 5], a[i, 6], a[i, 7], a[i, 8])
b4read = vec4(b[i, 5], b[i, 6], b[i, 7], b[i, 8])
c4 = wptype(2) * wp.min(a4read, b4read)
d4 = wptype(2) * wp.max(a4read, b4read)
a5read = vec5(a[i, 9], a[i, 10], a[i, 11], a[i, 12], a[i, 13])
b5read = vec5(b[i, 9], b[i, 10], b[i, 11], b[i, 12], b[i, 13])
c5 = wptype(2) * wp.min(a5read, b5read)
d5 = wptype(2) * wp.max(a5read, b5read)
mins[i, 0] = c2[0]
mins[i, 1] = c2[1]
mins[i, 2] = c3[0]
mins[i, 3] = c3[1]
mins[i, 4] = c3[2]
mins[i, 5] = c4[0]
mins[i, 6] = c4[1]
mins[i, 7] = c4[2]
mins[i, 8] = c4[3]
mins[i, 9] = c5[0]
mins[i, 10] = c5[1]
mins[i, 11] = c5[2]
mins[i, 12] = c5[3]
mins[i, 13] = c5[4]
maxs[i, 0] = d2[0]
maxs[i, 1] = d2[1]
maxs[i, 2] = d3[0]
maxs[i, 3] = d3[1]
maxs[i, 4] = d3[2]
maxs[i, 5] = d4[0]
maxs[i, 6] = d4[1]
maxs[i, 7] = d4[2]
maxs[i, 8] = d4[3]
maxs[i, 9] = d5[0]
maxs[i, 10] = d5[1]
maxs[i, 11] = d5[2]
maxs[i, 12] = d5[3]
maxs[i, 13] = d5[4]
kernel = getkernel(check_vec_min_max, suffix=dtype.__name__)
output_select_kernel = get_select_kernel2(wptype)
if register_kernels:
return
a = wp.array(randvals((10, 14), dtype), dtype=wptype, requires_grad=True, device=device)
b = wp.array(randvals((10, 14), dtype), dtype=wptype, requires_grad=True, device=device)
mins = wp.zeros((10, 14), dtype=wptype, requires_grad=True, device=device)
maxs = wp.zeros((10, 14), dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[a, b], outputs=[mins, maxs], device=device)
assert_np_equal(mins.numpy(), 2 * np.minimum(a.numpy(), b.numpy()), tol=tol)
assert_np_equal(maxs.numpy(), 2 * np.maximum(a.numpy(), b.numpy()), tol=tol)
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
if dtype in np_float_types:
for i in range(10):
for j in range(14):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[a, b], outputs=[mins, maxs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[mins, i, j], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(a.numpy())
expected[i, j] = 2 if (a.numpy()[i, j] < b.numpy()[i, j]) else 0
assert_np_equal(tape.gradients[a].numpy(), expected, tol=tol)
expected[i, j] = 2 if (b.numpy()[i, j] < a.numpy()[i, j]) else 0
assert_np_equal(tape.gradients[b].numpy(), expected, tol=tol)
tape.zero()
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[a, b], outputs=[mins, maxs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[maxs, i, j], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(a.numpy())
expected[i, j] = 2 if (a.numpy()[i, j] > b.numpy()[i, j]) else 0
assert_np_equal(tape.gradients[a].numpy(), expected, tol=tol)
expected[i, j] = 2 if (b.numpy()[i, j] > a.numpy()[i, j]) else 0
assert_np_equal(tape.gradients[b].numpy(), expected, tol=tol)
tape.zero()
def test_equivalent_types(test, device, dtype, register_kernels=False):
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
# vector types
vec2 = wp.types.vector(length=2, dtype=wptype)
vec3 = wp.types.vector(length=3, dtype=wptype)
vec4 = wp.types.vector(length=4, dtype=wptype)
vec5 = wp.types.vector(length=5, dtype=wptype)
# vector types equivalent to the above
vec2_equiv = wp.types.vector(length=2, dtype=wptype)
vec3_equiv = wp.types.vector(length=3, dtype=wptype)
vec4_equiv = wp.types.vector(length=4, dtype=wptype)
vec5_equiv = wp.types.vector(length=5, dtype=wptype)
# declare kernel with original types
def check_equivalence(
v2: vec2,
v3: vec3,
v4: vec4,
v5: vec5,
):
wp.expect_eq(v2, vec2(wptype(1), wptype(2)))
wp.expect_eq(v3, vec3(wptype(1), wptype(2), wptype(3)))
wp.expect_eq(v4, vec4(wptype(1), wptype(2), wptype(3), wptype(4)))
wp.expect_eq(v5, vec5(wptype(1), wptype(2), wptype(3), wptype(4), wptype(5)))
wp.expect_eq(v2, vec2_equiv(wptype(1), wptype(2)))
wp.expect_eq(v3, vec3_equiv(wptype(1), wptype(2), wptype(3)))
wp.expect_eq(v4, vec4_equiv(wptype(1), wptype(2), wptype(3), wptype(4)))
wp.expect_eq(v5, vec5_equiv(wptype(1), wptype(2), wptype(3), wptype(4), wptype(5)))
kernel = getkernel(check_equivalence, suffix=dtype.__name__)
if register_kernels:
return
# call kernel with equivalent types
v2 = vec2_equiv(1, 2)
v3 = vec3_equiv(1, 2, 3)
v4 = vec4_equiv(1, 2, 3, 4)
v5 = vec5_equiv(1, 2, 3, 4, 5)
wp.launch(kernel, dim=1, inputs=[v2, v3, v4, v5], device=device)
def test_conversions(test, device, dtype, register_kernels=False):
def check_vectors_equal(
v0: wp.vec3,
v1: wp.vec3,
v2: wp.vec3,
v3: wp.vec3,
):
wp.expect_eq(v1, v0)
wp.expect_eq(v2, v0)
wp.expect_eq(v3, v0)
kernel = getkernel(check_vectors_equal, suffix=dtype.__name__)
if register_kernels:
return
v0 = wp.vec3(1, 2, 3)
# test explicit conversions - constructing vectors from different containers
v1 = wp.vec3((1, 2, 3))
v2 = wp.vec3([1, 2, 3])
v3 = wp.vec3(np.array([1, 2, 3], dtype=dtype))
wp.launch(kernel, dim=1, inputs=[v0, v1, v2, v3], device=device)
# test implicit conversions - passing different containers as vectors to wp.launch()
v1 = (1, 2, 3)
v2 = [1, 2, 3]
v3 = np.array([1, 2, 3], dtype=dtype)
wp.launch(kernel, dim=1, inputs=[v0, v1, v2, v3], device=device)
# Test matrix constructors using explicit type (float16)
# note that these tests are specifically not using generics / closure
# args to create kernels dynamically (like the rest of this file)
# as those use different code paths to resolve arg types which
# has lead to regressions.
@wp.kernel
def test_constructors_explicit_precision():
# construction for custom matrix types
ones = wp.vector(wp.float16(1.0), length=2)
zeros = wp.vector(length=2, dtype=wp.float16)
custom = wp.vector(wp.float16(0.0), wp.float16(1.0))
for i in range(2):
wp.expect_eq(ones[i], wp.float16(1.0))
wp.expect_eq(zeros[i], wp.float16(0.0))
wp.expect_eq(custom[i], wp.float16(i))
# Same as above but with a default (float/int) type
# which tests some different code paths that
# need to ensure types are correctly canonicalized
# during codegen
@wp.kernel
def test_constructors_default_precision():
# construction for custom matrix types
ones = wp.vector(1.0, length=2)
zeros = wp.vector(length=2, dtype=float)
custom = wp.vector(0.0, 1.0)
for i in range(2):
wp.expect_eq(ones[i], 1.0)
wp.expect_eq(zeros[i], 0.0)
wp.expect_eq(custom[i], float(i))
@wp.kernel
def test_vector_mutation(expected: wp.types.vector(length=10, dtype=float)):
v = wp.vector(length=10, dtype=float)
# test element indexing
v[0] = 1.0
for i in range(1, 10):
v[i] = float(i) + 1.0
wp.expect_eq(v, expected)
CONSTANT_LENGTH = wp.constant(10)
# tests that we can use global constants in length keyword argument
# for vector constructor
@wp.kernel
def test_constructors_constant_length():
v = wp.vector(length=(CONSTANT_LENGTH), dtype=float)
for i in range(CONSTANT_LENGTH):
v[i] = float(i)
def register(parent):
devices = get_test_devices()
class TestVec(parent):
pass
add_kernel_test(TestVec, test_constructors_explicit_precision, dim=1, devices=devices)
add_kernel_test(TestVec, test_constructors_default_precision, dim=1, devices=devices)
add_kernel_test(TestVec, test_constructors_constant_length, dim=1, devices=devices)
vec10 = wp.types.vector(length=10, dtype=float)
add_kernel_test(
TestVec,
test_vector_mutation,
dim=1,
inputs=[vec10(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)],
devices=devices,
)
for dtype in np_unsigned_int_types:
add_function_test_register_kernel(
TestVec,
f"test_subtraction_unsigned_{dtype.__name__}",
test_subtraction_unsigned,
devices=devices,
dtype=dtype,
)
for dtype in np_signed_int_types + np_float_types:
add_function_test_register_kernel(
TestVec, f"test_negation_{dtype.__name__}", test_negation, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestVec, f"test_subtraction_{dtype.__name__}", test_subtraction, devices=devices, dtype=dtype
)
for dtype in np_float_types:
add_function_test_register_kernel(
TestVec, f"test_crossproduct_{dtype.__name__}", test_crossproduct, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestVec, f"test_length_{dtype.__name__}", test_length, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestVec, f"test_normalize_{dtype.__name__}", test_normalize, devices=devices, dtype=dtype
)
for dtype in np_scalar_types:
add_function_test(TestVec, f"test_arrays_{dtype.__name__}", test_arrays, devices=devices, dtype=dtype)
add_function_test(TestVec, f"test_components_{dtype.__name__}", test_components, devices=None, dtype=dtype)
add_function_test_register_kernel(
TestVec, f"test_constructors_{dtype.__name__}", test_constructors, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestVec, f"test_anon_type_instance_{dtype.__name__}", test_anon_type_instance, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestVec, f"test_indexing_{dtype.__name__}", test_indexing, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestVec, f"test_equality_{dtype.__name__}", test_equality, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestVec,
f"test_scalar_multiplication_{dtype.__name__}",
test_scalar_multiplication,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestVec,
f"test_scalar_multiplication_rightmul_{dtype.__name__}",
test_scalar_multiplication_rightmul,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestVec, f"test_cw_multiplication_{dtype.__name__}", test_cw_multiplication, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestVec, f"test_scalar_division_{dtype.__name__}", test_scalar_division, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestVec, f"test_cw_division_{dtype.__name__}", test_cw_division, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestVec, f"test_addition_{dtype.__name__}", test_addition, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestVec, f"test_dotproduct_{dtype.__name__}", test_dotproduct, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestVec, f"test_equivalent_types_{dtype.__name__}", test_equivalent_types, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestVec, f"test_conversions_{dtype.__name__}", test_conversions, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestVec, f"test_constants_{dtype.__name__}", test_constants, devices=devices, dtype=dtype
)
# the kernels in this test compile incredibly slowly...
# add_function_test_register_kernel(TestVec, f"test_minmax_{dtype.__name__}", test_minmax, devices=devices, dtype=dtype)
return TestVec
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2, failfast=True)
| warp-main | warp/tests/test_vec.py |
Subsets and Splits